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