'
' This is an implementation for Run Length Enconding (RLE).
'
' http://en.wikipedia.org/wiki/Run-length_encoding
'
' This type of encoding works good with large amounts of equal bytes, for example with BMP files.
' It does not work good with text files.
' (c) PvE - Oct 2012.
'--------------------------------------------------------------------------------------------'

' Get the separate arguments
OPTION COLLAPSE TRUE
SPLIT ARGUMENT$ BY " " TO arg$ SIZE amount

' Show usage
IF amount < 2 THEN
    PRINT "Usage: ", arg$[0], " <file>"
    END
ENDIF

' Check if the file exists
IF NOT(FILEEXISTS(arg$[1])) THEN
    PRINT "File ", arg$[1], " not found!"
    END 1
END IF

' Get filesize
FileSize = FILELEN(arg$[1])

' Reserve some memory to start with
FileData = MEMORY(FileSize+1)

' Get the file into memory
OPEN arg$[1] FOR READING AS myfile
    GETBYTE FileData FROM myfile SIZE FileSize
CLOSE FILE myfile

' Where to store the decompressed data
memsize = FileSize
FileDest = MEMORY(memsize)

' Initialize
newpos = 0

' Start looping through data
FOR x = 0 TO FileSize-1

    ' Make sure there is enough memory
    IF newpos+y > memsize THEN
        INCR memsize, memsize
        RESIZE FileDest, memsize
    END IF

    ' Get the next indicator
    p = PEEK(FileData+x)

    ' It is diverse data
    IF (p&128) > 0 THEN
        FOR y = 0 TO (p&127)-1
            POKE FileDest+newpos+y, PEEK(FileData+x+1+y)
        NEXT
        INCR newpos, y
        INCR x, (p&127)
    ELSE
        ' It is equal data
        FOR y = 0 TO (p&127)-1
            POKE FileDest+newpos+y, PEEK(FileData+x+1)
        NEXT
        INCR newpos, y
        INCR x
    END IF
NEXT

' Show some statistics
PRINT "Resulting filesize: ", newpos, " bytes. ";

' Determine new name
newname$ = LEFT$(arg$[1], INSTRREV(arg$[1], ".")-1)

' Save compressed data from memory to file
OPEN newname$ FOR WRITING AS myfile
    PUTBYTE FileDest TO myfile SIZE newpos
CLOSE FILE myfile

PRINT "File '", arg$[1], "' decompressed from RLE and saved as '", newname$, "'."

' Free claimed memory
FREE FileData
FREE FileDest

END