1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <wchar.h>
#include <errno.h>
#include <locale.h>
#include <inttypes.h>
#include <libgen.h>
#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;
}
|