From 795a8ecaf5656d299139e2c41fab19573bdac0c6 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Sat, 7 Nov 2026 05:33:00 +0300 Subject: publish --- src/lzw-dec.c | 119 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 src/lzw-dec.c (limited to 'src/lzw-dec.c') diff --git a/src/lzw-dec.c b/src/lzw-dec.c new file mode 100644 index 0000000..e5125dc --- /dev/null +++ b/src/lzw-dec.c @@ -0,0 +1,119 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "config.h" + +FILE *istream; + +uint16_t next_input_code () +{ + static uint8_t buf[3]; + static uint16_t next; + static int i = 0; + + if (i) { + if (next != -1) + i = 0; + return next; + } else { + size_t read; + read = fread (buf, 1, 3, istream); + i = 1; + if (read == 3) { + next = buf[1] >> 4 | buf[2] << 4; + } else if (read == 2) { + next = -1; + } else + return -1; + + return buf[0] | (buf[1] & ((1 << 4) - 1)) << 8; + } +} + +int +main (int argc, char *argv[]) +{ + setlocale (LC_ALL, ""); + + if (argc != 3) { + fprintf (stderr, "Usage: %s {infile} {outfile}\n", basename (argv[0])); + return EXIT_FAILURE; + } + + // initialize dictionary + wchar_t *dict[1 << 11] = { NULL }; + size_t next_code; + for (next_code = 0; next_code < wcslen (ALPHABET); ++next_code) { + dict[next_code] = malloc (2*sizeof (wchar_t)); + dict[next_code][0] = ALPHABET[next_code]; + dict[next_code][1] = L'\0'; + // printf ("%d %ls\n", next_code, dict[next_code]); + } // putchar ('\n'); + + istream = fopen (argv[1], "rb"); + if (istream == NULL) { + perror (NULL); + return EXIT_FAILURE; + } + + FILE *ostream = fopen (argv[2], "w,ccs="CCS); + if (ostream == NULL) { + perror (NULL); + return EXIT_FAILURE; + } + + uint16_t old = next_input_code (); + if (old == -1) { + return EXIT_SUCCESS; + } + uint16_t new; + wchar_t *seq = NULL; + wchar_t wc; + fputws (dict[old], ostream); + while ((new = next_input_code ()) != (uint16_t) -1) { + if (dict[new]) { + size_t new_len = wcslen (dict[new]); + seq = realloc (seq, (new_len + 1)*sizeof (wchar_t)); + wcscpy (seq, dict[new]); + } else { + size_t old_len = wcslen (dict[old]); + seq = realloc (seq, (old_len + 2)*sizeof (wchar_t)); + memcpy (seq, dict[old], old_len*sizeof (wchar_t)); + seq[old_len + 0] = wc; + seq[old_len + 1] = L'\0'; + } + + fputws (seq, ostream); + + wc = seq[0]; + + if (next_code < 1 << 11 - 1) { + size_t old_len = wcslen (dict[old]); + dict[next_code] = malloc ((old_len + 2)*sizeof (wchar_t)); + memcpy (dict[next_code], dict[old], old_len*sizeof (wchar_t)); + dict[next_code][old_len + 0] = wc; + dict[next_code][old_len + 1] = L'\0'; + ++next_code; + } + + old = new; + // fflush (stdout); + } // putchar ('\n'); + + if (fclose (istream) == EOF) { + perror (NULL); + return EXIT_FAILURE; + } + if (fclose (ostream) == EOF) { + perror (NULL); + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} -- cgit v1.3.1