chiark / gitweb /
fixes to find_aa_density: MUST failures print p, deal with rounding problems in alpha...
[ypp-sc-tools.web-live.git] / pctb / structure.c
index f9f1e7f52b1c8cf08328fe8a05a0446f0bc3452f..c54f89a13c35aa3a4b8bc7ef4dda73b1bc665fb3 100644 (file)
@@ -1,23 +1,39 @@
 /*
-  */
+ * Parsing of the structure of the YPP client's displayed image
+ */
+/*
+ *  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 "structure.h"
 
-
-typedef struct {
-  int x, y;
-} Point;
-
-typedef struct { /* both inclusive */
-  Point tl;
-  Point br;
-} Rect;
-
 static CanonImage *cim;
 
 static inline char get(int x, int y) { return cim->d[y * cim->w + x]; }
 static inline char get_p(Point p) { return get(p.x,p.y); }
 
+DEBUG_DEFINE_DEBUGF(struct)
+
 #define START_MAIN {200,200}
 #define MIN_COLUMNS         6
 #define INTERESTING_COLUMNS 7
@@ -30,10 +46,25 @@ static int colrightx[INTERESTING_COLUMNS];
 static int text_h=-1, columns=-1;
 static OcrReader *rd;
 
-const CanonColourInfo canoncolourinfos[]= {
+char *archipelago, *island;
+
+#define OTHERCOORD_x y
+#define OTHERCOORD_y x
+
+typedef struct {
+  Rgb rgb; /* on screen */
+  char c; /* canonical */
+} CanonColourInfo;
+
+const CanonColourInfo canoncolourinfo_table[]= {
   { 0x475A5E, '*' }, /* edge */
   { 0x2C5F7A, '*' }, /* edge just under box heading shadow */
+  { 0xC5C7AE, '*' }, /* blank area of partial commodities list */
+  { 0x6B828C, '*' }, /* background of ship status meter area */
+  { 0x934405, '*' }, /* border of ship meter area */
   { 0x7D9094, '+' }, /* interbox */
+  { 0x022158, 'O' }, /* ahoy /w output foreground */
+  { 0xB5B686, 'H' }, /* ahoy /w output heading background */
 
   { 0xBDC5BF, ' ' }, /* background - pale  Sugar cane, etc. */
   { 0xADB5AF, ' ' }, /* background - dark                   */
@@ -63,35 +94,137 @@ const CanonColourInfo canoncolourinfos[]= {
   { 0,0 }
 };
 
-static void require_rectangle(int tlx, int tly, int brx, int bry,
-                             const char *ok) {
-  int x,y;
-  for (x=tlx; x<=brx; x++)
-    for (y=tly; y<=bry; y++) {
-      int c= get(x,y);
-      assert(strchr(ok,c));
+CanonColourInfoReds canoncolourinfo_tree;
+
+void canon_colour_prepare(void) {
+  const CanonColourInfo *cci;
+  for (cci=canoncolourinfo_table; cci->c; cci++) {
+    unsigned char r= cci->rgb >> 16;
+    unsigned char g= cci->rgb >>  8;
+    unsigned char b= cci->rgb;
+
+    CanonColourInfoGreens *greens= canoncolourinfo_tree.red2[r];
+    if (!greens) {
+      greens= canoncolourinfo_tree.red2[r]= mmalloc(sizeof(*greens));
+      FILLZERO(*greens);
     }
+
+    CanonColourInfoBlues *blues= greens->green2[g];
+    if (!blues) {
+      blues= greens->green2[g]= mmalloc(sizeof(*blues));
+      memset(blues, '?', sizeof(blues));
+    }
+
+    blues->blue2[b]= cci->c;
+  }
 }
-static void require_rectangle_r(Rect rr, const char *ok) {
-  require_rectangle(rr.tl.x,rr.tl.y, rr.br.x,rr.br.y, ok);
+
+
+static void mustfail1(const char *file, int line, const char *what) {
+  fprintf(stderr,
+ "\n\n"
+ "Unable to figure out contents of YPP client display.\n"
+ "Please check the following:\n"
+ "   * YPP client is showing commodity listing screen\n"
+ "   * YPP client window is on top (we try to raise it but your window\n"
+ "      manager might have prevented that from succeeding)\n"
+ "   * Your X display is 24bpp (NB some VNC servers use 16bpp by default)\n"
+ "\n"
+ "If all of these are true, please report this as a fault.\n\n"
+         "Technical details:"
+         " %s:%d: requirement failed:\n"
+         " %s\n",
+         file, line, what);
+}
+static void mustfail2(void) NORET;
+static void mustfail2(void) {
+  fprintf(stderr, "\n\nGiving up.\n");
+  exit(8);
+}
+
+#define MUST(x, ifnot) do{                     \
+    if (!(x)) {                                        \
+      mustfail1(__FILE__,__LINE__,#x);         \
+      ifnot;                                   \
+      mustfail2();                             \
+    }                                          \
+  }while(0)
+
+#define MP(v) fprintf(stderr," %s=%d,%d",#v,(v).x,(v).y)
+#define MI(v) fprintf(stderr," %s=%d",   #v,(v))
+#define MIL(v) fprintf(stderr," %s=%ld", #v,(v))
+#define MRGB(v) fprintf(stderr," %s=%06lx", #v,(v))
+#define MC(v) fprintf(stderr," %s='%c'", #v,(v))
+#define MS(v) fprintf(stderr," %s=\"%s\"", #v,(v))
+#define MF(v) fprintf(stderr," %s=%f", #v,(v))
+#define MSB(v) fprintf(stderr," %s", (v))
+#define MR(v) fprintf(stderr," %s=%d,%d..%d,%d",\
+                      #v,(v).tl.x,(v).tl.y,(v).br.x,(v).br.y)
+
+
+#define REQUIRE_RECTANGLE(tlx,tly,brx,bry,ok) \
+ require_rectangle(tlx, tly, brx, bry, ok, __LINE__);
+
+#define FOR_P_RECT(p,rr)                               \
+  for ((p).x=(rr).tl.x; (p).x<=(rr).br.x; (p).x++)     \
+    for ((p).y=(rr).tl.y; (p).y<=(rr).br.y; (p).y++)
+
+static void require_rectangle_r(Rect rr, const char *ok, int lineno) {
+  Point p;
+  FOR_P_RECT(p,rr) {
+    int c= get_p(p);
+    MUST( strchr(ok,c), ({
+      MI(lineno),MR(rr);MP(p);MS(ok);
+    }));
+  }
+}
+static void require_rectangle(int tlx, int tly, int brx, int bry,
+                             const char *ok, int lineno) {
+  Rect rr= {{tlx,tly},{brx,bry}};
+  require_rectangle_r(rr, ok, lineno);
 }
 
 static void debug_rect(const char *what, int whati, Rect rr) {
   if (!DEBUGP(rect)) return;
-  int y,r,w;
+  int y,w;
   fprintf(debug, "%s %d: %d,%d..%d,%d:\n", what, whati,
          rr.tl.x,rr.tl.y, rr.br.x,rr.br.y);
   w= rr.br.x - rr.tl.x + 1;
   for (y=rr.tl.y; y<=rr.br.y; y++) {
     fprintf(debug, "%4d%*s|", y, rr.tl.x,"");
-    r= fwrite(cim->d + y*cim->w + rr.tl.x, 1, w, debug);
-    eassert(r==w);
+    fwrite(cim->d + y*cim->w + rr.tl.x, 1, w, debug);
     fputc('|',debug);
     fputc('\n',debug);
   }
   debug_flush();
 }
 
+static int commod_selector_matches(Rect search, const char *const *all,
+                                  int allh, int allw) {
+  int alloffy, alloffx;
+  for (alloffy=0; alloffy < search.br.y; alloffy++) {
+    if (alloffy+allh-1 < search.tl.y) continue;
+    for (alloffx=search.tl.x; alloffx+allw-1 <= search.br.x; alloffx++) {
+      int good=0, bad=0;
+      int x,y;
+      for (x=0; x<allw; x++)
+       for (y=0; y<allh; y++) {
+         int want= all[y][x];
+         if (want==' ') continue;
+          if (get(alloffx+x, alloffy+y) == want)
+           good++;
+         else
+           bad++;
+       }
+      debugf("CHECKCOMMOD alloff=%d,%d good=%d bad=%d\n",
+            alloffx,alloffy, good,bad);
+      if (good > 20*bad)
+       return 1;
+    }
+  }
+  return 0;
+}
+
 #define WALK_UNTIL(point,coord,increm,last,edge)                       \
   for (;;) {                                                           \
     if ((point).coord == (last)+(increm)) break;                       \
@@ -102,37 +235,67 @@ static void debug_rect(const char *what, int whati, Rect rr) {
 #define WALK_UNTIL_MUST(point,coord,increm,last,edge)  \
   do {                                                 \
     WALK_UNTIL(point,coord,increm,last,edge);          \
-    eassert((point).coord != (last)+(increm));         \
-  } while(0)
+    MUST( (point).coord != (last)+(increm),            \
+         MP(point); MI(increm); MI(last); MC(edge);    \
+         );                                            \
+  }while(0)
 
-void find_structure(CanonImage *im) {
+#define ADJUST_BOX(search,insidechrs,OP,want, lim,LIMIT_MUST, TLBR,XY,increm) \
+  for (;;) {                                                                 \
+    LIMIT_MUST( (search).tl.XY != (search).br.XY &&                          \
+               (search).tl.XY != (lim),                                      \
+               MR((search));MSB(#TLBR);MSB(#XY) );                           \
+    int got=0;                                                               \
+    Point p=(search).tl;                                                     \
+    for (p.XY=(search).TLBR.XY;                                                      \
+        p.OTHERCOORD_##XY <= (search).br.OTHERCOORD_##XY;                    \
+        p.OTHERCOORD_##XY++)                                                 \
+      got += !!strchr(insidechrs, get_p(p));                                 \
+    if ((got) OP (want))                                                     \
+      break;                                                                 \
+    (search).TLBR.XY += increm;                                                      \
+  }
+
+void find_structure(CanonImage *im, int *max_relevant_y_r) {
   cim= im;
   
   Rect whole = { {0,0}, {cim->w-1,cim->h-1} };
 
+  if (DEBUGP(rect)) {
+    int xscaleunit, y,x;
+    for (y=0, xscaleunit=1; y<4; y++, xscaleunit*=10) {
+      fprintf(debug,"     ");
+      for (x=0; x<=cim->w; x++) {
+       if (x % xscaleunit) fputc(' ',debug);
+       else fprintf(debug,"%d",(x / xscaleunit)%10);
+      }
+      fputc('\n',debug);
+    }
+  }
+
   WALK_UNTIL_MUST(mainr.tl, x,-1, whole.tl.x, '*');
   WALK_UNTIL_MUST(mainr.tl, y,-1, whole.tl.y, '*');
   WALK_UNTIL_MUST(mainr.br, x,+1, whole.br.x, '*');
   WALK_UNTIL_MUST(mainr.br, y,+1, whole.br.y, '*');
 
-  require_rectangle(mainr.tl.x-1, mainr.tl.y, mainr.tl.x-1, mainr.br.y, "*");
-  require_rectangle(mainr.br.x+1, mainr.tl.y, mainr.br.x+1, mainr.br.y, "*");
-  require_rectangle(mainr.tl.x, mainr.tl.y-1, mainr.br.x, mainr.tl.y-1, "*");
-  require_rectangle(mainr.tl.x, mainr.br.y+1, mainr.br.x, mainr.br.y+1, "*");
-
-#define CHECK_STRIP_BORDER(tlbr,xy,increm)     \
-  do {                                         \
-    Point csb_p;                               \
-    Rect csb_r;                                        \
-    csb_p= mainr.tl;                           \
-    csb_p.xy= mainr.tlbr.xy;                   \
-    if (get_p(csb_p)=='+') {                   \
-      csb_r= mainr;                            \
-      csb_r.tl.xy= csb_p.xy;                   \
-      csb_r.br.xy= csb_p.xy;                   \
-      require_rectangle_r(csb_r, "+");         \
-      mainr.tlbr.xy += increm;                 \
-    }                                          \
+  REQUIRE_RECTANGLE(mainr.tl.x-1, mainr.tl.y, mainr.tl.x-1, mainr.br.y, "*");
+  REQUIRE_RECTANGLE(mainr.br.x+1, mainr.tl.y, mainr.br.x+1, mainr.br.y, "*");
+  REQUIRE_RECTANGLE(mainr.tl.x, mainr.tl.y-1, mainr.br.x, mainr.tl.y-1, "*");
+  REQUIRE_RECTANGLE(mainr.tl.x, mainr.br.y+1, mainr.br.x, mainr.br.y+1, "*");
+
+#define CHECK_STRIP_BORDER(tlbr,xy,increm)             \
+  do {                                                 \
+    Point csb_p;                                       \
+    Rect csb_r;                                                \
+    csb_p= mainr.tl;                                   \
+    csb_p.xy= mainr.tlbr.xy;                           \
+    if (get_p(csb_p)=='+') {                           \
+      csb_r= mainr;                                    \
+      csb_r.tl.xy= csb_p.xy;                           \
+      csb_r.br.xy= csb_p.xy;                           \
+      require_rectangle_r(csb_r, "+", __LINE__);       \
+      mainr.tlbr.xy += increm;                         \
+    }                                                  \
   } while(0)
 
   debug_rect("mainr",0, mainr);
@@ -151,27 +314,15 @@ void find_structure(CanonImage *im) {
   down.y++;
   WALK_UNTIL_MUST(down, y,+1, mainr.br.y, '+');
 
-  if (DEBUGP(rect)) {
-    int xscaleunit, y,x;
-    for (y=0, xscaleunit=1; y<4; y++, xscaleunit*=10) {
-      fprintf(debug,"     ");
-      for (x=0; x<=cim->w; x++) {
-       if (x % xscaleunit) fputc(' ',debug);
-       else fprintf(debug,"%d",(x / xscaleunit)%10);
-      }
-      fputc('\n',debug);
-    }
-  }
-
   commbasey= up.y;
   comminty= down.y - up.y + 2;
 
   Point across= { mainr.tl.x, commbasey };
   int colno=0;
   for (;;) {
-    eassert(get_p(across) != '+');
+    MUST( get_p(across) != '+', MI(colno);MP(across);MR(mainr);MI(commbasey) );
     WALK_UNTIL(across, x,+1, mainr.br.x, '+');
-    eassert(colno < MAX_COLUMNS);
+    MUST( colno < MAX_COLUMNS, MP(across);MR(mainr);MI(commbasey); );
     int colrx= across.x;
     if (colrx > mainr.br.x) colrx= mainr.br.x;
     if (colno < INTERESTING_COLUMNS)
@@ -183,59 +334,172 @@ void find_structure(CanonImage *im) {
       break;
 
     across.x++;
-    require_rectangle(across.x,mainr.tl.y, across.x,mainr.br.y, "+");
+    REQUIRE_RECTANGLE(across.x,mainr.tl.y, across.x,mainr.br.y, "+");
     across.x++;
   }
-  eassert(colno >= MIN_COLUMNS);
+  MUST( colno >= MIN_COLUMNS, MI(colno);MR(mainr);MP(across); );
 
-#define SET_ONCE(var,val) do{                  \
-    int v= (val);                              \
-    if ((var)==-1) (var)= v;                   \
-    else eassert((var) == v);                  \
+#define SET_ONCE(var,val) do{                                          \
+    int v= (val);                                                      \
+    if ((var)==-1) (var)= v;                                           \
+    else MUST( (var) == v, MSB(#var);MI((var));MI(v);MR(mainr); );     \
   }while(0)
 
   SET_ONCE(columns, colno);
   SET_ONCE(text_h, comminty - 1);
+  if (max_relevant_y_r)
+    SET_ONCE(*max_relevant_y_r, mainr.br.y + 10);
+
+  MUST( text_h <= OCR_MAX_H, MI(text_h) );
 }                  
 
+void check_correct_commodities(void) {
+  Rect search= { { 50,39 }, { 130,59 } };
+
+  ADJUST_BOX(search,"_",>=,10, cim->h, MUST, tl,y,+1);
+  ADJUST_BOX(search,"_",>=,10, 0,      MUST, br,y,-1);
+
+  debug_rect("commodselr",1, search);
+
+  static const char *all_small[]= {
+    "   ___________________________________   ",
+    "  ________X____X__X____________________  ",
+    " ________ X___ X_ X_____XXXXXXXXXXX_____ ",
+    "_________X_X__ X_ X______XXXXXXXXX_______",
+    "________ X X__ X_ X_______XXXXXXX________",
+    "________X_ _X_ X_ X________XXXXX_________",
+    "_______ X__ X_ X_ X_________XXX__________",
+    "_______XXXXXXX X_ X__________X___________",
+    " _____ X     X X_ X______________________",
+    "  ____X_____ _XX_ X______________________",
+    "   __ _______  __ ______________________ ",
+  };
+  static const char *all_big[]= {
+    "???_______________________________________???",
+    "??_________________________________________??",
+    "?_________X______X___X______________________?",
+    "_________?X_____?X__?X______XXXXXXXXXXX______",
+    "_________X_X____?X__?X_______XXXXXXXXX_______",
+    "________?X?X____?X__?X________XXXXXXX________",
+    "________X_?_X___?X__?X_________XXXXX_________",
+    "_______?X__?X___?X__?X__________XXX__________",
+    "_______?XXXXX___?X__?X___________X___________",
+    "_______X????_X__?X__?X_______________________",
+    "?_____?X____?X__?X__?X_______________________",
+    "??____X_____?_X_?X__?X_______________________",
+    "???__?_______?__?___?_______________________?",
+  };
+
+#define COMMOD_SELECTOR_MATCHES(all)                           \
+  commod_selector_matches(search, all,                         \
+                         sizeof((all))/sizeof((all)[0]),       \
+                         strlen((all)[0]))
+
+  if (!(COMMOD_SELECTOR_MATCHES(all_small) ||
+       COMMOD_SELECTOR_MATCHES(all_big)))
+    fatal("Commodities selector not set to `All'.");
+}
+
 CanonImage *alloc_canon_image(int w, int h) {
-  CanonImage *im= malloc(sizeof(CanonImage) + w*h);
-  eassert(im);
+  CanonImage *im= mmalloc(sizeof(CanonImage) + w*h);
   im->w= w;
   im->h= h;
   memset(im->d,'?',w*h);
   return im;
 }
 
-CanonImage *file_read_image_ppm(FILE *f) {
+static void file_read_image_ppm(FILE *f) {
   struct pam inpam;
   unsigned char rgb_buf[3];
   CanonImage *im;
 
   pnm_readpaminit(f, &inpam, sizeof(inpam));
-  eassert(inpam.maxval == 255);
-  eassert(inpam.bytes_per_sample == 1);
+  if (!(inpam.maxval == 255 &&
+       inpam.bytes_per_sample == 1 &&
+       inpam.format == RPPM_FORMAT))
+    fatal("PNM screenshot(s) file must be 8bpp 1 byte-per-sample RGB raw");
 
   CANONICALISE_IMAGE(im, inpam.width, inpam.height, {
-    int r= fread(&rgb_buf,1,3,f);  eassert(r==3);
+    int rr= fread(&rgb_buf,1,3,f);
+    sysassert(!ferror(f));
+    if (rr!=3) fatal("PNM screenshot(s) file ends unexpectedly");
 
-    rgb=
-       ((unsigned long)rgb_buf[0]<<16) |
-       ((unsigned long)rgb_buf[1]<<8) |
-                      (rgb_buf[2]);
+    r= rgb_buf[0];
+    g= rgb_buf[1];
+    b= rgb_buf[2];
   });
 
-  return im;
+  sysassert(!ferror(screenshot_file));
+
+  if (!(npages < MAX_PAGES))
+    fatal("Too many images in screenshots file; max is %d.\n", MAX_PAGES);
+
+  page_images[npages++]= im;
+}
+
+void read_one_screenshot(void) {
+  progress("reading screenshot...");
+  file_read_image_ppm(screenshot_file);
+  progress_log("read screenshot.");
 }
 
 void read_screenshots(void) {
-//  int c;
-//  while ((c= fgetc(screenshots_file) != EOF)) {
-//    ungetc(c, screenshots_file);
+  struct stat stab;
+  
+  sysassert(! fstat(fileno(screenshot_file), &stab) );
+  
+  for (;;) {
+    if (S_ISREG(stab.st_mode)) {
+      long pos= ftell(screenshot_file);
+      if (pos == stab.st_size) break;
+    } else {
+      int c= fgetc(screenshot_file);
+      if (c==EOF) break;
+      ungetc(c, screenshot_file);
+    }
+    progress("reading screenshot %d...",npages);
+    file_read_image_ppm(screenshot_file);
+  }
+  sysassert(!ferror(screenshot_file));
+  progress_log("read %d screenshots.",npages);
+}
+
+static double find_aa_density(const RgbImage *ri, Point p, long background,
+                             long foreground, int fg_extra) {
+  Rgb here= ri_rgb(ri, p.x, p.y);
+
+  double alpha[3], alpha_mean=0;
+  int i;
+  for (i=0; i<3; i++) {
+    unsigned char here_chan= here       >> (i*8);
+    unsigned char bg_chan=   background >> (i*8);
+    unsigned char fg_chan=   foreground >> (i*8);
+    double alpha_chan=
+      ((double)here_chan    - (double)bg_chan) /
+      ((fg_chan + fg_extra) - (double)bg_chan);
+    alpha[i]= alpha_chan;
+    alpha_mean += alpha_chan * (1/3.0);
+  }
 
-//    eassert(npages < MAX_PAGES);
-    page_images[npages++]= file_read_image_ppm(screenshots_file);
-//  }
+  double thresh= 1.5/AAMAXVAL;
+  double alpha_min= alpha_mean - thresh;
+  double alpha_max= alpha_mean + thresh;
+  for (i=0; i<3; i++)
+    MUST( alpha_min <= alpha[i] && alpha[i] <= alpha_max,
+         MP(p);
+         MRGB(here);MRGB(background);MRGB(foreground);MI(fg_extra);
+         MF(alpha_min); MI(i);MF(alpha[i]);MF(alpha_max) );
+
+  if (   -1e-5 <  alpha_mean && alpha_mean <= 0.0     ) alpha_mean= 0.0;
+  if (1.0      <= alpha_mean && alpha_mean <= 1.0+1e-5) alpha_mean= 1.0;
+
+  MUST( 0 <= alpha_mean &&
+       (fg_extra ? (alpha_mean < 0.999) : (alpha_mean <= 1.0)),
+       MP(p);
+       MRGB(here);MRGB(background);MRGB(foreground);MI(fg_extra);
+       MF(alpha_mean); MF(alpha[0]);MF(alpha[1]);MF(alpha[2]); );
+
+  return alpha_mean;
 }
 
 static void find_commodity(int offset, Rect *rr) {
@@ -243,58 +507,113 @@ static void find_commodity(int offset, Rect *rr) {
   rr->tl.y= commbasey - offset*comminty;
   rr->br.y= rr->tl.y + comminty-2;
   if (rr->tl.y < mainr.tl.y || rr->br.y > mainr.br.y) { rr->tl.x=-1; return; }
-  if (rr->tl.y > mainr.tl.y)
-    require_rectangle(rr->tl.x,rr->tl.y-1, rr->br.x,rr->tl.y-1, "+");
-  if (rr->br.y < mainr.tl.y)
-    require_rectangle(rr->tl.x,rr->br.y+1, rr->br.x,rr->br.y+1, "+");
   
   rr->tl.x= mainr.tl.x;
   rr->br.x= mainr.br.x;
+
+  if (rr->tl.y > mainr.tl.y)
+    REQUIRE_RECTANGLE(rr->tl.x,rr->tl.y-1, rr->br.x,rr->tl.y-1, "+");
+  if (rr->br.y < mainr.tl.y)
+    REQUIRE_RECTANGLE(rr->tl.x,rr->br.y+1, rr->br.x,rr->br.y+1, "+");
 }
 
-static void find_table_entry(Rect commod, int colno, Rect *cellr) {
-  cellr->tl.y= commod.tl.y;
-  cellr->br.y= commod.br.y;
-  cellr->tl.x= !colno ? commod.tl.x : colrightx[colno-1]+2;
-  cellr->br.x=                        colrightx[colno];
-  debug_rect("cell", colno, *cellr);
-  require_rectangle_r(*cellr, " o");
+static void find_table_entry(Rect commod, int colno, Rect *cell) {
+  cell->tl.y= commod.tl.y;
+  cell->br.y= commod.br.y;
+  cell->tl.x= !colno ? commod.tl.x : colrightx[colno-1]+2;
+  cell->br.x=                        colrightx[colno];
+  debug_rect("cell", colno, *cell);
+
+  const RgbImage *ri= cim->rgb;
+  
+  Rgb background= ri_rgb(ri, cell->br.x, cell->br.y);
+  long bg_count=0, light_count=0, dark_count=0;
+  Point p;
+  FOR_P_RECT(p,*cell) {
+    Rgb here= ri_rgb(ri, p.x, p.y);
+    if (here == background) bg_count++;
+    else if (here < background) dark_count++;
+    else if (here > background) light_count++;
+  }
+  long total_count= RECT_W(*cell) * RECT_H(*cell);
+  MUST( bg_count > total_count / 2,
+       MR(*cell);MIL(total_count);MIL(bg_count);
+       MIL(light_count);MIL(dark_count) );
+  if (bg_count == total_count)
+    return;
+
+  MUST( !!dark_count != !!light_count,
+       MR(*cell);MIL(total_count);MIL(bg_count);
+       MIL(light_count);MIL(dark_count) );
+
+  debugf("TABLEENTRY col=%d %d,%d..%d,%d bg=%ld light=%ld dark=%ld\n",
+        colno, cell->tl.x,cell->tl.y, cell->br.x,cell->br.y,
+        bg_count, light_count, dark_count);
+  
+  Rgb foreground;
+  double fg_extra;
+  if (light_count) {
+    foreground= 0xffffffU;
+    fg_extra= +1;
+  } else {
+    foreground= 0;
+    fg_extra= -1;
+  }
+  int monochrome= 1;
+
+  FOR_P_RECT(p,*cell) {
+    double alpha= find_aa_density(ri,p,background,foreground,fg_extra);
+
+    int here_int= floor((AAMAXVAL+1)*alpha);
+    assert(here_int <= AAMAXVAL);
+    if (!(here_int==0 || here_int==AAMAXVAL)) monochrome=0;
+    cim->d[p.y * cim->w + p.x]= '0' + here_int;
+  }
+
+  debug_rect("cell0M", colno, *cell);
+
+  require_rectangle_r(*cell, "0123456789", __LINE__);
 }
 
-static void ocr_rectangle(Rect r, const OcrCellType ct) {
+static void ocr_rectangle(Rect r, const OcrCellType ct, FILE *tsv_output) {
   OcrResultGlyph *results, *res;
 
   int w= r.br.x - r.tl.x + 1;
   Pixcol cols[w+1];
   int x,y;
   for (x=0; x<w; x++) {
-    Pixcol cx, rv;
-    for (y=0, cx=0, rv=1; y<text_h; y++, rv<<=1) {
-      switch (get(x+r.tl.x, y+r.tl.y)) {
-      case ' ':           break;
-      case 'o': cx |= rv; break;
-      default: eassert(!"wrong pixel");
-      }
+    FILLZERO(cols[x]);
+    for (y=0; y<text_h; y++) {
+      Point here= { x+r.tl.x, y+r.tl.y };
+      int pixel= get_p(here);
+      if (pixel==' ') pixel= '0';
+      MUST( pixel >= '0' && pixel <= '0'+AAMAXVAL,
+           MC(pixel);MP(here);MSB(ocr_celltype_name(ct));MR(r); );
+      pixcol_p_add(&cols[x], y, pixel-'0');
     }
-    cols[x]= cx;
   }
-  cols[w]= 0;
+  FILLZERO(cols[w]);
 
   results= ocr(rd,ct,w,cols);
   for (res=results; res->s; res++)
-    printf("%s",res->s);
+    fputs(res->s,tsv_output);
 }
 
-void analyse(void) {
+void analyse(FILE *tsv_output) {
   Rect thisr, entryr;
   int page, tryrect, colno;
 
   for (page=0; page<npages; page++) {
-    find_structure(page_images[page]);
+    find_structure(page_images[page], 0);
+
+    if (!page)
+      check_correct_commodities();
 
     if (!rd)
       rd= ocr_init(text_h);
 
+    progress("Scanning page %d...",page);
+
     for (tryrect= +cim->h; tryrect >= -cim->h; tryrect--) {
       find_commodity(tryrect, &thisr);
       if (thisr.tl.x < 0)
@@ -304,16 +623,197 @@ void analyse(void) {
       const char *tab= "";
       for (colno=0; colno<columns; colno++) {
        find_table_entry(thisr,colno,&entryr);
-       fputs(tab, stdout);
+       fputs(tab, tsv_output);
        ocr_rectangle(entryr,
                      colno<TEXT_COLUMNS
                      ? &ocr_celltype_text
-                     : &ocr_celltype_number);
+                     : &ocr_celltype_number,
+                     tsv_output);
        tab= "\t";
       }
-      fputs("\n", stdout);
-      eassert(!ferror(stdout));
-      eassert(!fflush(stdout));
+      fputs("\n", tsv_output);
+      sysassert(!ferror(tsv_output));
+      sysassert(!fflush(tsv_output));
+    }
+  }
+  progress("Commodity table scan complete.");
+}
+
+//static Rect islandnamer;
+
+DEBUG_DEFINE_SOME_DEBUGF(structcolon,colondebugf)
+
+Rect find_sunshine_widget(void) {
+  Rect sunshiner;
+
+  sunshiner.tl.x= cim->w - 1034 +  885;
+  sunshiner.br.x= cim->w - 1034 + 1020;
+  sunshiner.tl.y= 227;
+  sunshiner.br.y= 228;
+
+  ADJUST_BOX(sunshiner,"o*",>=,30, 100,MUST, tl,y,-1);
+  ADJUST_BOX(sunshiner,"o*",>=,30, 100,MUST, br,y,+1);
+  debug_rect("sunshiner",0, sunshiner);
+
+  MUST(sunshiner.br.y - sunshiner.tl.y > 20, MR(sunshiner));
+  sunshiner.br.y--;
+
+  ADJUST_BOX(sunshiner,"o",>=,20, (cim->w - 1034 + 700), MUST, tl,x,-1);
+  ADJUST_BOX(sunshiner,"o",>=,20,  cim->w,               MUST, br,x,+1);
+  debug_rect("sunshiner",1, sunshiner);
+  return sunshiner;
+}
+
+void find_islandname(RgbImage *ri) {
+  find_structure(page_images[0], 0);
+
+  Rect sunshiner= find_sunshine_widget();
+  char sunshine[MAXIMGIDENT], archisland[MAXIMGIDENT];
+
+  const unsigned char *srcp;
+  unsigned char *destp, *endp;
+  for (srcp=page_images[0]->rgb->data, destp=ri->data,
+        endp= ri->data + 3 * ri->w * ri->h;
+       destp < endp;
+       srcp++, destp++) {
+    unsigned char c= *srcp & 0xf0;
+    *destp= c | (c>>4);
+  }
+
+  identify_rgbimage(ri, sunshiner, sunshine, "sunshine widget");
+  
+  if (!memcmp(sunshine,"Vessel ",5)) {
+    Rect islandnamer;
+    
+    islandnamer.tl.x= cim->w - 1034 +  885;
+    islandnamer.br.x= cim->w - 1034 + 1020;
+    islandnamer.tl.y=                 128;
+    islandnamer.br.y=                 156;
+
+    ADJUST_BOX(islandnamer,"o",>=,5, 0,      MUST, tl,y,+1);
+    ADJUST_BOX(islandnamer,"o",>=,5, cim->h, MUST, br,y,-1);
+
+    ADJUST_BOX(islandnamer,"o",>=,1, 0,      MUST, tl,x,+1);
+    ADJUST_BOX(islandnamer,"o",>=,1, cim->w, MUST, br,x,-1);
+
+    debug_rect("islandnamer",0, islandnamer);
+//    int larger_islandnamebry= islandnamer.tl.y + 25;
+//    MUST(islandnamer.br.y < larger_islandnamebry,
+//      MR(islandnamer);MI(larger_islandnamebry));
+//    islandnamer.br.y = larger_islandnamebry;
+    debug_rect("islandnamer",1, islandnamer);
+
+    int x,y,i;
+    for (x=islandnamer.tl.x; x<=islandnamer.br.x; x++)
+      for (y=islandnamer.tl.y; y<=islandnamer.br.y; y++) {
+       if (RI_PIXEL(ri,x,y)[0] < 0x40) {
+         for (i=0; i<3; i++) {
+           RI_PIXEL(ri,x,y)[i]= 0;
+         }
+       }
+      }
+
+    identify_rgbimage(ri, islandnamer, archisland, "island");
+  } else if (!strcmp(sunshine,"Land - Ahoy!")) {
+    Rect islandnamer;
+
+    islandnamer.tl.x= (sunshiner.tl.x + sunshiner.br.x) / 2;
+    islandnamer.tl.y= sunshiner.tl.y + 100;
+    islandnamer.br= islandnamer.tl;
+    debug_rect("islandnamer",__LINE__, islandnamer);
+    
+    WALK_UNTIL_MUST(islandnamer.tl,y, -1, sunshiner.br.y, 'H');
+    WALK_UNTIL_MUST(islandnamer.tl,x, -1, 0,              'o');
+    WALK_UNTIL_MUST(islandnamer.br,x, +1, cim->w,         'o');
+    debug_rect("islandnamer",__LINE__, islandnamer);
+
+#define RW (RECT_W(islandnamer))
+#define RH (RECT_H(islandnamer))
+
+    ADJUST_BOX(islandnamer,"O",>=,RW-4, cim->h, MUST,br,y,+1);
+    debug_rect("islandnamer",__LINE__, islandnamer);
+
+    islandnamer.br.y += 2;
+
+    ADJUST_BOX(islandnamer,"*",<,RW, cim->h, MUST,br,y,+1);
+    debug_rect("islandnamer",__LINE__, islandnamer);
+
+    islandnamer.tl.y= islandnamer.br.y-1;
+    islandnamer.br.y= islandnamer.br.y+1;
+    debug_rect("islandnamer",__LINE__, islandnamer);
+
+    ADJUST_BOX(islandnamer,"*",>=,RW, cim->h, MUST,br,y,+1);
+    debug_rect("islandnamer",__LINE__, islandnamer);
+
+    ADJUST_BOX(islandnamer,"*",<, RH, cim->w, MUST,tl,x,+1);
+    debug_rect("islandnamer",__LINE__, islandnamer);
+
+    MUST( RECT_H(islandnamer) <= 30, MR(islandnamer));
+
+    Point p;
+    int nspaces=1, might_be_colon=0;
+    uint32_t colon_pattern= 0;
+    p.y=-1;
+
+    for (p.x=islandnamer.br.x; p.x>islandnamer.tl.x; p.x--) {
+      colondebugf("structcolon: x=%4d nsp=%2d mbc=%d cp=%08"PRIx32" ",
+                 p.x, nspaces, might_be_colon, colon_pattern);
+
+      uint32_t pattern=0;
+      int runs[32], nruns=0;
+      runs[0]=0; runs[1]=0;
+      
+      for (p.y=islandnamer.tl.y; p.y<=islandnamer.br.y; p.y++) {
+       pattern <<= 1;
+       switch (get_p(p)) {
+       case '*': if (runs[nruns]) { nruns++; runs[nruns]=0; }          break;
+       case 'O': runs[nruns]++;              pattern |= 1u;            break;
+       default:                              pattern |= 1UL<<31;       break;
+       }
+      }
+
+      colondebugf(" pat=%08"PRIx32" nruns=%d runs[]={%d,%d..} ",
+                 pattern, nruns, runs[0],runs[1]);
+
+      if (!pattern) {
+       if (might_be_colon)
+         /* omg it _is_ a colon */
+         goto colon_found;
+       nspaces++;
+       might_be_colon=0;
+      } else {
+       if (!(pattern & 1UL<<31) && nruns==2 && runs[1]==runs[0]) {
+         if (!nspaces) {
+           if (pattern==colon_pattern)
+             goto ok_might_be_colon;
+         } else if (nspaces>=2) {
+           colon_pattern= pattern;
+           might_be_colon=1;
+           goto ok_might_be_colon;
+         }
+       }
+       might_be_colon=0;
+      ok_might_be_colon:
+       nspaces= 0;
+      }
+      colondebugf(" nsp=%2d mbc=%d\n", nspaces, might_be_colon);
     }
+    MUST(!"colon found", MP(p);MR(islandnamer) );
+
+  colon_found:
+    colondebugf(" found\n");
+    islandnamer.br.x= p.x;
+
+    identify_rgbimage(ri, islandnamer, archisland, "island");
+  } else {
+
+    MUST(!"sunshine shows ship or ahoy", MS(sunshine) );
+
   }
+
+  char *delim= strstr(archisland," - ");
+  assert(delim);
+  archipelago= masprintf("%.*s", (int)(delim-archisland), archisland);
+  island= masprintf("%s", delim+3);
+
 }