chiark / gitweb /
make AADEPTH configurable
[ypp-sc-tools.db-live.git] / pctb / ocr.c
index 314a8294bea8b9c7db56bda9d6d5fa259159a7bc..8d1b88bbf1f20f35e992c82cbf357ecb1385800b 100644 (file)
 /*
-  */
+ * Core OCR algorithm (first exact bitmap match)
+ */
+/*
+ *  This is part of ypp-sc-tools, a set of third-party tools for assisting
+ *  players of Yohoho Puzzle Pirates.
+ * 
+ *  Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
+ * 
+ *  This program is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation, either version 3 of the License, or
+ *  (at your option) any later version.
+ * 
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ * 
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ * 
+ *  Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
+ *  are used without permission.  This program is not endorsed or
+ *  sponsored by Three Rings.
+ */
 
 #include "ocr.h"
+#include "convert.h"
 
 typedef struct {
   Pixcol col;
   struct DatabaseNode *then;
 } DatabaseLink;
 
-#define MAXGLYPHCHRS 7
-
 typedef struct DatabaseNode {
-  char s[MAXGLYPHCHRS+1]; /* null-terminated; "" means no match here */
+  char *str;
   int nlinks, alinks;
-  unsigned endsword:1;
+  unsigned match:1, defined:1, endsword:1, local:1;
   DatabaseLink *links;
 } DatabaseNode;
 
