chiark / gitweb /
antialiasing text conversion: canonimage has 0..AAMAXVAL
[ypp-sc-tools.main.git] / pctb / structure.c
1 /*
2  * Parsing of the structure of the YPP client's displayed image
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 "structure.h"
29
30 static CanonImage *cim;
31
32 static inline char get(int x, int y) { return cim->d[y * cim->w + x]; }
33 static inline char get_p(Point p) { return get(p.x,p.y); }
34
35 DEBUG_DEFINE_DEBUGF(struct)
36
37 #define START_MAIN {200,200}
38 #define MIN_COLUMNS         6
39 #define INTERESTING_COLUMNS 7
40 #define TEXT_COLUMNS        2
41 #define MAX_COLUMNS         7
42
43 static Rect mainr = { START_MAIN,START_MAIN };
44 static int commbasey, comminty;
45 static int colrightx[INTERESTING_COLUMNS];
46 static int text_h=-1, columns=-1;
47 static OcrReader *rd;
48
49 char *archipelago, *island;
50
51 #define OTHERCOORD_x y
52 #define OTHERCOORD_y x
53
54 const CanonColourInfo canoncolourinfos[]= {
55   { 0x475A5E, '*' }, /* edge */
56   { 0x2C5F7A, '*' }, /* edge just under box heading shadow */
57   { 0xC5C7AE, '*' }, /* blank area of partial commodities list */
58   { 0x6B828C, '*' }, /* background of ship status meter area */
59   { 0x934405, '*' }, /* border of ship meter area */
60   { 0x7D9094, '+' }, /* interbox */
61   { 0x022158, 'O' }, /* ahoy /w output foreground */
62   { 0xB5B686, 'H' }, /* ahoy /w output heading background */
63
64   { 0xBDC5BF, ' ' }, /* background - pale  Sugar cane, etc. */
65   { 0xADB5AF, ' ' }, /* background - dark                   */
66   { 0xC7E1C3, ' ' }, /* background - pale  Swill, etc.      */
67   { 0xB5CFB1, ' ' }, /* background - dark                   */
68   { 0xD6CEB0, ' ' }, /* background - pale  Madder, etc.     */
69   { 0xC8C0A2, ' ' }, /* background - dark                   */
70   { 0xE0E1D3, ' ' }, /* background - pale  Lorandite, etc.  */
71   { 0xD0D1C3, ' ' }, /* background - dark                   */
72   { 0xE5E6C1, ' ' }, /* background - pale  Cloth            */
73   { 0xD7D8B3, ' ' }, /* background - dark                   */
74   { 0xEDDED9, ' ' }, /* background - pale  Dye              */
75   { 0xDACBC6, ' ' }, /* background - dark                   */
76   { 0xD3DEDF, ' ' }, /* background - pale  Paint            */
77   { 0xC5D0D1, ' ' }, /* background - dark                   */
78   { 0xDCD1CF, ' ' }, /* background - pale  Enamel           */
79   { 0xCEC3C1, ' ' }, /* background - dark                   */
80   { 0xF3F6F5, ' ' }, /* background - pale  fruit            */
81   { 0xE2E7E5, ' ' }, /* background - dark                   */
82
83   { 0x000000, 'o' }, /* foreground */
84   { 0xD4B356, ' ' }, /* background (cursor) */
85   { 0xFFFFFF, 'o' }, /* foreground (cursor) */
86
87   { 0x5B93BF, '_' }, /* selector dropdown background */
88   { 0xD7C94F, 'X' }, /* selector dropdown foreground */
89   { 0,0 }
90 };
91
92
93 static void mustfail1(const char *file, int line, const char *what) {
94   fprintf(stderr,
95  "\n\n"
96  "Unable to figure out contents of YPP client display.\n"
97  "Please check the following:\n"
98  "   * YPP client is showing commodity listing screen\n"
99  "   * YPP client has antialiased text turned off (Ye / Options / General)\n"
100  "   * YPP client window is on top (we try to raise it but your window\n"
101  "      manager might have prevented that from succeeding)\n"
102  "   * Your X display is 24bpp (NB some VNC servers use 16bpp by default)\n"
103  "\n"
104  "If all of these are true, please report this as a fault.\n\n"
105           "Technical details:"
106           " %s:%d: requirement failed:\n"
107           " %s\n",
108           file, line, what);
109 }
110 static void mustfail2(void) NORET;
111 static void mustfail2(void) {
112   fprintf(stderr, "\n\nGiving up.\n");
113   exit(8);
114 }
115
116 #define MUST(x, ifnot) do{                      \
117     if (!(x)) {                                 \
118       mustfail1(__FILE__,__LINE__,#x);          \
119       ifnot;                                    \
120       mustfail2();                              \
121     }                                           \
122   }while(0)
123
124 #define MP(v) fprintf(stderr," %s=%d,%d",#v,(v).x,(v).y)
125 #define MI(v) fprintf(stderr," %s=%d",   #v,(v))
126 #define MIL(v) fprintf(stderr," %s=%ld", #v,(v))
127 #define MRGB(v) fprintf(stderr," %s=%06lx", #v,(v))
128 #define MC(v) fprintf(stderr," %s='%c'", #v,(v))
129 #define MS(v) fprintf(stderr," %s=\"%s\"", #v,(v))
130 #define MF(v) fprintf(stderr," %s=\"%f\"", #v,(v))
131 #define MSB(v) fprintf(stderr," %s", (v))
132 #define MR(v) fprintf(stderr," %s=%d,%d..%d,%d",\
133                       #v,(v).tl.x,(v).tl.y,(v).br.x,(v).br.y)
134
135
136 #define REQUIRE_RECTANGLE(tlx,tly,brx,bry,ok) \
137  require_rectangle(tlx, tly, brx, bry, ok, __LINE__);
138
139 #define FOR_P_RECT(p,rr)                                \
140   for ((p).x=(rr).tl.x; (p).x<=(rr).br.x; (p).x++)      \
141     for ((p).y=(rr).tl.y; (p).y<=(rr).br.y; (p).y++)
142
143 static void require_rectangle_r(Rect rr, const char *ok, int lineno) {
144   Point p;
145   FOR_P_RECT(p,rr) {
146     int c= get_p(p);
147     MUST( strchr(ok,c), ({
148       MI(lineno),MR(rr);MP(p);MS(ok);
149     }));
150   }
151 }
152 static void require_rectangle(int tlx, int tly, int brx, int bry,
153                               const char *ok, int lineno) {
154   Rect rr= {{tlx,tly},{brx,bry}};
155   require_rectangle_r(rr, ok, lineno);
156 }
157
158 static void debug_rect(const char *what, int whati, Rect rr) {
159   if (!DEBUGP(rect)) return;
160   int y,w;
161   fprintf(debug, "%s %d: %d,%d..%d,%d:\n", what, whati,
162           rr.tl.x,rr.tl.y, rr.br.x,rr.br.y);
163   w= rr.br.x - rr.tl.x + 1;
164   for (y=rr.tl.y; y<=rr.br.y; y++) {
165     fprintf(debug, "%4d%*s|", y, rr.tl.x,"");
166     fwrite(cim->d + y*cim->w + rr.tl.x, 1, w, debug);
167     fputc('|',debug);
168     fputc('\n',debug);
169   }
170   debug_flush();
171 }
172
173 static int commod_selector_matches(Rect search, const char *const *all,
174                                    int allh, int allw) {
175   int alloffy, alloffx;
176   for (alloffy=0; alloffy < search.br.y; alloffy++) {
177     if (alloffy+allh-1 < search.tl.y) continue;
178     for (alloffx=search.tl.x; alloffx+allw-1 <= search.br.x; alloffx++) {
179       int good=0, bad=0;
180       int x,y;
181       for (x=0; x<allw; x++)
182         for (y=0; y<allh; y++) {
183           int want= all[y][x];
184           if (want==' ') continue;
185           if (get(alloffx+x, alloffy+y) == want)
186             good++;
187           else
188             bad++;
189         }
190       debugf("CHECKCOMMOD alloff=%d,%d good=%d bad=%d\n",
191              alloffx,alloffy, good,bad);
192       if (good > 20*bad)
193         return 1;
194     }
195   }
196   return 0;
197 }
198
199 #define WALK_UNTIL(point,coord,increm,last,edge)                        \
200   for (;;) {                                                            \
201     if ((point).coord == (last)+(increm)) break;                        \
202     if (get_p((point)) == (edge)) { (point).coord -= (increm); break; } \
203     (point).coord += (increm);                                          \
204   }
205
206 #define WALK_UNTIL_MUST(point,coord,increm,last,edge)   \
207   do {                                                  \
208     WALK_UNTIL(point,coord,increm,last,edge);           \
209     MUST( (point).coord != (last)+(increm),             \
210           MP(point); MI(increm); MI(last); MC(edge);    \
211           );                                            \
212   }while(0)
213
214 #define ADJUST_BOX(search,insidechrs,want, lim,LIMIT_MUST, TLBR,XY,increm) \
215   for (;;) {                                                               \
216     LIMIT_MUST( (search).tl.XY != (search).br.XY &&                        \
217                 (search).tl.XY != (lim),                                   \
218                 MR((search));MSB(#TLBR);MSB(#XY) );                        \
219     int got=0;                                                             \
220     Point p=(search).tl;                                                   \
221     for (p.XY=(search).TLBR.XY;                                            \
222          p.OTHERCOORD_##XY <= (search).br.OTHERCOORD_##XY;                 \
223          p.OTHERCOORD_##XY++)                                              \
224       got += !!strchr(insidechrs, get_p(p));                               \
225     if (got >= (want))                                                     \
226       break;                                                               \
227     (search).TLBR.XY += increm;                                            \
228   }
229
230 void find_structure(CanonImage *im, int *max_relevant_y_r) {
231   cim= im;
232   
233   Rect whole = { {0,0}, {cim->w-1,cim->h-1} };
234
235   if (DEBUGP(rect)) {
236     int xscaleunit, y,x;
237     for (y=0, xscaleunit=1; y<4; y++, xscaleunit*=10) {
238       fprintf(debug,"     ");
239       for (x=0; x<=cim->w; x++) {
240         if (x % xscaleunit) fputc(' ',debug);
241         else fprintf(debug,"%d",(x / xscaleunit)%10);
242       }
243       fputc('\n',debug);
244     }
245   }
246
247   WALK_UNTIL_MUST(mainr.tl, x,-1, whole.tl.x, '*');
248   WALK_UNTIL_MUST(mainr.tl, y,-1, whole.tl.y, '*');
249   WALK_UNTIL_MUST(mainr.br, x,+1, whole.br.x, '*');
250   WALK_UNTIL_MUST(mainr.br, y,+1, whole.br.y, '*');
251
252   REQUIRE_RECTANGLE(mainr.tl.x-1, mainr.tl.y, mainr.tl.x-1, mainr.br.y, "*");
253   REQUIRE_RECTANGLE(mainr.br.x+1, mainr.tl.y, mainr.br.x+1, mainr.br.y, "*");
254   REQUIRE_RECTANGLE(mainr.tl.x, mainr.tl.y-1, mainr.br.x, mainr.tl.y-1, "*");
255   REQUIRE_RECTANGLE(mainr.tl.x, mainr.br.y+1, mainr.br.x, mainr.br.y+1, "*");
256
257 #define CHECK_STRIP_BORDER(tlbr,xy,increm)              \
258   do {                                                  \
259     Point csb_p;                                        \
260     Rect csb_r;                                         \
261     csb_p= mainr.tl;                                    \
262     csb_p.xy= mainr.tlbr.xy;                            \
263     if (get_p(csb_p)=='+') {                            \
264       csb_r= mainr;                                     \
265       csb_r.tl.xy= csb_p.xy;                            \
266       csb_r.br.xy= csb_p.xy;                            \
267       require_rectangle_r(csb_r, "+", __LINE__);        \
268       mainr.tlbr.xy += increm;                          \
269     }                                                   \
270   } while(0)
271
272   debug_rect("mainr",0, mainr);
273
274   CHECK_STRIP_BORDER(tl,x,+1);
275   CHECK_STRIP_BORDER(tl,y,+1);
276   CHECK_STRIP_BORDER(br,x,-1);
277   CHECK_STRIP_BORDER(br,y,-1);
278
279   debug_rect("mainr",1, mainr);
280
281   Point up = START_MAIN;
282   WALK_UNTIL_MUST(up, y,-1, mainr.tl.y, '+');
283
284   Point down = START_MAIN;
285   down.y++;
286   WALK_UNTIL_MUST(down, y,+1, mainr.br.y, '+');
287
288   commbasey= up.y;
289   comminty= down.y - up.y + 2;
290
291   Point across= { mainr.tl.x, commbasey };
292   int colno=0;
293   for (;;) {
294     MUST( get_p(across) != '+', MI(colno);MP(across);MR(mainr);MI(commbasey) );
295     WALK_UNTIL(across, x,+1, mainr.br.x, '+');
296     MUST( colno < MAX_COLUMNS, MP(across);MR(mainr);MI(commbasey); );
297     int colrx= across.x;
298     if (colrx > mainr.br.x) colrx= mainr.br.x;
299     if (colno < INTERESTING_COLUMNS)
300       colrightx[colno]= colrx;
301       
302     colno++;
303     
304     if (across.x >= mainr.br.x-1)
305       break;
306
307     across.x++;
308     REQUIRE_RECTANGLE(across.x,mainr.tl.y, across.x,mainr.br.y, "+");
309     across.x++;
310   }
311   MUST( colno >= MIN_COLUMNS, MI(colno);MR(mainr);MP(across); );
312
313 #define SET_ONCE(var,val) do{                                           \
314     int v= (val);                                                       \
315     if ((var)==-1) (var)= v;                                            \
316     else MUST( (var) == v, MSB(#var);MI((var));MI(v);MR(mainr); );      \
317   }while(0)
318
319   SET_ONCE(columns, colno);
320   SET_ONCE(text_h, comminty - 1);
321   if (max_relevant_y_r)
322     SET_ONCE(*max_relevant_y_r, mainr.br.y + 10);
323 }                   
324
325 void check_correct_commodities(void) {
326   Rect search= { { 50,39 }, { 130,59 } };
327
328   ADJUST_BOX(search,"_",10, cim->h, MUST, tl,y,+1);
329   ADJUST_BOX(search,"_",10, 0,      MUST, br,y,-1);
330
331   debug_rect("commodselr",1, search);
332
333   static const char *all_small[]= {
334     "   ___________________________________   ",
335     "  ________X____X__X____________________  ",
336     " ________ X___ X_ X_____XXXXXXXXXXX_____ ",
337     "_________X_X__ X_ X______XXXXXXXXX_______",
338     "________ X X__ X_ X_______XXXXXXX________",
339     "________X_ _X_ X_ X________XXXXX_________",
340     "_______ X__ X_ X_ X_________XXX__________",
341     "_______XXXXXXX X_ X__________X___________",
342     " _____ X     X X_ X______________________",
343     "  ____X_____ _XX_ X______________________",
344     "   __ _______  __ ______________________ ",
345   };
346   static const char *all_big[]= {
347     "???_______________________________________???",
348     "??_________________________________________??",
349     "?_________X______X___X______________________?",
350     "_________?X_____?X__?X______XXXXXXXXXXX______",
351     "_________X_X____?X__?X_______XXXXXXXXX_______",
352     "________?X?X____?X__?X________XXXXXXX________",
353     "________X_?_X___?X__?X_________XXXXX_________",
354     "_______?X__?X___?X__?X__________XXX__________",
355     "_______?XXXXX___?X__?X___________X___________",
356     "_______X????_X__?X__?X_______________________",
357     "?_____?X____?X__?X__?X_______________________",
358     "??____X_____?_X_?X__?X_______________________",
359     "???__?_______?__?___?_______________________?",
360   };
361
362 #define COMMOD_SELECTOR_MATCHES(all)                            \
363   commod_selector_matches(search, all,                          \
364                           sizeof((all))/sizeof((all)[0]),       \
365                           strlen((all)[0]))
366
367   if (!(COMMOD_SELECTOR_MATCHES(all_small) ||
368         COMMOD_SELECTOR_MATCHES(all_big)))
369     fatal("Commodities selector not set to `All'.");
370 }
371
372 CanonImage *alloc_canon_image(int w, int h) {
373   CanonImage *im= mmalloc(sizeof(CanonImage) + w*h);
374   im->w= w;
375   im->h= h;
376   memset(im->d,'?',w*h);
377   return im;
378 }
379
380 static void file_read_image_ppm(FILE *f) {
381   struct pam inpam;
382   unsigned char rgb_buf[3];
383   CanonImage *im;
384
385   pnm_readpaminit(f, &inpam, sizeof(inpam));
386   if (!(inpam.maxval == 255 &&
387         inpam.bytes_per_sample == 1 &&
388         inpam.format == RPPM_FORMAT))
389     fatal("PNM screenshot(s) file must be 8bpp 1 byte per sample RGB");
390
391   CANONICALISE_IMAGE(im, inpam.width, inpam.height, {
392     int r= fread(&rgb_buf,1,3,f);
393     sysassert(!ferror(f));
394     if (r!=3) fatal("PNM screenshot(s) file ends unexpectedly");
395
396     rgb=
397         ((unsigned long)rgb_buf[0]<<16) |
398         ((unsigned long)rgb_buf[1]<<8) |
399                        (rgb_buf[2]);
400
401   });
402
403   sysassert(!ferror(screenshot_file));
404
405   if (!(npages < MAX_PAGES))
406     fatal("Too many images in screenshots file; max is %d.\n", MAX_PAGES);
407
408   page_images[npages++]= im;
409 }
410
411 void read_one_screenshot(void) {
412   progress("reading screenshot...");
413   file_read_image_ppm(screenshot_file);
414   progress_log("read screenshot.");
415 }
416
417 void read_screenshots(void) {
418   struct stat stab;
419   
420   sysassert(! fstat(fileno(screenshot_file), &stab) );
421   
422   for (;;) {
423     if (S_ISREG(stab.st_mode)) {
424       long pos= ftell(screenshot_file);
425       if (pos == stab.st_size) break;
426     } else {
427       int c= fgetc(screenshot_file);
428       if (c==EOF) break;
429       ungetc(c, screenshot_file);
430     }
431     progress("reading screenshot %d...",npages);
432     file_read_image_ppm(screenshot_file);
433   }
434   sysassert(!ferror(screenshot_file));
435   progress_log("read %d screenshots.",npages);
436 }
437
438 static void find_commodity(int offset, Rect *rr) {
439   /* rr->tl.x==-1 if offset out of range */
440   rr->tl.y= commbasey - offset*comminty;
441   rr->br.y= rr->tl.y + comminty-2;
442   if (rr->tl.y < mainr.tl.y || rr->br.y > mainr.br.y) { rr->tl.x=-1; return; }
443   
444   rr->tl.x= mainr.tl.x;
445   rr->br.x= mainr.br.x;
446
447   if (rr->tl.y > mainr.tl.y)
448     REQUIRE_RECTANGLE(rr->tl.x,rr->tl.y-1, rr->br.x,rr->tl.y-1, "+");
449   if (rr->br.y < mainr.tl.y)
450     REQUIRE_RECTANGLE(rr->tl.x,rr->br.y+1, rr->br.x,rr->br.y+1, "+");
451 }
452
453 static void find_table_entry(Rect commod, int colno, Rect *cell) {
454   cell->tl.y= commod.tl.y;
455   cell->br.y= commod.br.y;
456   cell->tl.x= !colno ? commod.tl.x : colrightx[colno-1]+2;
457   cell->br.x=                        colrightx[colno];
458   debug_rect("cell", colno, *cell);
459
460   const RgbImage *ri= cim->rgb;
461   
462   Rgb background= ri_rgb(ri, cell->br.x, cell->br.y);
463   long bg_count=0, white_count=0, black_count=0;
464   Point p;
465   FOR_P_RECT(p,*cell) {
466     Rgb here= ri_rgb(ri, p.x, p.y);
467     if (here == background) bg_count++;
468     else if (here == 0) black_count++;
469     else if (here == 0xffffffU) white_count++;
470   }
471   long total_count= RECT_W(*cell) * RECT_H(*cell);
472   MUST( bg_count > 8*total_count / 10,
473         MR(*cell);MIL(bg_count);MIL(white_count);MIL(black_count) );
474   if (bg_count == total_count)
475     return;
476
477   MUST( !!black_count != !!white_count,
478         MR(*cell);MIL(bg_count);MIL(white_count);MIL(black_count) );
479
480   debugf("TABLEENTRY col=%d %d,%d..%d,%d bg=%ld white=%ld black=%ld\n",
481          colno, cell->tl.x,cell->tl.y, cell->br.x,cell->br.y,
482          bg_count, white_count, black_count);
483   
484   Rgb foreground= white_count ? 0xffffffU : 0;
485   int monochrome= 1;
486
487   FOR_P_RECT(p,*cell) {
488     Rgb here= ri_rgb(ri, p.x, p.y);
489     double alpha[3], alpha_mean=0;
490     int i;
491     for (i=0; i<3; i++) {
492       unsigned char here_chan= here       >> (i*8);
493       unsigned char bg_chan=   background >> (i*8);
494       unsigned char fg_chan=   foreground >> (i*8);
495       double alpha_chan=
496         ((double)here_chan - (double)bg_chan) /
497         ((double)fg_chan   - (double)bg_chan);
498       alpha[i]= alpha_chan;
499       alpha_mean += alpha_chan * (1/3.0);
500     }
501
502     double thresh= 1.0/AAMAXVAL;
503     double alpha_min= alpha_mean - thresh;
504     double alpha_max= alpha_mean + thresh;
505     for (i=0; i<3; i++)
506       MUST( alpha_min <= alpha[i] && alpha[i] <= alpha_max,
507             MI(i);MRGB(here);MRGB(background);MRGB(foreground);
508             MF(alpha_min);MF(alpha[i]);MF(alpha_max) );
509
510     MUST( 0 <= alpha_mean && alpha_mean <= 1,
511           MRGB(here);MRGB(background);MRGB(foreground);
512           MF(alpha_mean) );
513     int here_int= AAMAXVAL*alpha_mean;
514     if (!(here_int==0 || here_int==AAMAXVAL)) monochrome=0;
515     cim->d[p.y * cim->w + p.x]= '0' + here_int;
516   }
517
518   debug_rect("cell0M", colno, *cell);
519
520   require_rectangle_r(*cell, "0123456789", __LINE__);
521 }
522
523 static void ocr_rectangle(Rect r, const OcrCellType ct, FILE *tsv_output) {
524   OcrResultGlyph *results, *res;
525
526   int w= r.br.x - r.tl.x + 1;
527   Pixcol cols[w+1];
528   int x,y;
529   for (x=0; x<w; x++) {
530     Pixcol cx, rv;
531     for (y=0, cx=0, rv=1; y<text_h; y++, rv<<=1) {
532       Point here= { x+r.tl.x, y+r.tl.y };
533       int pixel= get_p(here);
534       switch (pixel) {
535       case ' ':                      break;
536       case '0':                      break;
537       case '0'+AAMAXVAL:  cx |= rv;  break;
538       default:
539         MUST(!"wrong pixel",
540              MC(pixel);MP(here);MSB(ocr_celltype_name(ct));MR(r); );
541       }
542     }
543     cols[x]= cx;
544   }
545   cols[w]= 0;
546
547   results= ocr(rd,ct,w,cols);
548   for (res=results; res->s; res++)
549     fputs(res->s,tsv_output);
550 }
551
552 void analyse(FILE *tsv_output) {
553   Rect thisr, entryr;
554   int page, tryrect, colno;
555
556   for (page=0; page<npages; page++) {
557     find_structure(page_images[page], 0);
558
559     if (!page)
560       check_correct_commodities();
561
562     if (!rd)
563       rd= ocr_init(text_h);
564
565     progress("Scanning page %d...",page);
566
567     for (tryrect= +cim->h; tryrect >= -cim->h; tryrect--) {
568       find_commodity(tryrect, &thisr);
569       if (thisr.tl.x < 0)
570         continue;
571       debug_rect("commod",tryrect, thisr);
572
573       const char *tab= "";
574       for (colno=0; colno<columns; colno++) {
575         find_table_entry(thisr,colno,&entryr);
576         fputs(tab, tsv_output);
577         ocr_rectangle(entryr,
578                       colno<TEXT_COLUMNS
579                       ? &ocr_celltype_text
580                       : &ocr_celltype_number,
581                       tsv_output);
582         tab= "\t";
583       }
584       fputs("\n", tsv_output);
585       sysassert(!ferror(tsv_output));
586       sysassert(!fflush(tsv_output));
587     }
588   }
589   progress("Commodity table scan complete.");
590 }
591
592 //static Rect islandnamer;
593
594 DEBUG_DEFINE_SOME_DEBUGF(structcolon,colondebugf)
595
596 Rect find_sunshine_widget(void) {
597   Rect sunshiner;
598
599   sunshiner.tl.x= cim->w - 1034 +  885;
600   sunshiner.br.x= cim->w - 1034 + 1020;
601   sunshiner.tl.y= 227;
602   sunshiner.br.y= 228;
603
604   ADJUST_BOX(sunshiner,"o*",30, 100,MUST, tl,y,-1);
605   ADJUST_BOX(sunshiner,"o*",30, 100,MUST, br,y,+1);
606   debug_rect("sunshiner",0, sunshiner);
607
608   MUST(sunshiner.br.y - sunshiner.tl.y > 20, MR(sunshiner));
609   sunshiner.br.y--;
610
611   ADJUST_BOX(sunshiner,"o",20, (cim->w - 1034 + 700), MUST, tl,x,-1);
612   ADJUST_BOX(sunshiner,"o",20,  cim->w,               MUST, br,x,+1);
613   debug_rect("sunshiner",1, sunshiner);
614   return sunshiner;
615 }
616
617 void find_islandname(RgbImage *ri) {
618   find_structure(page_images[0], 0);
619
620   Rect sunshiner= find_sunshine_widget();
621   char sunshine[MAXIMGIDENT], archisland[MAXIMGIDENT];
622
623   const unsigned char *srcp;
624   unsigned char *destp, *endp;
625   for (srcp=page_images[0]->rgb->data, destp=ri->data,
626          endp= ri->data + 3 * ri->w * ri->h;
627        destp < endp;
628        srcp++, destp++) {
629     unsigned char c= *srcp & 0xf0;
630     *destp= c | (c>>4);
631   }
632
633   identify_rgbimage(ri, sunshiner, sunshine, "sunshine widget");
634   
635   if (!memcmp(sunshine,"Vessel ",5)) {
636     Rect islandnamer;
637     
638     islandnamer.tl.x= cim->w - 1034 +  885;
639     islandnamer.br.x= cim->w - 1034 + 1020;
640     islandnamer.tl.y=                 128;
641     islandnamer.br.y=                 156;
642
643     ADJUST_BOX(islandnamer,"o",5, 0,      MUST, tl,y,+1);
644     ADJUST_BOX(islandnamer,"o",5, cim->h, MUST, br,y,-1);
645
646     ADJUST_BOX(islandnamer,"o",1, 0,      MUST, tl,x,+1);
647     ADJUST_BOX(islandnamer,"o",1, cim->w, MUST, br,x,-1);
648
649     debug_rect("islandnamer",0, islandnamer);
650 //    int larger_islandnamebry= islandnamer.tl.y + 25;
651 //    MUST(islandnamer.br.y < larger_islandnamebry,
652 //       MR(islandnamer);MI(larger_islandnamebry));
653 //    islandnamer.br.y = larger_islandnamebry;
654     debug_rect("islandnamer",1, islandnamer);
655
656     int x,y,i;
657     for (x=islandnamer.tl.x; x<=islandnamer.br.x; x++)
658       for (y=islandnamer.tl.y; y<=islandnamer.br.y; y++) {
659         if (RI_PIXEL(ri,x,y)[0] < 0x40) {
660           for (i=0; i<3; i++) {
661             RI_PIXEL(ri,x,y)[i]= 0;
662           }
663         }
664       }
665
666     identify_rgbimage(ri, islandnamer, archisland, "island");
667   } else {
668     Rect islandnamer;
669
670     islandnamer.tl.x= (sunshiner.tl.x + sunshiner.br.x) / 2;
671     islandnamer.tl.y= sunshiner.tl.y + 100;
672     islandnamer.br= islandnamer.tl;
673     debug_rect("islandnamer",__LINE__, islandnamer);
674     
675     WALK_UNTIL_MUST(islandnamer.tl,y, -1, sunshiner.br.y, 'H');
676     WALK_UNTIL_MUST(islandnamer.tl,x, -1, 0,              'o');
677     WALK_UNTIL_MUST(islandnamer.br,x, +1, cim->w,         'o');
678     debug_rect("islandnamer",__LINE__, islandnamer);
679
680     require_rectangle_r(islandnamer, "O*", __LINE__);
681
682     int rw= RECT_W(islandnamer);
683     ADJUST_BOX(islandnamer,"O",rw-4, cim->h, MUST,br,y,+1);
684     debug_rect("islandnamer",__LINE__, islandnamer);
685
686     islandnamer.br.y += 2;
687     ADJUST_BOX(islandnamer,"O",1,    cim->h, MUST,br,y,+1);
688     debug_rect("islandnamer",__LINE__, islandnamer);
689
690     islandnamer.tl.y= islandnamer.br.y-1;
691     islandnamer.br.y= islandnamer.br.y+1;
692     ADJUST_BOX(islandnamer,"*",rw,   cim->h, MUST,br,y,+1);
693     ADJUST_BOX(islandnamer,"O",1,    cim->w, MUST,tl,x,+1);
694     debug_rect("islandnamer",__LINE__, islandnamer);
695
696     MUST( RECT_H(islandnamer) <= 31, MR(islandnamer));
697
698     Point p;
699     int nspaces=1, might_be_colon=0;
700     uint32_t colon_pattern= 0;
701     p.y=-1;
702
703     for (p.x=islandnamer.br.x; p.x>islandnamer.tl.x; p.x--) {
704       colondebugf("structcolon: x=%4d nsp=%2d mbc=%d cp=%08"PRIx32" ",
705                   p.x, nspaces, might_be_colon, colon_pattern);
706
707       uint32_t pattern=0;
708       int runs[32], nruns=0;
709       runs[0]=0; runs[1]=0;
710       
711       for (p.y=islandnamer.tl.y; p.y<=islandnamer.br.y; p.y++) {
712         pattern <<= 1;
713         switch (get_p(p)) {
714         case 'O': runs[nruns]++;                         pattern |= 1u; break;
715         case '*': if (runs[nruns]) { nruns++; runs[nruns]=0; }          break;
716         default: abort();
717         }
718       }
719
720       colondebugf(" pat=%08"PRIx32" nruns=%d runs[]={%d,%d..} ",
721                   pattern, nruns, runs[0],runs[1]);
722
723       if (!pattern) {
724         if (might_be_colon)
725           /* omg it _is_ a colon */
726           goto colon_found;
727         nspaces++;
728         might_be_colon=0;
729       } else {
730         if (nruns==2 && runs[1]==runs[0]) {
731           if (!nspaces) {
732             if (pattern==colon_pattern)
733               goto ok_might_be_colon;
734           } else if (nspaces>=2) {
735             colon_pattern= pattern;
736             might_be_colon=1;
737             goto ok_might_be_colon;
738           }
739         }
740         might_be_colon=0;
741       ok_might_be_colon:
742         nspaces= 0;
743       }
744       colondebugf(" nsp=%2d mbc=%d\n", nspaces, might_be_colon);
745     }
746     MUST(!"colon found", MP(p);MR(islandnamer) );
747
748   colon_found:
749     colondebugf(" found\n");
750     islandnamer.br.x= p.x;
751
752     identify_rgbimage(ri, islandnamer, archisland, "island");
753   }
754
755   char *delim= strstr(archisland," - ");
756   assert(delim);
757   archipelago= masprintf("%.*s", (int)(delim-archisland), archisland);
758   island= masprintf("%s", delim+3);
759
760 }