8 static unsigned char decode[] = "**etianmsurwdkgohvf*l*pjbxcyzq*";
9 static unsigned char encode[256];
11 static void init(void)
13 for (unsigned i=2; i<sizeof(decode); i++)
22 encode[decode[i]] = y;
23 encode[toupper(decode[i])] = y;
27 static void strencode(unsigned char *dest, unsigned char *src, int spaces)
31 int c = encode[*src++];
45 static void strdecode(unsigned char *dest, unsigned char *src)
49 if (*src != '.' && *src != '-')
55 while (*src == '.' || *src == '-')
56 c = 2*c + (*src++ == '-');
74 static void die(char *msg)
76 fprintf(stderr, "%s\n", msg);
80 static void *xmalloc(unsigned int s)
84 die("Out of memory. All memory.");
88 static void load(char *name)
90 FILE *fi = fopen(name, "r");
92 die("Cannot open dictionary");
93 char buf[256], m[256];
96 while (fgets(buf, sizeof(buf), fi))
98 char *c = strchr(buf, '\n');
101 strencode(m, buf, 0);
108 t->son[i] = xmalloc(sizeof(struct t));
109 memset(t->son[i], 0, sizeof(struct t));
114 struct w *w = xmalloc(sizeof(*w) + strlen(buf));
121 printf("Loaded %d words, built %d nodes\n", cnt, treesize);
124 static char M[MAXLEN+1][MAXLEN+1]; /* M[i][j]==1 if it's possible to cover in[i...N-1] with exactly j words */
126 static void map(char *in, int N)
129 for (int i=N-1; i>=0; i--)
135 t = t->son[in[j++] == '-'];
137 for (int k=0; k<N; k++)
144 static void print(char *buf, char *p, char *in, int i, int N, int j) /* cover in[i...N-1] with exactly j words */
157 t = t->son[in[i++] == '-'];
158 if (t && t->words && M[i][j-1])
159 for (struct w *w = t->words; w; w=w->next)
161 int l = strlen(w->c);
163 print(buf, p+l, in, i, N, j-1);
168 int main(int argc, char **argv)
171 die("Usage: morse <dict> <string>");
175 char *in, mbuf[MAXLEN+1];
176 if (argv[2][0] == '.' || argv[2][0] == '-')
180 strencode(mbuf, argv[2], 0);
182 if (strchr(mbuf, '?'))
183 die("Unable to encode");
189 die("Oops, too long for my memory!");
193 for (int j=1; j<=N; j++)
195 print(buf+1, buf, in, 0, N, j);