OPTION COLLAPSE TRUE
SPLIT ARGUMENT$ BY " " TO arg$ SIZE amount
IF amount < 2 THEN
PRINT "Usage: ", arg$[0], " <file>"
END
ENDIF
IF NOT(FILEEXISTS(arg$[1])) THEN
PRINT "File ", arg$[1], " not found!"
END 1
END IF
FileSize = FILELEN(arg$[1])
FileData = MEMORY(FileSize+1)
OPEN arg$[1] FOR READING AS myfile
GETBYTE FileData FROM myfile SIZE FileSize
CLOSE FILE myfile
DECLARE newtable[255]
FOR x = 0 TO 254
newtable[x] = (int)PEEK(FileData+x*2)<<8 | (int)PEEK(FileData+x*2+1)&255
NEXT
FileDest = MEMORY(FileSize*2)
pos = 0
FOR x = 508+2 TO FileSize-1
current = PEEK(FileData+x)
IF current < 255 THEN
POKE FileDest+pos, newtable[current]>>8
POKE FileDest+pos+1, newtable[current]&255
INCR pos, 2
ELSE
FOR y = x + 2 TO x + 2 + PEEK(FileData+x+1)-1
POKE FileDest+pos, PEEK(FileData+y)
INCR pos
NEXT
INCR x, 2 + PEEK(FileData+x+1)
ENDIF
NEXT
PRINT "Resulting filesize: ", pos, " bytes. ";
newname$ = LEFT$(arg$[1], INSTRREV(arg$[1], ".")-1)
OPEN newname$ FOR WRITING AS myfile
PUTBYTE FileDest TO myfile SIZE pos
CLOSE FILE myfile
PRINT "File '", arg$[1], "' decompressed from LZ77 and saved as '", newname$, "'."
FREE FileData
FREE FileDest
END