chiark / gitweb /
Print sensible error if all trades deselected.
[ypp-sc-tools.db-test.git] / yarrg / ocr.c
1 /*
2  * Core OCR algorithm (first exact bitmap match)
3  */
4 /*
5  *  This is part of ypp-sc-tools, a set of third-party tools for assisting
6  *  players of Yohoho Puzzle Pirates.
7  * 
8  *  Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
9  * 
10  *  This program is free software: you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License as published by
12  *  the Free Software Foundation, either version 3 of the License, or
13  *  (at your option) any later version.
14  * 
15  *  This program is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  * 
20  *  You should have received a copy of the GNU General Public License
21  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  * 
23  *  Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
24  *  are used without permission.  This program is not endorsed or
25  *  sponsored by Three Rings.
26  */
27
28 #include "convert.h"
29
30 typedef struct {
31   Pixcol col;
32   struct DatabaseNode *then;
33 } DatabaseLink;
34
35 typedef struct DatabaseNode {
36   char *str;
37   int nlinks, alinks;
38   unsigned match:1, defined:1, endsword:1, local:1;
39   DatabaseLink *links;
40 } DatabaseNode;
41
42 typedef struct {
43   OcrReader *rd;
44   OcrCellType ct;
45   int w;
46   const Pixcol *cols;
47   int x;
48   unsigned ctxmap;
49 } FindCharArgs;
50 typedef struct {
51   DatabaseNode *match;
52   int rx;
53 } FindCharResults;
54
55 #define FOR_EACH_CONTEXT(EACH)                  \
56   EACH(Word)                                    \
57   EACH(Lower)                                   \
58   EACH(Upper)                                   \
59   EACH(Digit)
60
61 #define FEC_ENUM(Context) ct_##Context,
62 #define FEC_BIT(Context) ctf_##Context = 1 << ct_##Context,
63 enum {
64   FOR_EACH_CONTEXT(FEC_ENUM)
65   FOR_EACH_CONTEXT(FEC_BIT)
66 };
67
68 #define FEC_STRINGS(Context) #Context,
69 static const char *context_names[]= { FOR_EACH_CONTEXT(FEC_STRINGS) };
70
71 struct OcrCellTypeInfo {
72   /* bitmaps of indices into context_names: */
73   unsigned initial, nextword, midword;
74   int space_spaces;
75   const char *name;
76   int (*findchar_select)(const FindCharArgs *fca,
77                          const FindCharResults results[]);
78 };
79
80 #define NCONTEXTS (sizeof(context_names)/sizeof(context_names[0]))
81
82 struct OcrReader {
83   int h;
84   DatabaseNode contexts[NCONTEXTS];
85   char *result;
86   int lresult, aresult;
87   OcrResultGlyph *results;
88   int aresults, nresults;
89 };
90
91 DEBUG_DEFINE_DEBUGF(ocr)
92
93 #define FGETSLINE (dbfile_getsline(lbuf,sizeof(lbuf),__FILE__,__LINE__))
94
95 static void cleardb_node(DatabaseNode *n) {
96   int i;
97   free(n->str); n->str=0;
98   n->defined=n->match=n->endsword= 0;
99   for (i=0; i<n->nlinks; i++)
100     cleardb_node(n->links[i].then);
101 }
102
103 static void readdb1(OcrReader *rd, const char *which, int local);
104
105 static void readdb(OcrReader *rd) {
106   int ctxi;
107   
108   for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
109     cleardb_node(&rd->contexts[ctxi]);
110
111   readdb1(rd, "master", 0);
112   readdb1(rd, "local",  1);
113 }
114
115 static void readdb1(OcrReader *rd, const char *which, int local) {
116   int nchrs;
117   DatabaseNode *current, *additional;
118   char chrs[100];
119   Pixcol cv;
120   int j,ctxi;
121   int h, endsword;
122   char lbuf[100];
123
124   char *dbfname= masprintf("%s/_%s-char%d.txt",
125                            get_vardir(), which, rd->h);
126   
127   if (!dbfile_open(dbfname))
128     goto x;
129
130   if (local)
131     o_flags |= ff_charset_havelocal;
132
133   FGETSLINE;
134   dbassert(!strcmp(lbuf,"# ypp-sc-tools pctb font v3 depth=" STRING(AADEPTH)));
135
136   dbassert( dbfile_scanf("%d", &h) == 1);
137   dbassert(h==rd->h);
138
139   for (;;) {
140     FGETSLINE;
141     if (!lbuf[0] || lbuf[0]=='#') continue;
142     if (!strcmp(lbuf,".")) break;
143
144     for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
145       if (!strcmp(lbuf,context_names[ctxi]))
146         goto found_ctx;
147     /* not found, just skip */
148     for (;;) { FGETSLINE; if (!lbuf[0]) break; }
149     continue;
150
151   found_ctx:
152     for (nchrs=0;;) {
153       int c= fgetc(dbfile); sysassert(!ferror(dbfile)); dbassert(c!=EOF);
154       if (c=='\n') break; /* forces no match */
155       dbassert(nchrs<sizeof(chrs));
156       chrs[nchrs++]= c;
157     }
158     endsword= 0;
159     if (nchrs>0 && chrs[nchrs-1]==' ') {
160       endsword= 1;
161       nchrs--;
162     }
163
164     current= &rd->contexts[ctxi];
165     for (;;) {
166       FGETSLINE;
167       if (!lbuf[0]) { dbassert(current != &rd->contexts[ctxi]); break; }
168       dbassert( strlen(lbuf) == rd->h );
169       FILLZERO(cv);
170       int y;
171       for (y=0; y<h; y++) {
172         char pb[2];
173         pb[0]= lbuf[y];
174         pb[1]= 0;
175         char *ep;
176         unsigned pv= strtoul(pb,&ep,16);  dbassert(!*ep);
177         pixcol_p_add(&cv, y, pv);
178       }
179       
180       for (j=0; j<current->nlinks; j++)
181         if (!pixcol_cmp(&cv, &current->links[j].col)) {
182           current= current->links[j].then;
183           goto found_link;
184         }
185
186       additional= mmalloc(sizeof(*additional));
187       additional->str= 0;
188       additional->defined= 0;
189       additional->match= 0;
190       additional->endsword= 0;
191       additional->nlinks= additional->alinks= 0;
192       additional->links= 0;
193       if (current->nlinks==current->alinks) {
194         current->alinks++;
195         current->alinks<<=1;
196         current->links= mrealloc(current->links,
197                                  sizeof(*current->links) * current->alinks);
198       }
199       current->links[current->nlinks].col= cv;
200       current->links[current->nlinks].then= additional;
201       current->nlinks++;
202       current= additional;
203
204     found_link:;
205     }
206
207     if (!current->defined) {
208       free(current->str);
209       current->str= 0;
210       current->defined= 1;
211       current->match= 0;
212       current->local= local;
213
214       if (nchrs) {
215         current->str= mmalloc(nchrs+1);
216         memcpy(current->str, chrs, nchrs);
217         current->str[nchrs]= 0;
218         current->match= 1;
219         current->endsword= endsword;
220       }
221     }
222   }
223  x:
224   dbfile_close();
225   free(dbfname);
226 }
227
228 typedef struct Rejection Rejection;
229 struct Rejection {
230   struct Rejection *next;
231   const char *fname;
232   int lno;
233   pcre *re;
234 };
235
236 Rejection *rejections;
237
238 static void load_rejections(const char *which) {
239   char lbuf[1000];
240   char *fname= masprintf("%s/_%s-reject.txt", get_vardir(), which);
241   int c, lno=0;
242   Rejection *rej;
243   
244   if (!dbfile_open(fname)) { free(fname); return; }
245   
246   while ((c= fgetc(dbfile))!=EOF) {
247     ungetc(c,dbfile);
248     lno++;
249     dbfile_getsline(lbuf,sizeof(lbuf),fname,lno);
250
251     if (!lbuf[0] || isspace(lbuf[0] || lbuf[0]=='#'))
252       continue;
253
254     rej= mmalloc(sizeof(*rej));
255     rej->next= rejections;
256     rej->fname= fname;
257     rej->lno= lno;
258
259     const char *err;
260     int erroffset;
261     rej->re= pcre_compile(lbuf, PCRE_NO_AUTO_CAPTURE|PCRE_UTF8,
262                           &err, &erroffset, 0);
263     if (!rej->re) {
264       char *what= masprintf("invalid regexp at offset %d: %s\n",
265                             erroffset, err);
266       dbfile_assertfail(fname, lno, what);
267     }
268     debugf("OCR LOADED REJECTION %s:%d `%s' %p\n", fname,lno, lbuf, rej->re);
269
270     rejections= rej;
271   }
272   sysassert(feof(dbfile));
273   dbfile_close();
274 }
275   
276 static int should_reject(OcrReader *rd) {
277   static int rejections_loaded;
278   int ovector[30];
279
280   if (!rejections_loaded) {
281     if (o_flags & ff_dict_fetch)
282       fetch_with_rsync("reject");
283     load_rejections("master");
284     load_rejections("local");
285     rejections_loaded=1;
286   }
287
288   debugf("[OCR REJECTION `%s'%d", rd->result, rd->lresult);
289   Rejection *rej;
290   for (rej=rejections; rej; rej=rej->next) {
291     debugf(" (%p)", rej);
292
293     int res= pcre_exec(rej->re, 0, rd->result,rd->lresult, 0,
294                        0, ovector, ARRAYSIZE(ovector));
295     if (res==PCRE_ERROR_NOMATCH) continue;
296     sysassert(res>0);
297
298     debugf(" MATCH]\n");
299     fprintf(stderr,"Rejecting OCR result `%s' (due to %s:%d)\n",
300             rd->result, rej->fname,rej->lno);
301     return 1;
302   }
303   debugf(" OK]");
304   return 0;
305 }
306
307 static void cu_pr_ctxmap(FILE *resolver, unsigned ctxmap) {
308   fprintf(resolver,"{");
309   const char *spc="";
310   int ctxi;
311   for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
312     if (!(ctxmap & (1u << ctxi))) continue;
313     fprintf(resolver,"%s%s",spc,context_names[ctxi]);
314     spc=" ";
315   }
316   fprintf(resolver,"}");
317 }
318
319 static void callout_unknown(OcrReader *rd, int w, const Pixcol cols[],
320                             int unk_l, int unk_r, unsigned unk_ctxmap) {
321   int c,i, x,y;
322   const OcrResultGlyph *s;
323   const char *p;
324
325   FILE *resolver= resolve_start();
326   if (!resolver ||
327       !((o_flags & ff_charset_edit) ||
328         ((o_flags & ff_charset_allowedit) &&
329          (o_flags & ff_charset_havelocal))))
330     fatal("OCR failed - unrecognised characters or ligatures.\n"
331           "Character set database needs to be updated or augmented.\n"
332           "See README.charset.\n");
333   
334   fprintf(resolver,
335           "char\n"
336           "%d %d ",unk_l,unk_r);
337   cu_pr_ctxmap(resolver,unk_ctxmap);
338   for (i=0, s=rd->results; i<rd->nresults; i++, s++) {
339     if (!strcmp(s->s," ")) continue;
340     fprintf(resolver," %d %d ",s->l,s->r);
341     cu_pr_ctxmap(resolver, 1u << s->match);
342     fprintf(resolver," ");
343     cu_pr_ctxmap(resolver, s->ctxmap);
344     fprintf(resolver," ");
345     for (p=s->s; (c= *p); p++) {
346       if (c=='\\') fprintf(resolver,"\\%c",c);
347       else if (c>=33 && c<=126) fputc(c,resolver);
348       else fprintf(resolver,"\\x%02x",(unsigned char)c);
349     }
350   }
351   fputc('\n',resolver);
352
353   fprintf(resolver,
354           "P2\n%d %d %d\n", w, rd->h, AAMAXVAL);
355   for (y=0; y<rd->h; y++) {
356     for (x=0; x<w; x++)
357       fprintf(resolver, " %d", pixcol_p_get(&cols[x], y));
358     fputc('\n',resolver);
359   }
360
361   resolve_finish();
362   readdb(rd);
363 }
364
365 static void add_result(OcrReader *rd, const char *s, int l, int r,
366                        int match, unsigned ctxmap) {
367   if (rd->nresults >= rd->aresults) {
368     rd->aresults++; rd->aresults<<=1;
369     rd->results= mrealloc(rd->results, sizeof(*rd->results)*rd->aresults);
370   }
371   rd->results[rd->nresults].s= s;
372   rd->results[rd->nresults].l= l;
373   rd->results[rd->nresults].r= r;
374   rd->results[rd->nresults].match= match;
375   rd->results[rd->nresults].ctxmap= ctxmap;
376   rd->nresults++;
377
378   if (!s) return; /* just the sentinel for the caller */
379
380   int sl= strlen(s);
381   int newlresult= rd->lresult + sl;
382   if (newlresult >= rd->aresult) {
383     rd->aresult= (newlresult << 1) + 1;
384     rd->result= mrealloc(rd->result, rd->aresult);
385   }
386   memcpy(rd->result + rd->lresult, s, sl);
387   rd->lresult= newlresult;
388   rd->result[rd->lresult]= 0;
389 }
390
391
392 static DatabaseNode *findchar_1ctx(const FindCharArgs *fca,
393                                    DatabaseNode *start, int *matchx_r) {
394   DatabaseNode *current= start;
395   DatabaseNode *bestmatch= 0;
396   int i;
397   int x= fca->x;
398
399   for (;;) {
400     if (DEBUGP(ocr)) debug_flush();
401     debugf(" | x=%d",x);
402     if (x > fca->w) break;
403     Pixcol cv= fca->cols[x];
404     debugf(" cv="PIXCOL_PRFMT, PIXCOL_PRVAL(cv));
405     for (i=0; i<current->nlinks; i++)
406       if (!pixcol_cmp(&cv, &current->links[i].col))
407         goto found;
408     /* not found */
409     debugf(" ?");
410     break;
411
412   found:
413     current= current->links[i].then;
414     if (current->match) {
415       debugf(" \"%s\"%s",current->str,current->endsword?"_":"");
416       bestmatch= current;
417       *matchx_r= x;
418     } else {
419       debugf(" ...");
420     }
421
422     x++;
423   }
424   return bestmatch;
425 }  
426
427 static DatabaseNode *findchar(const FindCharArgs *fca,
428                               int *match_rx, int *match_rctxi) {
429   FindCharResults results[NCONTEXTS];
430   int ctxi, match=-1, nmatches=0;
431
432   debugf("OCR  lx=%d ct_state=%x  ", fca->x, fca->ctxmap);
433   for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
434     results[ctxi].match= 0;
435     if (!(fca->ctxmap & (1u << ctxi))) continue;
436     debugf(" || %s",context_names[ctxi]);
437
438     results[ctxi].match= findchar_1ctx(fca, &fca->rd->contexts[ctxi],
439                                        &results[ctxi].rx);
440     if (!results[ctxi].match) continue;
441
442     match= ctxi;
443     nmatches++;
444   }
445   if (nmatches==1) {
446     debugf(" unique");
447   } else {
448     debugf(" ambiguous");
449     match= !fca->ct->findchar_select ? -1 :
450       fca->ct->findchar_select(fca,results);
451     debugf(" resolved %s", match<0 ? "<none>" : context_names[match]);
452   }
453   if (match<0)
454     return 0;
455   
456   *match_rx= results[match].rx;
457   if (match_rctxi) *match_rctxi= match;
458   return results[match].match;
459 }
460
461 static int findchar_select_text(const FindCharArgs *fca,
462                                 const FindCharResults results[]) {
463   
464   dbassert(! results[ct_Digit].match ); /* digits are supposedly unambiguous */
465
466   switch (fca->ctxmap) {
467
468 #define RETURN_IF_LONGER(this,that) do{                 \
469     if (results[ct_##this].rx > results[ct_##that].rx)  \
470        return ct_##this;                                \
471   }while(0)
472
473   case ctf_Digit | ctf_Upper | ctf_Lower | ctf_Word:
474     /* Start of word.  Prefer Word match; failing that, take the longest */
475     if (results[ct_Word].match) return ct_Word;
476     RETURN_IF_LONGER(Lower,Upper);
477     RETURN_IF_LONGER(Upper,Lower);
478     break;
479
480   case ctf_Digit | ctf_Upper | ctf_Lower:
481     /* Mid-word.  Prefer longer match; failing that, match lower. */
482     RETURN_IF_LONGER(Upper,Lower);
483     return ct_Lower;
484   }
485
486   /* oh well */
487   return -1;
488 }
489
490 const struct OcrCellTypeInfo ocr_celltype_number= {
491   ctf_Digit, ctf_Digit, ctf_Digit,
492   .space_spaces= 5,
493   .name= "number",
494   .findchar_select= 0
495 };
496 const struct OcrCellTypeInfo ocr_celltype_text= {
497   .initial=  ctf_Digit | ctf_Upper,
498   .nextword= ctf_Digit | ctf_Upper | ctf_Lower | ctf_Word,
499   .midword=  ctf_Digit | ctf_Upper | ctf_Lower,
500   .space_spaces= 4,
501   .name= "text",
502   .findchar_select= findchar_select_text
503 };
504
505
506 const char *ocr_celltype_name(OcrCellType ct) { return ct->name; }
507
508 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w,
509                     const Pixcol cols[]) {
510   int nspaces;
511   int x;
512
513   FindCharArgs fca;
514   fca.rd= rd;
515   fca.ct= ct;
516   fca.w= w;
517   fca.cols= cols;
518   fca.x= -1;
519
520  restart:
521
522   nspaces=- w;
523   fca.ctxmap= ct->initial;
524   rd->nresults=0;
525   rd->lresult=0;
526   rd->result[0]=0;
527   debugf("OCR h=%d w=%d",rd->h,w);
528   for (x=0; x<w; x++) debugf(" "PIXCOL_PRFMT, PIXCOL_PRVAL(cols[x]));
529   debugf("\n");
530   debug_flush();
531
532   x=0;
533   for (;;) {
534     if (DEBUGP(ocr)) debug_flush();
535     /* skip spaces */
536     if (x>=w)
537       break;
538
539     if (!pixcol_nonzero(&cols[x])) {
540       nspaces++;
541       x++;
542       if (nspaces == ct->space_spaces) {
543         debugf("OCR  x=%x nspaces=%d space\n",x,nspaces);
544         fca.ctxmap= ct->nextword;
545       }
546       continue;
547     }
548
549     /* something here, so we need to add the spaces */
550     if (nspaces >= ct->space_spaces)
551       add_result(rd," ",x-nspaces,x+1,-1,0);
552     nspaces=0;
553
554     fca.x= x;
555
556     int match_rx=-1;
557     int match_ctxi=-1;
558     DatabaseNode *match= findchar(&fca, &match_rx, &match_ctxi);
559     
560     if (match) {
561       debugf(" || YES");
562       add_result(rd, match->str, x, match_rx, match_ctxi, fca.ctxmap);
563       if (should_reject(rd)) {
564         callout_unknown(rd, w,cols, match_rx+1,match_rx, 0);
565         goto restart;
566       }
567       x= match_rx+1;
568       if (match->match) fca.ctxmap= ct->midword;
569       else debugf(" (empty)");
570       if (match->endsword) {
571         nspaces= ct->space_spaces;
572         debugf("_");
573         fca.ctxmap= ct->nextword;
574       }
575       debugf("\n");
576     } else {
577       int rx;
578       debugf(" || UNKNOWN");
579       for (rx=x; rx<w && pixcol_nonzero(&cols[rx]); rx++);
580       debugf(" x=%d ctxmap=%x %d..%d\n",x, fca.ctxmap, x,rx);
581       debug_flush();
582       callout_unknown(rd, w,cols, x,rx-1, fca.ctxmap);
583       goto restart;
584     }
585
586   }
587   add_result(rd, 0,-1,-1,-1,0);
588   debugf("OCR  finished %d glyphs\n",rd->nresults);
589   debug_flush();
590   return rd->results;
591 }
592
593 OcrReader *ocr_init(int h) {
594   OcrReader *rd;
595
596   assert(h <= OCR_MAX_H);
597
598   if (o_flags & ff_dict_fetch) {
599     char *fetchfile= masprintf("char%d",h);
600     fetch_with_rsync(fetchfile);
601     free(fetchfile);
602   }
603
604   rd= mmalloc(sizeof(*rd));
605   memset(rd,0,sizeof(*rd));
606
607   rd->h= h;
608
609   rd->aresult= 10;
610   rd->result= mmalloc(rd->aresult);
611
612   readdb(rd);
613   return rd;
614 }
615
616 /*---------- character set dump ----------*/
617
618 static void show_recurse(const DatabaseNode *t, int *count,
619                          const DatabaseNode **store_ary) {
620   if (t->defined) {
621     if (store_ary) store_ary[*count]= t;
622     (*count)++;
623   }
624   int l;
625   for (l=0; l<t->nlinks; l++)
626     show_recurse(t->links[l].then, count,store_ary);
627 }
628
629 static int show_char_compar(const void *av, const void *bv) {
630   const DatabaseNode *const *ap= av;  const DatabaseNode *a= *ap;
631   const DatabaseNode *const *bp= bv;  const DatabaseNode *b= *bp;
632   return strcmp(a->str, b->str) ?:
633     ((int)a->match -    (int)b->match) ?:
634     ((int)a->endsword - (int)b->endsword) ?:
635     ((int)a->local -    (int)b->local) ?:
636     0;
637 }
638
639 void ocr_showcharsets(void) {
640   DIR *d;
641   struct dirent *de;
642   char found[OCR_MAX_H];
643   pcre *fnpat;
644   int matchvec[10];
645   char hbuf[10];
646   const char *pcre_err;
647   int pcre_erroffset;
648
649   memset(found,0,sizeof(found));
650   
651   fnpat= pcre_compile("_(?:master|local)\\-char([1-9]\\d{0,2})\\.txt$",
652                       PCRE_ANCHORED|PCRE_DOLLAR_ENDONLY,
653                       &pcre_err,&pcre_erroffset, 0);
654   debugf("pcre_compile %p %s\n",fnpat,pcre_err);
655   assert(fnpat);
656
657   sysassert( d= opendir(get_vardir()) );
658   for (;;) {
659     errno=0; de= readdir(d);  if (!de) break;
660
661     int rer= pcre_exec(fnpat,0, de->d_name,strlen(de->d_name), 0,0,
662                        matchvec,ARRAYSIZE(matchvec));
663     debugf("pcre_exec `%s' => %d\n", de->d_name,rer);
664
665     if (rer==PCRE_ERROR_NOMATCH || rer==PCRE_ERROR_BADUTF8) continue;
666     assert(rer==2);
667
668     rer= pcre_copy_substring(de->d_name,matchvec,rer, 1, hbuf,sizeof(hbuf));
669     debugf("pcre_copy_substring => %d\n", rer);
670     assert(rer>0);
671
672     int h= atoi(hbuf);
673     if (h >= ARRAYSIZE(found)) continue;
674     
675     found[h]= 1;
676   }
677
678   int h;
679   for (h=0; h<ARRAYSIZE(found); h++) {
680     if (!found[h]) continue;
681
682     OcrReader *rd= ocr_init(h); /* we leak this but never mind */
683     progress("");
684
685     int ctxi;
686     for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
687       int nchars= 0;
688       show_recurse(&rd->contexts[ctxi], &nchars, 0);
689       const DatabaseNode **chars= mmalloc(sizeof(*chars) * nchars);
690       int chari= 0;
691       show_recurse(&rd->contexts[ctxi], &chari, chars);
692       assert(chari==nchars);
693       qsort(chars, nchars, sizeof(*chars), show_char_compar);
694
695       int local;
696       for (local=0; local<2; local++) {
697         printf("%2d %-6s %-6s ", h, context_names[ctxi],
698                local?"local":"master");
699         for (chari=0; chari<nchars; chari++) {
700           const DatabaseNode *t= chars[chari];
701           static const char accept[]=
702             "abcdefghijklmnopqrstuvwxyz"
703             "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
704             "0123456789" "'!&-+.,>";
705
706           if (t->local != local) continue;
707
708           if (!t->match)
709             printf(" [nomatch]");
710           else if (!t->endsword && strspn(t->str, accept) == strlen(t->str))
711             printf(" %s",t->str);
712           else {
713             printf(" \"");
714             char *p= t->str;
715             int c;
716             while ((c=*p++)) {
717               if (c=='"' || c=='\\') printf("\\%c",c);
718               else if (c>=' ' && c<=126) putchar(c);
719               else printf("\\x%02x", (unsigned char)c);
720             }
721             if (t->endsword) putchar(' ');
722             putchar('"');
723           }
724         }
725         putchar('\n');
726       }
727       free(chars);
728     }
729   }
730 }