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