-static const char *context_names[]= {
-  "Lower",
-  "Upper",
-  "Digit"
+typedef struct {
+  OcrReader *rd;
+  OcrCellType ct;
+  int w;
+  const Pixcol *cols;
+  int x;
+  unsigned ctxmap;
+} FindCharArgs;
+typedef struct {
+  DatabaseNode *match;
+  int rx;
+} FindCharResults;
+
+#define FOR_EACH_CONTEXT(EACH)                 \
+  EACH(Word)                                   \
+  EACH(Lower)                                  \
+  EACH(Upper)                                  \
+  EACH(Digit)
+
+#define FEC_ENUM(Context) ct_##Context,
+#define FEC_BIT(Context) ctf_##Context = 1 << ct_##Context,
+enum {
+  FOR_EACH_CONTEXT(FEC_ENUM)
+  FOR_EACH_CONTEXT(FEC_BIT)
 };
 
-#define NCONTEXTS (sizeof(context_names)/sizeof(context_names[0]))
+#define FEC_STRINGS(Context) #Context,
+static const char *context_names[]= { FOR_EACH_CONTEXT(FEC_STRINGS) };
+
+struct OcrCellTypeInfo {
+  /* bitmaps of indices into context_names: */
+  unsigned initial, nextword, midword;
+  int space_spaces;
+  const char *name;
+  int (*findchar_select)(const FindCharArgs *fca,
+                        const FindCharResults results[]);
+};
 
-#define SPACE_SPACES 4
+#define NCONTEXTS (sizeof(context_names)/sizeof(context_names[0]))
 
 struct OcrReader {
   int h;
   DatabaseNode contexts[NCONTEXTS];
+  char *result;
+  int lresult, aresult;
   OcrResultGlyph *results;
   int aresults, nresults;
 };
 
-static FILE *resolver;
-static pid_t resolver_pid;
-static int resolver_done;
-
 DEBUG_DEFINE_DEBUGF(ocr)
 
-#define dbassert(x)                                                    \
-  ((x) ? (void)0 :                                                     \
-     fatal("Error in character set database.\n"                                \
-          " Requirement not met: %s:%d: %s", __FILE__,__LINE__, #x))
-
-static void fgetsline(FILE *f, char *lbuf, size_t lbufsz) {
-  errno=0;
-  char *s= fgets(lbuf,lbufsz,f);
-  sysassert(!ferror(f));
-  dbassert(!feof(f));
-  assert(s);
-  int l= strlen(lbuf);
-  dbassert(l>0);  dbassert(lbuf[--l]='\n');
-  lbuf[l]= 0;
-}
-#define FGETSLINE(f,buf) (fgetsline(f,buf,sizeof(buf)))
+#define FGETSLINE (dbfile_getsline(lbuf,sizeof(lbuf),__FILE__,__LINE__))
 
 static void cleardb_node(DatabaseNode *n) {
   int i;
-  n->s[0]= 0;
+  free(n->str); n->str=0;
+  n->defined=n->match=n->endsword= 0;
   for (i=0; i<n->nlinks; i++)
     cleardb_node(n->links[i].then);
 }
 
+static void readdb1(OcrReader *rd, const char *which, int local);
+
 static void readdb(OcrReader *rd) {
+  int ctxi;
+  
+  for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
+    cleardb_node(&rd->contexts[ctxi]);
+
+  readdb1(rd, "master", 0);
+  readdb1(rd, "local",  1);
+}
+
+static void readdb1(OcrReader *rd, const char *which, int local) {
   int nchrs;
   DatabaseNode *current, *additional;
-  char chrs[MAXGLYPHCHRS+1];
+  char chrs[100];
   Pixcol cv;
-  int r,j,ctxi;
+  int j,ctxi;
   int h, endsword;
   char lbuf[100];
-  FILE *db;
-
-  for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
-    cleardb_node(&rd->contexts[ctxi]);
 
-  char *dbfname=0;
-  asprintf(&dbfname,"%s/charset-%d.txt",get_vardir(),rd->h);
-  sysassert(dbfname);
+  char *dbfname= masprintf("%s/#%s-char%d#.txt",
+                          get_vardir(), which, rd->h);
   
-  db= fopen(dbfname,"r");
-  free(dbfname);
-  if (!db) {
-    sysassert(errno==ENOENT);
-    return;
-  }
+  if (!dbfile_open(dbfname))
+    goto x;
 
-  FGETSLINE(db,lbuf);
-  dbassert(!strcmp(lbuf,"# ypp-sc-tools pctb font v1"));
+  if (local)
+    o_flags |= ff_charset_havelocal;
 
-  r= fscanf(db, "%d", &h);
-  dbassert(r==1);
+  FGETSLINE;
+  dbassert(!strcmp(lbuf,"# ypp-sc-tools pctb font v3 depth=" STRING(AADEPTH)));
+
+  dbassert( dbfile_scanf("%d", &h) == 1);
   dbassert(h==rd->h);
 
   for (;;) {
-    FGETSLINE(db,lbuf);
-    if (!lbuf || lbuf[0]=='#') continue;
+    FGETSLINE;
+    if (!lbuf[0] || lbuf[0]=='#') continue;
     if (!strcmp(lbuf,".")) break;
 
     for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
       if (!strcmp(lbuf,context_names[ctxi]))
        goto found_ctx;
     /* not found, just skip */
-    for (;;) { FGETSLINE(db,lbuf); if (!lbuf[0]) break; }
+    for (;;) { FGETSLINE; if (!lbuf[0]) break; }
     continue;
 
   found_ctx:
     for (nchrs=0;;) {
-      int c= fgetc(db); sysassert(!ferror(db)); dbassert(c!=EOF);
-      if (c=='\n') { dbassert(nchrs); break; }
-      dbassert(nchrs<MAXGLYPHCHRS);
-      if (c=='\\') {
-       unsigned cr;
-       c= fgetc(db); sysassert(!ferror(db)); dbassert(c=='x');
-       r= fscanf(db, "%2x", &cr); sysassert(!ferror(db)); dbassert(r==1);
-       assert(cr>0 && cr<=255);
-       c= cr;
-      }
+      int c= fgetc(dbfile); sysassert(!ferror(dbfile)); dbassert(c!=EOF);
+      if (c=='\n') break; /* forces no match */
+      dbassert(nchrs<sizeof(chrs));
       chrs[nchrs++]= c;
     }
     endsword= 0;
-    if (nchrs>1 && chrs[nchrs-1]==' ') {
+    if (nchrs>0 && chrs[nchrs-1]==' ') {
       endsword= 1;
       nchrs--;
     }
-    chrs[nchrs]= 0;
 
     current= &rd->contexts[ctxi];
     for (;;) {
-      FGETSLINE(db,lbuf);
+      FGETSLINE;
       if (!lbuf[0]) { dbassert(current != &rd->contexts[ctxi]); break; }
-      char *ep;
-      cv= strtoul(lbuf,&ep,16);  dbassert(!*ep);
-      dbassert(!(cv & ~((1UL << rd->h)-1)));
+      dbassert( strlen(lbuf) == rd->h );
+      FILLZERO(cv);
+      int y;
+      for (y=0; y<h; y++) {
+       char pb[2];
+       pb[0]= lbuf[y];
+       pb[1]= 0;
+       char *ep;
+       unsigned pv= strtoul(pb,&ep,16);  dbassert(!*ep);
+       pixcol_p_add(&cv, y, pv);
+      }
       
       for (j=0; j<current->nlinks; j++)
-       if (current->links[j].col == cv) {
+       if (!pixcol_cmp(&cv, &current->links[j].col)) {
          current= current->links[j].then;
          goto found_link;
        }
 
       additional= mmalloc(sizeof(*additional));
-      additional->s[0]= 0;
+      additional->str= 0;
+      additional->defined= 0;
+      additional->match= 0;
+      additional->endsword= 0;
       additional->nlinks= additional->alinks= 0;
       additional->links= 0;
       if (current->nlinks==current->alinks) {
@@ -160,15 +205,106 @@ static void readdb(OcrReader *rd) {
     found_link:;
     }
 
-    dbassert(!current->s[0]);
-    strcpy(current->s, chrs);
-    current->endsword= endsword;
+    if (!current->defined) {
+      free(current->str);
+      current->str= 0;
+      current->defined= 1;
+      current->match= 0;
+      current->local= local;
+
+      if (nchrs) {
+       current->str= mmalloc(nchrs+1);
+       memcpy(current->str, chrs, nchrs);
+       current->str[nchrs]= 0;
+       current->match= 1;
+       current->endsword= endsword;
+      }
+    }
   }
-  sysassert(!ferror(db));
-  sysassert(!fclose(db));
+ x:
+  dbfile_close();
+  free(dbfname);
 }
 
-static void cu_pr_ctxmap(unsigned ctxmap) {
+typedef struct Rejection Rejection;
+struct Rejection {
+  struct Rejection *next;
+  const char *fname;
+  int lno;
+  pcre *re;
+};
+
+Rejection *rejections;
+
+static void load_rejections(const char *which) {
+  char lbuf[1000];
+  char *fname= masprintf("%s/#%s-reject#.txt", get_vardir(), which);
+  int c, lno=0;
+  Rejection *rej;
+  
+  if (!dbfile_open(fname)) { free(fname); return; }
+  
+  while ((c= fgetc(dbfile))!=EOF) {
+    ungetc(c,dbfile);
+    lno++;
+    dbfile_getsline(lbuf,sizeof(lbuf),fname,lno);
+
+    if (!lbuf[0] || isspace(lbuf[0] || lbuf[0]=='#'))
+      continue;
+
+    rej= mmalloc(sizeof(*rej));
+    rej->next= rejections;
+    rej->fname= fname;
+    rej->lno= lno;
+
+    const char *err;
+    int erroffset;
+    rej->re= pcre_compile(lbuf, PCRE_NO_AUTO_CAPTURE|PCRE_UTF8,
+                         &err, &erroffset, 0);
+    if (!rej->re) {
+      char *what= masprintf("invalid regexp at offset %d: %s\n",
+                           erroffset, err);
+      dbfile_assertfail(fname, lno, what);
+    }
+    debugf("OCR LOADED REJECTION %s:%d `%s' %p\n", fname,lno, lbuf, rej->re);
+
+    rejections= rej;
+  }
+  sysassert(feof(dbfile));
+  dbfile_close();
+}
+  
+static int should_reject(OcrReader *rd) {
+  static int rejections_loaded;
+  int ovector[30];
+
+  if (!rejections_loaded) {
+    fetch_with_rsync("reject");
+    load_rejections("master");
+    load_rejections("local");
+    rejections_loaded=1;
+  }
+
+  debugf("[OCR REJECTION `%s'%d", rd->result, rd->lresult);
+  Rejection *rej;
+  for (rej=rejections; rej; rej=rej->next) {
+    debugf(" (%p)", rej);
+
+    int res= pcre_exec(rej->re, 0, rd->result,rd->lresult, 0,
+                      0, ovector, ARRAYSIZE(ovector));
+    if (res==PCRE_ERROR_NOMATCH) continue;
+    sysassert(res>0);
+
+    debugf(" MATCH]\n");
+    fprintf(stderr,"Rejecting OCR result `%s' (due to %s:%d)\n",
+           rd->result, rej->fname,rej->lno);
+    return 1;
+  }
+  debugf(" OK]");
+  return 0;
+}
+
+static void cu_pr_ctxmap(FILE *resolver, unsigned ctxmap) {
   fprintf(resolver,"{");
   const char *spc="";
   int ctxi;
@@ -180,43 +316,31 @@ static void cu_pr_ctxmap(unsigned ctxmap) {
   fprintf(resolver,"}");
 }
 
-static void callout_unknown(OcrReader *rd, int w, Pixcol cols[],
+static void callout_unknown(OcrReader *rd, int w, const Pixcol cols[],
                            int unk_l, int unk_r, unsigned unk_ctxmap) {
-  int jobpipe[2],donepipe[2], c,i, x,y;
+  int c,i, x,y;
   const OcrResultGlyph *s;
   const char *p;
-  char cb;
-  Pixcol pv;
+
+  FILE *resolver= resolve_start();
+  if (!resolver ||
+      !((o_flags & ff_charset_edit) ||
+       ((o_flags & ff_charset_allowedit) &&
+        (o_flags & ff_charset_havelocal))))
+    fatal("OCR failed - unrecognised characters or ligatures.\n"
+         "Character set database needs to be updated or augmented.\n"
+         "See README.charset.\n");
   
-  if (!resolver) {
-    sysassert(! pipe(jobpipe) );
-    sysassert(! pipe(donepipe) );
-    resolver_pid= fork();
-    sysassert(resolver_pid!=-1);
-    if (!resolver_pid) {
-      sysassert( dup2(jobpipe[0],0) ==0 );
-      sysassert(! close(jobpipe[1]) );
-      sysassert(! close(donepipe[0]) );
-      /* we know donepipe[1] is >= 4 and we have dealt with all the others
-       * so we aren't in any danger of overwriting some other fd 4: */
-      sysassert( dup2(donepipe[1],4) ==4 );
-      execlp("./show-thing.tcl", "./show-thing.tcl",
-            DEBUGP(callout) ? "--debug" : "--noop-arg",
-            "--automatic-1",
-            (char*)0);
-      sysassert(!"execlp failed");
-    }
-    sysassert(! close(jobpipe[0]) );
-    sysassert(! close(donepipe[1]) );
-    resolver= fdopen(jobpipe[1],"w"); sysassert(resolver);
-    resolver_done= donepipe[0];
-  }
-  fprintf(resolver,"%d %d ",unk_l,unk_r);
-  cu_pr_ctxmap(unk_ctxmap);
+  fprintf(resolver,
+         "char\n"
+         "%d %d ",unk_l,unk_r);
+  cu_pr_ctxmap(resolver,unk_ctxmap);
   for (i=0, s=rd->results; i<rd->nresults; i++, s++) {
     if (!strcmp(s->s," ")) continue;
     fprintf(resolver," %d %d ",s->l,s->r);
-    cu_pr_ctxmap(s->ctxmap);
+    cu_pr_ctxmap(resolver, 1u << s->match);
+    fprintf(resolver," ");
+    cu_pr_ctxmap(resolver, s->ctxmap);
     fprintf(resolver," ");
     for (p=s->s; (c= *p); p++) {
       if (c=='\\') fprintf(resolver,"\\%c",c);
@@ -227,64 +351,19 @@ static void callout_unknown(OcrReader *rd, int w, Pixcol cols[],
   fputc('\n',resolver);
 
   fprintf(resolver,
-         "/* XPM */\n"
-         "static char *t[] = {\n"
-         "/* columns rows colors chars-per-pixel */\n"
-         "\"%d %d 2 1\",\n"
-         "\"  c black\",\n"
-         "\"o c white\",\n",
-         w,rd->h);
-  for (y=0, pv=1; y<rd->h; y++, pv<<=1) {
-    fputc('"',resolver);
+         "P2\n%d %d %d\n", w, rd->h, AAMAXVAL);
+  for (y=0; y<rd->h; y++) {
     for (x=0; x<w; x++)
-      fputc(cols[x] & pv ? 'o' : ' ', resolver);
-    fputs("\",\n",resolver);
-  }
-  fputs("};\n",resolver);
-  sysassert(!ferror(resolver));
-  sysassert(!fflush(resolver));
-
-  sysassert(resolver);
-
-  int r;
-  for (;;) {
-    r= read(resolver_done,&cb,1);
-    if (r==-1) { sysassert(errno==EINTR); continue; }
-    break;
-  }
-
-  if (r==0) {
-    pid_t pid;
-    int st;
-    for (;;) {
-      pid= waitpid(resolver_pid, &st, 0);
-      if (pid==-1) { sysassert(errno==EINTR); continue; }
-      break;
-    }
-    sysassert(pid==resolver_pid);
-    if (WIFEXITED(st)) {
-      if (WEXITSTATUS(st))
-       fatal("character resolver failed with nonzero exit status %d",
-             WEXITSTATUS(st));
-      fclose(resolver);
-      close(resolver_done);
-      resolver= 0;
-    } else if (WIFSIGNALED(st)) {
-      fatal("character resolver died due to signal %s%s",
-           strsignal(WTERMSIG(st)), WCOREDUMP(st)?" (core dumped)":"");
-    } else {
-      fatal("character resolver gave strange wait status %d",st);
-    }
-  } else {
-    assert(r==1);
-    sysassert(cb==0);
+      fprintf(resolver, " %d", pixcol_p_get(&cols[x], y));
+    fputc('\n',resolver);
   }
 
+  resolve_finish();
   readdb(rd);
 }
 
 static void add_result(OcrReader *rd, const char *s, int l, int r,
-                      unsigned ctxmap) {
+                      int match, unsigned ctxmap) {
   if (rd->nresults >= rd->aresults) {
     rd->aresults++; rd->aresults<<=1;
     rd->results= mrealloc(rd->results, sizeof(*rd->results)*rd->aresults);
@@ -292,39 +371,161 @@ static void add_result(OcrReader *rd, const char *s, int l, int r,
   rd->results[rd->nresults].s= s;
   rd->results[rd->nresults].l= l;
   rd->results[rd->nresults].r= r;
+  rd->results[rd->nresults].match= match;
   rd->results[rd->nresults].ctxmap= ctxmap;
   rd->nresults++;
+
+  if (!s) return; /* just the sentinel for the caller */
+
+  int sl= strlen(s);
+  int newlresult= rd->lresult + sl;
+  if (newlresult >= rd->aresult) {
+    rd->aresult= (newlresult << 1) + 1;
+    rd->result= mrealloc(rd->result, rd->aresult);
+  }
+  memcpy(rd->result + rd->lresult, s, sl);
+  rd->lresult= newlresult;
+  rd->result[rd->lresult]= 0;
+}
+
+
+static DatabaseNode *findchar_1ctx(const FindCharArgs *fca,
+                                  DatabaseNode *start, int *matchx_r) {
+  DatabaseNode *current= start;
+  DatabaseNode *bestmatch= 0;
+  int i;
+  int x= fca->x;
+
+  for (;;) {
+    debug_flush();
+    debugf(" | x=%d",x);
+    if (x > fca->w) break;
+    Pixcol cv= fca->cols[x];
+    debugf(" cv="PIXCOL_PRFMT, PIXCOL_PRVAL(cv));
+    for (i=0; i<current->nlinks; i++)
+      if (!pixcol_cmp(&cv, &current->links[i].col))
+       goto found;
+    /* not found */
+    debugf(" ?");
+    break;
+
+  found:
+    current= current->links[i].then;
+    if (current->match) {
+      debugf(" \"%s\"%s",current->str,current->endsword?"_":"");
+      bestmatch= current;
+      *matchx_r= x;
+    } else {
+      debugf(" ...");
+    }
+
+    x++;
+  }
+  return bestmatch;
+}  
+
+static DatabaseNode *findchar(const FindCharArgs *fca,
+                             int *match_rx, int *match_rctxi) {
+  FindCharResults results[NCONTEXTS];
+  int ctxi, match=-1, nmatches=0;
+
+  debugf("OCR  lx=%d ct_state=%x  ", fca->x, fca->ctxmap);
+  for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
+    results[ctxi].match= 0;
+    if (!(fca->ctxmap & (1u << ctxi))) continue;
+    debugf(" || %s",context_names[ctxi]);
+
+    results[ctxi].match= findchar_1ctx(fca, &fca->rd->contexts[ctxi],
+                                      &results[ctxi].rx);
+    if (!results[ctxi].match) continue;
+
+    match= ctxi;
+    nmatches++;
+  }
+  if (nmatches==1) {
+    debugf(" unique");
+  } else {
+    debugf(" ambiguous");
+    match= !fca->ct->findchar_select ? -1 :
+      fca->ct->findchar_select(fca,results);
+    debugf(" resolved %s", match<0 ? "<none>" : context_names[match]);
+  }
+  if (match<0)
+    return 0;
+  
+  *match_rx= results[match].rx;
+  if (match_rctxi) *match_rctxi= match;
+  return results[match].match;
+}
+
+static int findchar_select_text(const FindCharArgs *fca,
+                               const FindCharResults results[]) {
+  
+  dbassert(! results[ct_Digit].match ); /* digits are supposedly unambiguous */
+
+  switch (fca->ctxmap) {
+
+#define RETURN_IF_LONGER(this,that) do{                        \
+    if (results[ct_##this].rx > results[ct_##that].rx) \
+       return ct_##this;                               \
+  }while(0)
+
+  case ctf_Digit | ctf_Upper | ctf_Lower | ctf_Word:
+    /* Start of word.  Prefer Word match; failing that, take the longest */
+    if (results[ct_Word].match) return ct_Word;
+    RETURN_IF_LONGER(Lower,Upper);
+    RETURN_IF_LONGER(Upper,Lower);
+    break;
+
+  case ctf_Digit | ctf_Upper | ctf_Lower:
+    /* Mid-word.  Prefer longer match; failing that, match lower. */
+    RETURN_IF_LONGER(Upper,Lower);
+    return ct_Lower;
+  }
+
+  /* oh well */
+  return -1;
 }
 
-struct OcrCellTypeInfo {
-  unsigned initial, nextword, midword;
-  const char *name;
-};
 const struct OcrCellTypeInfo ocr_celltype_number= {
-  4,4,4,
-  .name= "number"
+  ctf_Digit, ctf_Digit, ctf_Digit,
+  .space_spaces= 5,
+  .name= "number",
+  .findchar_select= 0
 };
 const struct OcrCellTypeInfo ocr_celltype_text= {
-  .initial=2, /* Uppercase */
-  .nextword=3, /* Either */
-  .midword=1, /* Lower only */
-  .name= "text"
+  .initial=  ctf_Digit | ctf_Upper,
+  .nextword= ctf_Digit | ctf_Upper | ctf_Lower | ctf_Word,
+  .midword=  ctf_Digit | ctf_Upper | ctf_Lower,
+  .space_spaces= 4,
+  .name= "text",
+  .findchar_select= findchar_select_text
 };
 
+
 const char *ocr_celltype_name(OcrCellType ct) { return ct->name; }
 
-OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w, Pixcol cols[]) {
+OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w,
+                   const Pixcol cols[]) {
   int nspaces;
-  unsigned ctxmap;
-  int ctxi, i, x;
+  int x;
+
+  FindCharArgs fca;
+  fca.rd= rd;
+  fca.ct= ct;
+  fca.w= w;
+  fca.cols= cols;
+  fca.x= -1;
 
  restart:
 
   nspaces=- w;
-  ctxmap= ct->initial;
+  fca.ctxmap= ct->initial;
   rd->nresults=0;
+  rd->lresult=0;
+  rd->result[0]=0;
   debugf("OCR h=%d w=%d",rd->h,w);
-  for (x=0; x<w; x++) debugf(" %"PSPIXCOL(PRIx),cols[x]);
+  for (x=0; x<w; x++) debugf(" "PIXCOL_PRFMT, PIXCOL_PRVAL(cols[x]));
   debugf("\n");
   debug_flush();
 
@@ -335,98 +536,55 @@ OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w, Pixcol cols[]) {
     if (x>=w)
       break;
 
-    if (!cols[x]) {
+    if (!pixcol_nonzero(&cols[x])) {
       nspaces++;
       x++;
-      if (nspaces==SPACE_SPACES) {
+      if (nspaces == ct->space_spaces) {
        debugf("OCR  x=%x nspaces=%d space\n",x,nspaces);
-       ctxmap= ct->nextword;
+       fca.ctxmap= ct->nextword;
       }
       continue;
     }
 
     /* something here, so we need to add the spaces */
-    if (nspaces>=SPACE_SPACES)
-      add_result(rd," ",x-nspaces,x+1,0);
+    if (nspaces >= ct->space_spaces)
+      add_result(rd," ",x-nspaces,x+1,-1,0);
     nspaces=0;
 
-    /* find character */
-    int lx=x;
+    fca.x= x;
 
-    DatabaseNode *uniquematch= 0;
-    int uniquematch_rx=-1;
+    int match_rx=-1;
+    int match_ctxi=-1;
+    DatabaseNode *match= findchar(&fca, &match_rx, &match_ctxi);
     
-    debugf("OCR  lx=%d ctxmap=%x  ",lx,ctxmap);
-
-    for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
-      DatabaseNode *current= &rd->contexts[ctxi];;
-      DatabaseNode *bestmatch= 0;
-      int bestmatch_rx=-1;
-
-      x= lx;
-      if (!(ctxmap & (1u << ctxi))) continue;
-      debugf(" || %s",context_names[ctxi]);
-
-      for (;;) {
-       debug_flush();
-       debugf(" | x=%d",x);
-       if (x>w) break;
-       Pixcol cv= cols[x];
-       debugf(" cv=%"PSPIXCOL(PRIx),cv);
-       for (i=0; i<current->nlinks; i++)
-         if (current->links[i].col == cv)
-           goto found;
-       /* not found */
-       debugf(" ?");
-       break;
-
-      found:
-       current= current->links[i].then;
-       if (current->s[0]) {
-         debugf(" \"%s\"%s",current->s,current->endsword?"_":"");
-         bestmatch= current;
-         bestmatch_rx= x;
-       } else {
-         debugf(" ...");
-       }
-
-       x++;
-      }
-      
-      if (bestmatch) {
-       if (uniquematch && strcmp(bestmatch->s, uniquematch->s)) {
-         debugf( " ambiguous");
-         uniquematch= 0;
-         break;
-       }
-       uniquematch= bestmatch;
-       uniquematch_rx= bestmatch_rx;
-      }
-    }
-
-    if (uniquematch) {
+    if (match) {
       debugf(" || YES");
-      add_result(rd, uniquematch->s, lx, uniquematch_rx, ctxmap);
-      x= uniquematch_rx+1;
-      if (uniquematch->s[0]) ctxmap= ct->midword;
+      add_result(rd, match->str, x, match_rx, match_ctxi, fca.ctxmap);
+      if (should_reject(rd)) {
+       callout_unknown(rd, w,cols, match_rx+1,match_rx, 0);
+       goto restart;
+      }
+      x= match_rx+1;
+      if (match->match) fca.ctxmap= ct->midword;
       else debugf(" (empty)");
-      if (uniquematch->endsword) {
-       nspaces= SPACE_SPACES;
+      if (match->endsword) {
+       nspaces= ct->space_spaces;
        debugf("_");
-       ctxmap= ct->nextword;
+       fca.ctxmap= ct->nextword;
       }
       debugf("\n");
     } else {
       int rx;
       debugf(" || UNKNOWN");
-      for (rx=lx; rx<w && cols[rx]; rx++);
-      debugf(" x=%d ctxmap=%x %d..%d\n",x, ctxmap, lx,rx);
+      for (rx=x; rx<w && pixcol_nonzero(&cols[rx]); rx++);
+      debugf(" x=%d ctxmap=%x %d..%d\n",x, fca.ctxmap, x,rx);
       debug_flush();
-      callout_unknown(rd, w,cols, lx,rx-1, ctxmap);
+      callout_unknown(rd, w,cols, x,rx-1, fca.ctxmap);
       goto restart;
     }
+
   }
-  add_result(rd, 0,-1,-1,0);
+  add_result(rd, 0,-1,-1,-1,0);
   debugf("OCR  finished %d glyphs\n",rd->nresults);
   debug_flush();
   return rd->results;
@@ -435,9 +593,139 @@ OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w, Pixcol cols[]) {
 OcrReader *ocr_init(int h) {
   OcrReader *rd;
 
+  assert(h <= OCR_MAX_H);
+
+  if (o_flags & ff_dict_fetch) {
+    char *fetchfile= masprintf("char%d",h);
+    progress("Updating %s...",fetchfile);
+    fetch_with_rsync(fetchfile);
+    free(fetchfile);
+  }
+
   rd= mmalloc(sizeof(*rd));
   memset(rd,0,sizeof(*rd));
+
   rd->h= h;
+
+  rd->aresult= 10;
+  rd->result= mmalloc(rd->aresult);
+
   readdb(rd);
   return rd;
 }
+
+/*---------- character set dump ----------*/
+
+static void show_recurse(const DatabaseNode *t, int *count,
+                        const DatabaseNode **store_ary) {
+  if (t->defined) {
+    if (store_ary) store_ary[*count]= t;
+    (*count)++;
+  }
+  int l;
+  for (l=0; l<t->nlinks; l++)
+    show_recurse(t->links[l].then, count,store_ary);
+}
+
+static int show_char_compar(const void *av, const void *bv) {
+  const DatabaseNode *const *ap= av;  const DatabaseNode *a= *ap;
+  const DatabaseNode *const *bp= bv;  const DatabaseNode *b= *bp;
+  return strcmp(a->str, b->str) ?:
+    ((int)a->match -    (int)b->match) ?:
+    ((int)a->endsword - (int)b->endsword) ?:
+    ((int)a->local -    (int)b->local) ?:
+    0;
+}
+
+void ocr_showcharsets(void) {
+  DIR *d;
+  struct dirent *de;
+  char found[OCR_MAX_H];
+  pcre *fnpat;
+  int matchvec[10];
+  char hbuf[10];
+  const char *pcre_err;
+  int pcre_erroffset;
+
+  memset(found,0,sizeof(found));
+  
+  fnpat= pcre_compile("\\#(?:master|local)\\-char([1-9]\\d{0,2})\\#\\.txt$",
+                     PCRE_ANCHORED|PCRE_DOLLAR_ENDONLY,
+                     &pcre_err,&pcre_erroffset, 0);
+  debugf("pcre_compile %p %s\n",fnpat,pcre_err);
+  assert(fnpat);
+
+  sysassert( d= opendir(get_vardir()) );
+  for (;;) {
+    errno=0; de= readdir(d);  if (!de) break;
+
+    int rer= pcre_exec(fnpat,0, de->d_name,strlen(de->d_name), 0,0,
+                      matchvec,ARRAYSIZE(matchvec));
+    debugf("pcre_exec `%s' => %d\n", de->d_name,rer);
+
+    if (rer==PCRE_ERROR_NOMATCH || rer==PCRE_ERROR_BADUTF8) continue;
+    assert(rer==2);
+
+    rer= pcre_copy_substring(de->d_name,matchvec,rer, 1, hbuf,sizeof(hbuf));
+    debugf("pcre_copy_substring => %d\n", rer);
+    assert(rer>0);
+
+    int h= atoi(hbuf);
+    if (h >= ARRAYSIZE(found)) continue;
+    
+    found[h]= 1;
+  }
+
+  int h;
+  for (h=0; h<ARRAYSIZE(found); h++) {
+    if (!found[h]) continue;
+
+    OcrReader *rd= ocr_init(h); /* we leak this but never mind */
+    progress("");
+
+    int ctxi;
+    for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
+      int nchars= 0;
+      show_recurse(&rd->contexts[ctxi], &nchars, 0);
+      const DatabaseNode **chars= mmalloc(sizeof(*chars) * nchars);
+      int chari= 0;
+      show_recurse(&rd->contexts[ctxi], &chari, chars);
+      assert(chari==nchars);
+      qsort(chars, nchars, sizeof(*chars), show_char_compar);
+
+      int local;
+      for (local=0; local<2; local++) {
+       printf("%2d %-6s %-6s ", h, context_names[ctxi],
+              local?"local":"master");
+       for (chari=0; chari<nchars; chari++) {
+         const DatabaseNode *t= chars[chari];
+         static const char accept[]=
+           "abcdefghijklmnopqrstuvwxyz"
+           "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+           "0123456789" "'!&-+.,>";
+
+         if (t->local != local) continue;
+
+         if (!t->match)
+           printf(" [nomatch]");
+         else if (!t->endsword && strspn(t->str, accept) == strlen(t->str))
+           printf(" %s",t->str);
+         else {
+           printf(" \"");
+           char *p= t->str;
+           int c;
+           while ((c=*p++)) {
+             if (c=='"' || c=='\\') printf("\\%c",c);
+             else if (c>=' ' && c<=126) putchar(c);
+             else printf("\\x%02x", (unsigned char)c);
+           }
+           if (t->endsword) putchar(' ');
+           putchar('"');
+         }
+       }
+       putchar('\n');
+      }
+      free(chars);
+    }
+  }
+}