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