#include #include #include #include #include #include #include #include #include #include "config.h" int main (int argc, char *argv[]) { setlocale (LC_ALL, ""); errno = 0; if (argc != 3) { fprintf (stderr, "Usage: %s {infile} {outfile}\n", basename (argv[0])); return EXIT_FAILURE; } // initialize dictionary hcreate ((1 << 12)*6/5); size_t next_code = 0; for (next_code = 0; next_code < wcslen (ALPHABET); ++next_code) { wchar_t wseq[2]; wseq[0] = ALPHABET[next_code]; wseq[1] = L'\0'; char *seq = malloc (3); wcstombs (seq, wseq, 3); ENTRY entry = { .key = seq, .data = (void *)next_code, }; // printf ("%d %s\n", next_code, seq); ENTRY *ep = hsearch (entry, ENTER); } // putchar ('\n'); FILE *istream = fopen (argv[1], "r,ccs="CCS); if (istream == NULL) { perror (NULL); return EXIT_FAILURE; } FILE *ostream = fopen (argv[2], "wb"); if (ostream == NULL) { perror (NULL); return EXIT_FAILURE; } size_t len = 1; wchar_t *wseq = malloc ((len + 1)*sizeof (wchar_t)); char *seq = malloc (2*len + 1); wseq[0] = fgetwc (istream); wseq[1] = L'\0'; uint8_t buf[3] = { 0 }; int bufcount = 0; size_t dictvol = next_code; while (wseq[len - 1] != WEOF) { wchar_t wc = fgetwc (istream); if (wc == WEOF) break; ++len; wseq = realloc (wseq, (len + 1)*sizeof (wchar_t)); seq = realloc (seq, 2*len + 1); wseq[len - 1] = wc; wseq[len] = L'\0'; wcstombs (seq, wseq, 2*len + 1); ENTRY entry = { .key = seq, }; ENTRY *ep = hsearch (entry, FIND); if (ep == NULL) { if (next_code < 1 << 11 - 1) { entry.key = strdup (entry.key); entry.data = (void *) next_code++; hsearch (entry, ENTER); entry.key = seq; dictvol += wcslen (wseq); } wseq[len - 1] = '\0'; wcstombs (seq, wseq, 2*len + 1); ENTRY *ep = hsearch (entry, FIND); // printf ("%llu %s\n", ep->data, ep->key); uint16_t c = (uint16_t) ep->data; if (bufcount) { buf[1] |= (c & ((1 << 4) - 1)) << 4; buf[2] = c >> 4; bufcount = 0; fwrite (buf, 1, 3, ostream); } else { buf[0] = c & ((1 << 8) - 1); buf[1] = c >> 8; bufcount = 1; } wseq[0] = wc; wseq[1] = L'\0'; len = 1; } } wcstombs (seq, wseq, 2*len + 1); ENTRY entry = { .key = seq, }; ENTRY *ep = hsearch (entry, FIND); // printf ("%llu %s\n", ep->data, ep->key); uint16_t c = (uint16_t) ep->data; if (bufcount) { buf[1] |= (c & ((1 << 4) - 1)) << 4; buf[2] = c >> 4; fwrite (buf, 1, 3, ostream); } else { buf[0] = c & ((1 << 8) - 1); buf[1] = c >> 8; fwrite (buf, 1, 2, ostream); } printf ("Coding cost: %.2f\n", (float) dictvol/next_code); if (fclose (istream) == EOF) { perror (NULL); return EXIT_FAILURE; } if (fclose (ostream) == EOF) { perror (NULL); return EXIT_FAILURE; } return EXIT_SUCCESS; }