uxn-utils/cli/lz/ulzdec.c

54 lines
1.2 KiB
C
Raw Normal View History

2023-11-15 15:06:28 -05:00
#include <stdio.h>
#include <stdlib.h>
/* cc ulzdec.c -o ulzdec && ./ulzdec compressed.bin */
static int
error(const char *name, const char *msg)
{
fprintf(stderr, "%s: %s\n", name, msg);
return 0;
}
2023-11-15 17:21:05 -05:00
char *mem, *ptr;
2023-11-15 19:18:03 -05:00
int
2023-11-15 17:35:57 -05:00
decode_ulz(FILE *src)
2023-11-15 15:06:28 -05:00
{
2023-11-15 17:35:57 -05:00
char c, *copy;
2023-11-15 17:21:05 -05:00
short i, length;
2023-11-15 19:18:03 -05:00
ptr = mem = malloc(0x10000);
2023-11-15 17:21:05 -05:00
while((c = getc(src)) != EOF) {
2023-11-15 19:42:27 -05:00
if(c & 0x80) { /* CPY */
2023-11-15 17:21:05 -05:00
if(c & 0x40)
length = (c & 0x3f) << 8 | getc(src);
else
length = c & 0x3f;
2023-11-15 17:35:57 -05:00
copy = ptr - (getc(src) + 1);
2023-11-15 17:21:05 -05:00
for(i = 0; i < length + 4; i++)
2023-11-15 17:35:57 -05:00
*(ptr++) = *(copy++);
2023-11-15 17:21:05 -05:00
} else /* LIT */
for(i = 0; i < c + 1; i++)
*(ptr++) = getc(src);
2023-11-15 15:06:28 -05:00
}
2023-11-15 19:18:03 -05:00
return ptr - mem;
2023-11-15 15:06:28 -05:00
}
int
main(int argc, char *argv[])
{
2023-11-15 19:18:03 -05:00
int res;
2023-11-15 19:14:41 -05:00
FILE *src, *dst;
if(argv[1][0] == '-' && argv[1][1] == 'v')
2023-11-15 15:06:28 -05:00
return !fprintf(stdout, "Ulzdec - ULZ Decoder, 15 Nov 2023.\n");
2023-11-15 19:14:41 -05:00
if(argc != 3)
return error("usage", "ulzdec [-v] a.ulz b.bin");
2023-11-15 15:06:28 -05:00
if(!(src = fopen(argv[1], "rb")))
2023-11-15 19:14:41 -05:00
return !error("Invalid input file", argv[1]);
2023-11-15 19:18:03 -05:00
res = decode_ulz(src);
2023-11-15 19:14:41 -05:00
if(!(dst = fopen(argv[2], "wb")))
return !error("Invalid output file", argv[1]);
2023-11-15 19:18:03 -05:00
fwrite(mem, res, 1, dst);
printf("Decompressed %s -> %s(%d bytes).\n", argv[1], argv[2], res);
2023-11-15 15:06:28 -05:00
return 0;
}