/*
This is a Optical-Character-Recognition program
Copyright (C) GPLv2 2000-2013  Joerg Schulenburg

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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

 see README for email address
 
 ToDo:
  - transform special xml bar code symbols (<>&) to xml symbols (&lt;&gt;&amp;)
 
*/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/* #include <math.h> -- we do not want unnecessary dependencies */
#include "pgm2asc.h"
#include "gocr.h"
#include "pnm.h"
#include "unicode_defs.h" /* define UNKNOWN + PICTURE */

#ifndef DO_DEBUG       /* can be defined outside (configure --with-debug) */
#define DO_DEBUG 0     /* 0 is the default */
#endif

#undef g_debug
#if DO_DEBUG
# define g_debug(a)  if (OCR_JOB->cfg.verbose&1) { a }
#else
# define g_debug(a)
#endif

/*
     detect barcode and add a XML-string to the box (obj-pointer, ToDo)
     ToDo: barcode-output stderr->stdout
*/

double sqr(double x) { return(x*x); }

/* ----------------------------- code128 ---------------------------- *
 *    "BSBSBS", B=Bar, S=Space, better using 2*6=12bit-integer?       */
#define Num128 107
const char *code128[Num128+1]={ /* can be generated by an algorithm? */
/* 00 */"212222","222122","222221","121223","121322","131222","122213","122312",
/* 08 */"132212","221213","221312","231212","112232","122132","122231","113222",
/* 16 */"123122","123221","223211","221132","221231","213212","223112","312131",
/* 24 */"311222","321122","321221","312212","322112","322211","212123","212321",
/* 32 */"232121","111323","131123","131321","112313","132113","132311","211313",
/* 40 */"231113","231311","112133","112331","132131","113123","113321","133121",
/* 48 */"313121","211331","231131","213113","213311","213131","311123","311321",
/* 56 */"331121","312113","312311","332111","314111","221411","431111","111224",
/* 64 */"111422","121124","121421","141122","141221","112214","112412","122114",
/* 72 */"122411","142112","142211","241211","221114","413111","241112","134111",
/* 80 */"111242","121142","121241","114212","124112","124211","411212","421112",
/* 88 */"421211","212141","214121","412121","111143","111341","131141","114113",
/* 96 */"114311","411113","411311","113141","114131","311141","411131","211412",
/*104 */"211214","211232","2331112","???"};

/*
      code128: see code128.tex by Petr Olsak (108 codes)
       quiet_zone: size=10 (before and after code128)
       num_bars=3*(start+chars[N]+crc+stop)+1
       B=bar S=space char=BSBSBS (size=11), stop=BSBSBSB (size=11+2)
       Width: Bar,Space=1,[2,3,4] char=11 code=11*(N+3)+2 sumB=even,sumS=odd
       startA="211412"=103 startB="211214"=104 startC="211232"=105(2dec_digits)
       mode/code 0..95        96   97   98   99  100 101 102 103 104 105 106
         1=A   x20-x5f,0-x20  F3   F2   uB   mC  mB  F4  F1  ^A  ^B  ^C   $
         2=B   x20-x7f        F3   F2   uA   mC  F4  mA  F1  ^A  ^B  ^C   $
         3=C   "00"-"95"     "96" "97" "98" "99" mB  mA  F1  ^A  ^B  ^C   $
        uA,uB: switch mode for next char, mA,mB: switch mode permanently
       crc=(start+1*char1+2*char2+3*char3+...+N*charN) mod 103
       $=stop="2331112"=106 (4bars, with=13)  => start/end==211
       return num of chars or string
       StartStopWidths: Bars=123 Spaces=123
       
       size  B+W    even-variants      odd-variants      num_codes 
        11 = 8+3 = (1+3+4,2+2+4,2+3+3)+(1+1+1)       => (6+3+3)*(1)   =  12
           = 6+5 = (1+1+4,1+2+3,2+2+2)+(1+1+3,1+2+2) => (3+6+1)*(3+3) =  60
           = 4+7 = (1+1+2)+(1+2+4,1+3+3,2+2+3)       => (3)*(6+3+3)   =  36
                                                                  sum = 108
 */
  /* example: barcode -E -e 128c -b 1434600120000884 >a.eps */
  /* example: barcode -E -e 128b -b 14Test41         >a.eps */
  /* example: barcode -E -e 128raw -b 105 17 14 30   >a.eps */

char *decode_code128(int *wb, int num_bars){
  int i, w, i1, i2, i3=0, i4, i4old, i5=0, crc, mode=1;
  int minB, maxB, minS, maxS; /* min/max bars/spaces sample: 3-10 1-8 */
  int wb6[6], addS, addB; /* normalized bars, normalization summand */
  double dww, dw, err, min_err;  char cc, *buf;
  char *result=NULL; /* malloc and store the result */
  
  minB=maxB=wb[0];
  minS=maxS=wb[1];
  /* sample090916 showed maxS = minB so we normalize first */
  for(i=0; i<2*num_bars-1; i++){
    if (i&1) { if (minS>wb[i]) minS=wb[i]; if (maxS<wb[i]) maxS=wb[i]; }
    else     { if (minB>wb[i]) minB=wb[i]; if (maxB<wb[i]) maxB=wb[i]; }
  }
  /* sample: 05 02 03 ...
     distortion: wb[0]=2*sb+db wb[1]=sb-db wb[2]=sb+db (scale+diff)
     back: sb = wb[0]-wb[2] = 2
           db = wb[2]-sb = 2wb[2]-wb[0] = 1
              = (wb[2]-wb[1]+1)/2 = 1
   */
  addS=(minB-minS+1)/2; addB=-(minB-minS)/2;
  for(w=i=0;i<2*num_bars-1;i++){ 
    w+=wb[i]+((i&1)?addS:addB); /* summ all bars and spaces */
  }
  
  /* test code128 characteristics, ToDo: look for correct start/stop 211 seq. */
  if ((num_bars-1)%3!=0 || num_bars<10 || w<11*(num_bars-1)/3+2)
    return 0;
  g_debug(fprintf(stderr," code128 BS= %d-%d %d-%d chars=%d 211... %02d %02d %02d\n",minB,maxB,minS,maxS,(num_bars-1)/3,wb[0],wb[1],wb[2]);)
  if (3*(wb[0]+addB)<4* (wb[1]+addS)
   || 3* wb[0]      <4*  wb[2]
   || 4* wb[0]      <3*(wb[1]+wb[2])
   || 3* wb[0]      >4*(wb[1]+wb[2])) return 0; /* start=211.. */
  dw=3.0*w/((num_bars-1)*11+6);
  /* get enough memory for all digits in longest mode C */
  buf   =(char *) malloc(    (num_bars-7)/3*2+1); if (!buf)    return result;
  result=(char *) malloc(256+(num_bars-7)/3*2+1);

  dww=crc=0;
  for(i4=i1=0;i1<(num_bars-1)/3;i1++) {
    for (i2=0;i2<6;i2++) wb6[i2]=wb[i1*6+i2]+((i2&1)?addS:addB);
    for(min_err=1e8,i3=Num128,i5=0;i5<Num128;i5++){ /* get best fit */
      for(err=i2=0;i2<6;i2++) err+=sqr(code128[i5][i2]-'0'-wb6[i2]/dw);
      if (err<min_err) { min_err=err; i3=i5; }
    } dww+=min_err;
    g_debug(for(i2=0;i2<6;i2++)fprintf(stderr," %2d",wb[i1*6+i2]);
      fprintf(stderr," %7s %3d err=%.3f",code128[i3],i3,min_err);)
    i4old=i4;
    if(i3<Num128){  /* valid symbol */
      if(i1==0){ if (i3>102 && i3<106) mode=i3-103+1; crc=i3; } /* start */
      if(i1>0 && i1<(num_bars-1)/3-2){
        crc+=i3*(i1); cc=0;  /* first * 1 + second * 2 + third * 3 ... */
        i5=((mode>3)?mode>>2:mode&3); mode&=3;  /* mode can be modified now */
        switch (i5) {                           /* mode=1..3=modeA..modeC */
          case 1: if (i3>=64 && i3<96) cc=i3-64;   /* modeA: x20-x5f,0-x20 */
                                  else cc=i3+32; 
                  if (i3==101) mode=1;     /* switch to mode A */
                  if (i3== 99) mode=3;     /* switch to mode C */
                  if (i3== 98) mode|=2<<2; /* shift  to mode B */
                  break;
          case 2: cc=i3+32;                        /* modeB: x20-x7f */
                  if (i3==100) mode=2;     /* switch to mode B */
                  if (i3== 99) mode=3;     /* switch to mode C */
                  if (i3== 98) mode|=1<<2; /* shift  to mode A */
                  break;
          case 3:
                  if (i3==101) mode=1;     /* switch to mode A */
                  if (i3==100) mode=2;     /* switch to mode B */
        } 
        if (i5==3 && i3<100) { buf[i4]='0'+i3/10; i4++;
                               buf[i4]='0'+i3%10; i4++; } /* modeC: 00-99 */
        if (i5!=3) {
          if (cc>=0x20 && i3<=0x7f) { buf[i4]=cc;        i4++; }  /* modeA+B: one digit */
          if (cc>=0    && cc< 0x20) { buf[i4]='^';       i4++;
                                      buf[i4]=cc+'@';    i4++; } 
        }
      }
      if(i1==(num_bars-1)/3-2){ crc=(crc+103-i3)%103; }
      if(i1==(num_bars-1)/3-1){ if(i3!=106) i3=-1; } /* stop code */
      mode &= 3;  /* remove shift */
    }
    else fprintf(stderr," %s=%02d? ",buf,i5);
    g_debug(fprintf(stderr," m%c %c%c\n",'A'-1+mode,
                  ((i4-i4old>1)?buf[i4-2]:' '), /* two digged modeC, Apr08 */
                  ((i4-i4old>0)?buf[i4-1]:' '));)
  }
  buf[i4]=0; /* end of string */
  if (result)
   sprintf(result,"<barcode type=\"128\" chars=\"%d\" code=\"%s\" "
                  "crc=\"%d\" error=\"%.3f\" />",
          i4,buf,crc,dww/((num_bars-1)));
  free(buf);
  return result;
}

/* -------------------------------------------------------------------- UPC
      EAN 13 (UPC,(1+6+1+6+1)*2bars,size=3+6*7+5+6*7+3=95) 
      EAN  8 (UPC,(1+4+1+4+1)*2bars,size=3+4*7+5+4*7+3=67)
      UPC: (10 codes)
       BSB SBSB^n SBSBS BSBS^n BSB
       bsb ...... sbsbs ...... bsb
       111 ...... 11111 ...... 111
       num_bars=2*(2*6+3) middle=SBSBS=11111 right/left=BSB=111="101"
       char: left=SBSB right=BSBS (size=7) only_dec_digits
           SS+BB = (S+S) + (B+B)     => BB:SS = 5:2 or 3:4
      size ev+odd  even  + odd       => variants     
       7 = 2 + 5 = (1+1) + (1+4,2+3) => (1)*(2+2) = 4 codes
         = 4 + 3 = (1+3,2+2) + (1+3) => (2+1)*(2) = 6 codes += 10 codes
       ToDo: make it more robust
             - return error as mean deviation
 * -------------------------------------------------------------------- */
  /* example: barcode -E -e upc -b 12345678901   >a.eps # ok */
  /* example: barcode -E -e ean -b 123456789012  >a.eps # ok */
#define NumUPC 20
const char *codeUPC[NumUPC+1]={ /* 0..9, first n = SBSB, last n = BSBS */
  "3211","2221","2122","1411","1132", /* 0,1,2,3,4 normal   (+0bit) */
  "1231","1114","1312","1213","3112", /* 5,6,7,8,9 */
  "1123","1222","2212","1141","2311", /* 0,1,2,3,4 mirrored (+1bit) */
  "1321","4111","2131","3121","2113", /* 5,6,7,8,9 */
  "????"}; /* not found */

char *decode_UPC(int *wb, int num_bars){ /* ToDo: char *dest, int len */
  int i, w, i1, i2, i3, i4, i5, crc, mirrored, ean;
  double err, min_err, dw, dww=0.0;  char digit;
  char *result=NULL, *buf=NULL; /* malloc and store the result */
  int minB, maxB, minS, maxS; /* min/max bars/spaces */
  int addS, addB; /* corrections, JS1002 sample090916 */

  minB=maxB=wb[0];
  minS=maxS=wb[1];
  /* sample090916 showed maxS = minB so we normalize first */
  for(i=0; i<2*num_bars-1; i++){
    if (i&1) { if (minS>wb[i]) minS=wb[i]; if (maxS<wb[i]) maxS=wb[i]; }
    else     { if (minB>wb[i]) minB=wb[i]; if (maxB<wb[i]) maxB=wb[i]; }
  }
  addS=(minB-minS)/2; addB=-(minB-minS)/2;
  for(w=i=0;i<2*num_bars-1;i++) w+=wb[i]+((i&1)?addS:addB);

  dw=2.0*w/((num_bars-6)*7+2*11); /* or min(wb[]) */
  crc=0;
  if ((num_bars)%2!=0 || num_bars<10 || w<7*(num_bars-6)/2+11
   || ((num_bars-6)/2)%2!=0) return 0;  /* should be balanced */
  g_debug(fprintf(stderr," UPC/EAN BS= %d-%d %d-%d\n",minB,maxB,minS,maxS);)
  /* check front BSB, middle SBSBS and end BSB */
  dww=0;
  for(i=0;i<3;i++){dww=sqr((wb[i             ]+((i&1)?addS:addB))/dw-1);if(dww>0.4)return 0;}
  for(i=0;i<5;i++){dww=sqr((wb[i+  num_bars-3]+((i&1)?addB:addS))/dw-1);if(dww>0.4)return 0;}
  for(i=0;i<3;i++){dww=sqr((wb[i+2*num_bars-4]+((i&1)?addS:addB))/dw-1);if(dww>0.4)return 0;}
  buf   =(char *)malloc(    (num_bars-6)/2+1); if (!buf)    return result;
  result=(char *)malloc(256+(num_bars-6)/2+1);

  for(ean=i5=0,i1=3;i1<2*num_bars-4;i1+=4) { /* each digit (2bars+2spaces) */
    if (i1==num_bars-3) { i1++; continue; } /* skip middle sync SBSBS */
    for (i4=NumUPC,mirrored=0,digit='?',min_err=16e8,i2=0;i2<NumUPC;i2++) {
      for (err=0,i3=0;i3<4;i3++)
        err+=sqr(codeUPC[i2][i3]-'0'-(wb[i1+i3]+(((i1+i3)&1)?addS:addB))/dw);
      if (err<min_err) { min_err=err; i4=i2; digit='0'+i2%10; mirrored=i2/10; }
    } dww+=min_err; crc+=(digit-'0')*((i5&1)?1:3); /* even*3+odd, last char is even */
    buf[i5++]=digit; if (i5<7) ean=(ean<<1)|mirrored; 
    /* ToDo: error as deviation wb from ideal */
    g_debug(fprintf(stderr,"\nDBG: UPC digit=%c mirrored=%d err=%.3f err_m=%.3f ",
                               digit,mirrored,min_err/4,dww/(i5*4));)
  }
  /* EAN has a 13th leading digit build by 3 of 6 mirorred digits */
  if (ean & 0x20) ean^=0x3f; /* UPC-E mirrored 1xxxxx => 0yyyyy */
  switch (ean) { 
    case 11: ean=1; break;
    case 13: ean=2; break;
    case 14: ean=3; break;
    case 19: ean=4; break;
    case 25: ean=5; break;
    case 28: ean=6; break;
    case 21: ean=7; break;
    case 22: ean=8; break;
    case 26: ean=9; break;
    default: ean=0; /* no or invalid EAN digit or UPC-extension */
  } crc+=ean*1;
  /* ToDo: fix possible buffer OVL, complement crc */
  buf[i5]=0;
  if (result)
   sprintf(result,"<barcode type=\"UPC\" chars=\"%d\" code=\"%d%s\" "
                  "crc=\"%d\" error=\"%.3f\" />",
          i5+1,ean,buf,(10-crc%10)%10,dww/((num_bars-6)*2));
  free(buf);
  return result;
}

    /* EAN/UPC add-on is either 2 or 5 digits.  It always starts with a
     * guard bar BSB, followed by ([digit + SB] * (N-1)) + digit. Digit is
     * SBSB.  Two digit add-on's have 7 bars, and 5 digit add ons have 16.
     */
char *decode_UPC_addon(int *wb, int num_bars){ /* ToDo: char *dest, int len */
  int i, w, i1, i2, i3, i4, i5, digits=num_bars/3;
  double err, min_err, dw, dww=0.0;  char digit;
  char *result=NULL, *buf=NULL; /* malloc and store the result */
  int minB, maxB, minS, maxS; /* min/max bars/spaces */
  int addS, addB; /* corrections, JS1002 sample090916 */

  minB=maxB=wb[0];
  minS=maxS=wb[1];
  /* sample090916 showed maxS = minB so we normalize first */
  for(i=0; i<2*num_bars-1; i++){
    if (i&1) { if (minS>wb[i]) minS=wb[i]; if (maxS<wb[i]) maxS=wb[i]; }
    else     { if (minB>wb[i]) minB=wb[i]; if (maxB<wb[i]) maxB=wb[i]; }
  }
  addS=(minB-minS)/2; addB=-(minB-minS)/2;
  if (num_bars!=7 && num_bars!=16)
    return 0;
  for(w=i=0;i<2*num_bars-1;i++) w+=wb[i];
  g_debug(fprintf(stderr," UPC_addon BS= %d-%d %d-%d\n",minB,maxB,minS,maxS);)

  dw=1.0*w/(digits*7+4 + (digits-1)*2);
  /* check front BSB, and delineators SB */
  dww=0;
  for (i=0;i<2;i++) {
    dww=sqr((wb[i]+((i&1)?addS:addB))/dw-1); if (dww>0.4) return 0; }
  dww=sqr((wb[i]+((i&1)?addS:addB))*0.5/dw-1);  if (dww>0.4) return 0;
  for (i=1;i<digits; i++) {
    for (i1=0; i1<2; i1++) {
      dww = sqr((wb[i*6 + 1 + i1]+((i1&1)?addB:addS))/dw-1);
      if (dww > 0.4) return 0;
    }
  }
  buf   =(char *)malloc(    digits+1); if (!buf)    return result;
  result=(char *)malloc(256+digits+1);

  for(i5=0,i1=3;i1<2*num_bars-1;i1+=6) { /* each digit (2bars+2spaces) */
    for (i4=NumUPC,digit='?',min_err=16e8,i2=0;i2<NumUPC;i2++) {
      for (err=0,i3=0;i3<4;i3++)
        err+=sqr(codeUPC[i2][i3]-'0'-(wb[i1+i3]+(((i1+i3)&1)?addS:addB))/dw);
      if (err<min_err) { min_err=err; i4=i2; digit='0'+i2%10; }
    }
    dww+=min_err;
    buf[i5++]=digit;
    /* ToDo: error as deviation wb from ideal */
    g_debug(fprintf(stderr,"\nDBG: UPC digit=%c err=%.3f err_m=%.3f ",
                               digit, min_err/4, dww/(i5*4));)
  }
  buf[i5]=0;
  if (result)
   sprintf(result, "<barcode type=\"UPC_addon\" chars=\"%d\" code=\"%s\" "
                   "error=\"%.3f\" />",
           i5, buf, dww/((num_bars-6)*2));
  free(buf);
  return result;
}


/* --------------------------------------------------------- *
 * code 3 of 9, 3 thick of 9 bars
 *    BSBSBSBSB<S> size=7+3*aw aw=2(3), sumS/sumB=2/1? 
 *    two widths: size=1 or size=2or3, digit_width=13(16)
 *    5 bars and 4(+1) spaces per digit, last space is not used
 *    with 2 (or 0) wide bars, 1 (or 3) wide spaces per digit
 *     => 3 of 9 => max=9*8*7=504
 *     evenBB=(0of5)+(2of5) oddSS=(1of4)+(3of4) max=44
 *  ToDo: better code -...-.-.. as 046 or 083 (even,even,odd)
 *  sample 090916: width of wide space may be smaller than narrow bar
 */
#define Num39 (40+4) /* (3of9)=(2of5)(1of4)+(0of5)(3of4), (2of5)(.-..)=0..9 */
const char *code39= /* rearranged to BBBBBSSSS<S> (bars,spaces) */
                                                "0..--..-.."
"1-...-.-..""2.-..-.-..""3--....-..""4..-.-.-..""5-.-...-.."
"6.--...-..""7...--.-..""8-..-..-..""9.-.-..-.."
"A-...-..-.""B.-..-..-.""C--.....-.""D..-.-..-.""E-.-....-."
"F.--....-.""G...--..-.""H-..-...-.""I.-.-...-.""J..--...-."
"K-...-...-""L.-..-...-""M--......-""N..-.-...-""O-.-.....-"
"P.--.....-""Q...--...-""R-..-....-""S.-.-....-""T..--....-"
"U-...--...""V.-..--...""W--...-...""X..-.--...""Y-.-..-..."
"Z.--..-...""-...---..."".-..-.-..."" .-.-.-...""*..--.-..."
/* (0of5)(3of4)=(.....)(3of4) store only 3of4? */
"$.....---.""/.....--.-""+.....-.--""%......---"
"?xxxxxxxxx";

/* example: barcode -E -e 39 -b 123abc | gs -sDEVICE=pnggray -r100 */

/* return index[] according to sorted values[], big first */
void sort(int *value, int *idx, int len){
  int i,j;
  for (j=0;j<len;j++) idx[j]=j; /* initialize */
  for(i=1;i;) {  /* bubble sort, len...len^2 steps */
    for(i=j=0;j<len-1;j++) if(value[idx[j]]<value[idx[j+1]]) {
      i=idx[j]; idx[j]=idx[j+1]; idx[j+1]=i; i=1;
    }
  } 
}

char *decode_39(int *wb, int num_bars){ /* ToDo: char *dest, int len */
  int i, w, i1, i3, i5, crc,
      idx[9], /* indices sorted by length of wb9[idx] */
      wb9[9], /* next 9 normalized bars and spaces BWBWBWBWB (JS1002) */
      addS, addB, /* normalization diffs */
      minB, maxB, minS, maxS;  /* min/max bar/space (JS1002) */
  double dw,dww,err;  char *buf;
  char *result=NULL; /* malloc and store the result */

  /* check for multiple of 5 bars and minimum start+1char+stop=15 bars */
  if ((num_bars)%5!=0 || num_bars<15) return 0;
  minB=maxB=wb[0];
  minS=maxS=wb[1];
  /* sample090916 showed maxS = minB so we normalize first */
  for(i=0; i<2*num_bars-1; i++){
    if (i&1) { if (minS>wb[i]) minS=wb[i]; if (maxS<wb[i]) maxS=wb[i]; }
    else     { if (minB>wb[i]) minB=wb[i]; if (maxB<wb[i]) maxB=wb[i]; }
  }
  addS=(minB-minS)/2; addB=-(minB-minS)/2;
  for(w=i=0; i<2*num_bars-1; i++){
#if 1
    if (i&1) { w+=wb[i]+addS; }
    else     { w+=wb[i]+addB; }
#else
    w+=wb[i];   /* summ width to w */
#endif
  }
  dw=w*1.0/(16*(num_bars/5)); /* threshold = 1.5..2 */
  /* whats best and most rigorosely for dw=threshold_width?
   *  - (1.5..2)*mean_width of every 5th space
   *  - (1.5..2)*summ(5bars+5spaces)/(13..16)
   *  - 3/4*summ(three thickest)/3
   */
  dww=crc=0; /* error and checksum (not supported yet) */
#if 0  /* should we exclude any non-standard code39? */
  /* check for correct start and end symbol * or NwNnWnWnN Narrow+Wide */
  for (i=0;i<9;i++) wb9[i]=wb[i]+((i&1)?addS:addB); /* good for sample090916 */
  if (wb9[0]>dw*2 || wb9[1]<=dw*2 || wb9[2]> dw*2) return 0; /* #  # */
  for (i=0;i<9;i++) wb9[i]=wb[2*num_bars-2-i]+((i&1)?addS:addB); /* good for sample090916 */
  if (wb9[0]>dw*2 || wb9[1]> dw*2 || wb9[2]<=dw*2) return 0; /* ## # */
#endif
  g_debug(fprintf(stderr," code39  base=%.3f B=%d-%d S=%d-%d chars=%2d\n ",dw,minB,maxB,minS,maxS,(num_bars)/5);)
  buf   =(char *)malloc(  1+(num_bars)/5); if (!buf)    return result;
  result=(char *)malloc(256+(num_bars)/5);

  for(i5=i1=0;i1<2*num_bars-3;i1+=10) {
    /* normalization, good for sample090916 */
    for (i=0;i<9;i++) wb9[i]=wb[i1+i]+((i&1)?addS:addB);
    /* ToDo: looking for three widest bars/gaps, 0 or 2 bars, 1 or 3 spaces */
    sort(wb9,idx,9);
    for(err=0,i3=3;i3<9;i3++)  // estimate error ??
      err+=sqr((wb9[idx[i3]])/dw-1.0); /* narrow=1, wide=2..3 */
    dww+=err;
    for(i3=0;i3<Num39;i3++)
      if (code39[10*i3+1+(idx[0]%2)*5+idx[0]/2]=='-'
       && code39[10*i3+1+(idx[1]%2)*5+idx[1]/2]=='-'
       && code39[10*i3+1+(idx[2]%2)*5+idx[2]/2]=='-') break;
    if (i5>0 && i5<num_bars/5-2) crc+=i3;
    buf[i5++]=code39[10*i3];

    /* ToDo: check if we have even number of black bars within 3 biggest */
    g_debug(for(i3=0;i3<9;i3++)fprintf(stderr,"%02d ",wb[i1+i3]);
       fprintf(stderr," posWide=%d,%d,%d  %c  err=%.3f\n ",
         idx[0],idx[1],idx[2],buf[i5-1],err/6);)
    { int num_ws=0;     // Jul09 ~codabar
      if (idx[0]&1) num_ws++;
      if (idx[1]&1) num_ws++;
      if (idx[2]&1) num_ws++;
      if ((num_ws&1)==0) { // num wide spaces must be 1 or 3
        free (buf); free(result); 
        g_debug(fprintf(stderr," num wide spaces = %d, abort code39\n", num_ws);)
        return 0;
      }
    }
  }
  buf[i5]=0;
  if (result)
   sprintf(result,"<barcode type=\"39\" chars=\"%d\" code=\"%s\" "
                  "crc=\"%c\" error=\"%.3f\" />",
          i5,buf,code39[(crc%44)*10],dww/((num_bars/5)*6));
  free(buf);
  return result;
}

/* code interleaved 2 of 5 numbers-only (10 bars+spaces = 2 decimal digits)
   B B B B B  <= digit1   bars=1,3,5,...
    S S S S S <= digit2 spaces=2,4,6,...
   1122447700 <= weight   digit=sum(bit*weight)%11 (except 7+4=11 means 0)
   N = narrow bar, W = wide bar, n = narrow space, w = wide space
   "NnNn"+interleaved+"WnN" (odd num W, even num w)
   18 digits/inch
   see http://www.barcode-1.net/i25code.html (Jun 2009)
   minN=0.19mm=0.0075inch
    sizeN>0.02inch: sizeW=2..3*sizeN (but constant)
    sizeN<0.02inch: sizeW=2.2..3*sizeN
    quite zones 10*sizeN or 0.25inch
    heigh=max(0.15*symbol_length,0.25inch)
    Len = (numChars*(2*(sizeW/sizeN)+3) + 6 + (sizeW/sizeN)) * sizeN
 */
#define Num25 10
const char *code25= /* is the code sorted randomly? */
"1-...-2.-..-3--...4..-.-5-.-..6.--..7...--8-..-.9.-.-.0..--.";

/* example: barcode -E -e i25 -b 123456 >a.eps */

/*
   add i25, patch by: Chris Lee, 13 Jul 2009
   ToDo: check correctness
 */
char *decode_i25(int *wb, int num_bars){ /* ToDo: char *dest, int len */
  int i, w, i1, i3, i5, crc, idx[7], pos;
  double dw, dww, err;  char *buf;
  char *result=NULL; /* malloc and store the result */

  int *wb_temp;
  int *wb_check;
  int code_chars;
  
  if ((num_bars)%5!=4) return 0; /* chars*5bars + 4 start/stop bars */
  code_chars = ((num_bars - 4) / 5) * 2;
//  dw=w*1.0/(9*(num_bars/3)); /* threshold = 1.5..2 */

  wb_temp  = (int *)malloc((code_chars * 5)*sizeof(int)); if (!wb_temp) { return NULL; }
  wb_check = (int *)malloc( 7              *sizeof(int));
  if (!wb_check) { free(wb_temp); return NULL; }
  buf   =malloc(    code_chars); 
  if (!buf)      { free(wb_temp); free(wb_check); return NULL; }

  for (i=0; i<(code_chars * 5)+7; i++) {
    if (i<4) { wb_check[i] = wb[i]; }  /* start sequence NnNn... */
    else if (i > ((code_chars*5)+3)) { /* end   sequence ...WnN  */
      wb_check[i-(code_chars*5)] = wb[i]; }
    else {
      pos = i - 4;
      /* reinterleave 0,5,1,6,2,7,3,8,4,9,... to 0,1,2,3,4,5,6,7,8,9,...  */
      // pos = (int)(10*(int)(pos/10) + 1.0*(pos%10)/2.0 + 4.5*(pos%2));
      pos = 10*(pos/10) + (pos%10)/2 + 5*(pos&1);
      wb_temp[pos] = wb[i];
    }
  }
  wb = wb_temp;

  /* check start / finish codes */
  sort(wb_check,idx,7);
  if (idx[0] != 4       /* widest bar W must be the 4th = 1st of end */
   || wb_check[idx[0]]==wb_check[idx[1]]) { /* exact 1 widest */
    free(wb_temp);
    free(wb_check);
    g_debug(fprintf(stderr," need exact 1 widest at start of end, abort\n");)
    return 0;
  }

  for(w=i=0;    i<5*code_chars;i++  ) w+=wb[i];   /* summ width */
  dw=w*1.0/(16*(num_bars/5)); /* threshold = 1.5..2 */
  /* whats best and most rigorosely for dw=threshold_width?
   *  - (1.5..2)*mean_width of every 5th space
   *  - (1.5..2)*summ(5bars+5spaces)/(13..16)
   *  - 3/4*summ(three thickest)/3
   */
  dww=crc=0; /* error and checksum (not supported yet) */
#if 0  /* should we exclude any non-standard code39? */
  /* check for correct start and end symbol * or NwNnWnWnN Narrow+Wide */
  i=2*num_bars-2;
  if (wb[  0]>dw*2 || wb[  1]<=dw*2 || wb[  2]> dw*2) return 0;
  if (wb[i-0]>dw*2 || wb[i-1]> dw*2 || wb[i-2]<=dw*2) return 0;
#endif
  g_debug(fprintf(stderr," code25  base=%.3f chars=%2d\n ",dw,code_chars);)

  for(i5=i1=0;i1<5*code_chars;i1+=5) {
    /* ToDo: looking for three widest bars/gaps */
    sort(wb+i1,idx,5);
    for(err=0,i3=2;i3<5;i3++)
       err+=sqr(wb[i1+idx[i3]]/dw-1.0); /* narrow=1, wide=2..3 */
    dww+=err;
    for(i3=0;i3<Num25;i3++)
      if (code25[6*i3+1+idx[0]]=='-'
       && code25[6*i3+1+idx[1]]=='-') break;
    //if (i5>0 && i5<num_bars/3-2) crc+=i3;
    buf[i5++]=code25[6*i3];

    /* ToDo: check if we have even number of black bars within 3 biggest */
    g_debug(for(i3=0;i3<5;i3++)fprintf(stderr,"%02d ",wb[i1+i3]);
       fprintf(stderr," posWide=%d,%d  %c  err=%.3f\n ",
         idx[0], idx[1], buf[i5-1], err/6);)
    {
      /* check that we have exact 2 widest bars, 2nd widest > 3th widest */
      if (wb[i1+idx[1]]==wb[i1+idx[2]]) { 
        free(buf);
        free(wb_temp); 
        free(wb_check);
        g_debug(fprintf(stderr," need exact 2 widest, abort\n");)
        return 0;
      }
    }
  }
  buf[i5]=0;
  result=malloc(256+code_chars);
  if (result) // ToDo: fix CRC (not defined?)
   sprintf(result,"<barcode type=\"i25\" chars=\"%d\" code=\"%s\" crc=\"%c\""
     " error=\"%.3f\" />", i5,buf,code25[(crc%10)*10],dww/((num_bars/5)*6));

  free(wb_temp);
  free(wb_check);
  free(buf);
  return result;
}

/* code codabar, numbers only, 4 bars per char (1*wide bar, 1*wide space) 
   robust code (dot-matrix printer)
   characters have same length (distance between 1st bar to 4th space)
    ??? codeproject: 6*n+2*w=12 or 5*n+3*w=14
    ??? suchymips.de:
      variant 1: 18 different bar widths (Monarch code)
      variant 2:  2 different bar widths (Codabar Matrix or ABC-Codabar)
   9..11 digits/inch, N=narrow bar, W=wide bar, n=narrow space, w=wide space
   see http://www.barcodeman.com/info/codabar.php (Jul 2009)
   minN=0.17mm=0.0065inch, 11 digits/inch = 0.0909 = 14*minN
   2of7 + extensions
   extensions: 1 wide bar + 2 wide spaces (no narrow space between 2 wide)
    4 start/stop sets = a/t, b/m, c/ *, d/e
   - mean wide = thickest of 4 bars
   - mean narrow = thinnest of 4 bars, thinnest of 3 (4) spaces or every 4th
   wiki-sample: a31117013206375b (wide spaces between chars) schraeg!
   barcode:     t1234567t  n=N=1 w=W=3 c=12,14 (not const.)
 */
const char *code27= /* 4bars+3spaces, 12+12 chars */
//  0..11: 3 nbar + 1 wbar + 2 nspace + 1 wspace
"0.....--1....--.2...-..-3--.....4..-..-."                  
"5-....-.6.-....-7.-..-..8.--....9-..-...-...--..$..--..."
// 12..15: 1 nbar + 3 wbar + 3 nspace + 0 wspace
":-...-.-/-.-...-.-.-.-..+..-.-.-"                          
// 16..23: 3 nbar + 1 wbar + 1 nspace + 2 wspace
"a..--.-.b.-.-..-c...-.--d...---.t..--.-.n.-.-..-*...-.--e...---."
// EOS
"????????";

/* example: barcode -E -e cbr -b 123456 >a.eps */

char *decode_27(int *wb, int num_bars){ /* ToDo: char *dest, int len */
  int i, i1, i2, i3, i4, i5, b_idx[4], s_idx[3], b_w[4], s_w[3],
      max_wdiff, err=0;
  // double dw, err;  
  char *buf, char27[8]="......";
  char *result=NULL; /* malloc and store the result */

  int code_chars;
#if 0 // ToDo: verifications nb_max < wb_min etc.
  int nb_min=99999, nb_max=0, nb_sum=0, nb_num=0; // narrow bar
  int ns_min=99999, ns_max=0, ns_sum=0, ns_num=0; // narrow space
  int wb_min=99999, wb_max=0, wb_sum=0, wb_num=0; // wide bar
  int ws_min=99999, ws_max=0, ws_sum=0, ws_num=0; // wide space
#endif
  
  if ((num_bars)%4!=0) return 0; /* chars*4bars */
  code_chars = num_bars / 4;
//  dw=w*1.0/(9*(num_bars/3)); /* threshold = 1.5..2 */

  g_debug(fprintf(stderr," codabar chars= %d\n ", code_chars);)
  buf   =malloc(    code_chars); if (!buf)    return result;
  result=malloc(256+code_chars);
  i5=0; // index output string
  for (i=0; i< code_chars; i++) {
    b_w[0]=wb[i*8+0]; // 1st bar
    b_w[1]=wb[i*8+2]; // 2nd bar
    b_w[2]=wb[i*8+4]; // 3th bar
    b_w[3]=wb[i*8+6]; // 4th bar
    s_w[0]=wb[i*8+1]; // 1st space
    s_w[1]=wb[i*8+3]; // 2nd space
    s_w[2]=wb[i*8+5]; // 3th space
    sort(b_w,b_idx,4); /* idx[0] points to widest bar */
    sort(s_w,s_idx,3); /* idx[0] points to widest space */
    g_debug(for(i3=0;i3<7;i3++)fprintf(stderr,"%02d ",wb[8*i+i3]);)
    if (b_w[b_idx[0]]==b_w[b_idx[3]]) { err=__LINE__; break; } // min. 1 wide + narrow
    // search max. diff between sorted widths
    i2=b_w[b_idx[0]]-b_w[b_idx[1]]; i1=1; max_wdiff=i2; // diff widest - 2nd wides
    i2=b_w[b_idx[1]]-b_w[b_idx[2]]; if (i2>max_wdiff) { i1=2; max_wdiff=i2; }
    i2=b_w[b_idx[2]]-b_w[b_idx[3]]; if (i2>max_wdiff) { i1=3; max_wdiff=i2; }
    if (i1==2) { err=__LINE__; break; } // 2 wide + 2 narrow bars not allowed
    for (i3=0;i3<7;i3++) char27[i3]='.'; // reset char
    if (i1==1) { // 1 wide bar (1 or 2 wspaces)
      if (s_w[s_idx[0]]-s_w[s_idx[1]]
         >s_w[s_idx[1]]-s_w[s_idx[2]]) { // 1 wspace
        char27[2*b_idx[0]+0]='-';
        char27[2*s_idx[0]+1]='-';
      } else { // assume 2 wspaces
        if (s_w[s_idx[2]]==s_w[s_idx[1]]) { err=__LINE__; break; }
        char27[2*b_idx[0]+0]='-';
        char27[2*s_idx[0]+1]='-';
        char27[2*s_idx[1]+1]='-';
      }
    } else {   // assume 3 wbars + 0 wspaces
      char27[2*s_idx[0]+0]='-';
      char27[2*s_idx[1]+0]='-';
      char27[2*s_idx[2]+0]='-';
    }
    for(i4=24,i3=0;i3<24;i3++) {
      if (code27[8*i3+1]==char27[0]
       && code27[8*i3+2]==char27[1]
       && code27[8*i3+3]==char27[2]
       && code27[8*i3+4]==char27[3]
       && code27[8*i3+5]==char27[4]
       && code27[8*i3+6]==char27[5]
       && code27[8*i3+7]==char27[6]) {
         i4=i3; buf[i5++]=code27[8*i3]; break; }
    }
    g_debug(fprintf(stderr," %s c27= %c\n ", char27, ((i5)?buf[i5-1]:'?'));)
    if (i4==24) { err=__LINE__; break; }
  } // each char
  if (i>=code_chars) { // else: inconsistent char
    g_debug(fprintf(stderr," code27  base=%.3f chars=%2d\n ",0.0,code_chars);)
  } else {
    g_debug(fprintf(stderr," error %d at char %d, abort\n", err, i);)
    free(result); result=0;
  }
  buf[i5]=0;
  if (result) // ToDo: fix CRC (not defined?)
   sprintf(result,"<barcode type=\"codabar\" chars=\"%d\" code=\"%s\""
     " crc=\"%c\" error=\"%.3f\" />", i5,buf,'?',0.0);

  free(buf);
  return result; // free at parent!
}


/*
    decode barcode
    - check main characteristics (num bars, min+max width, etc.)
    - detect code type
    - the current algorithm measures the width of bars and spaces
    called by detect_barcode()
    ToDo: - like storing sequence of widths for 1D code
            store array of bits for 2D matrix code and decode later
 */
char *decode_barcode(struct box *bb){ /* ToDo: char *dest, int len */
  job_t *job=OCR_JOB; /* fixme */
  int i, num_bars, yy, w, ww, dx, xx, cs=job->cfg.cs, *wb;
  char *result=NULL; /* store the result */
  yy=(bb->y0+bb->y1)/2;
  w=ww=bb->x1-bb->x0+1;
  num_bars = num_cross(bb->x0,bb->x1,yy,yy,bb->p,job->cfg.cs);
  if(job->cfg.verbose)  
    fprintf(stderr,"\n# ... detect bars=%3d w=%4d",num_bars,ww);
  
  /* store width of bars and spaces to buffer wb */
  wb=(int *)malloc(2*num_bars*sizeof(int)); if(!wb) return NULL;
  xx=bb->x0;
  xx-=loop(bb->p,xx,yy, 8,cs,1,LE);
  xx+=loop(bb->p,xx,yy,ww,cs,0,RI); /* start with a bar! */
  for (i=0;i<2*num_bars;i++) {
    dx=loop(bb->p,xx,yy,w,cs,1^(i&1),RI);
    xx+=dx;
    w-=dx;
    wb[i]=dx;
  } wb[2*num_bars-1]=0;
  
  /* ToDo: what about probability? if not unique
   *      - add argument char *result which can be modified or not,
   *      - or add box2? (would reuse of this code more difficult)
   */
  /* test code128 characteristics, ToDo: look for correct start/stop 211 seq. */
  if ((num_bars-1)%3==0 && num_bars>=10 && ww>=11*(num_bars-1)/3+2){
    if (!result) result=decode_code128(wb,num_bars);
  }
  /* test UPC/EAN characteristics */
  if ((num_bars)%2==0 && num_bars>=8 && ww>=7*(num_bars-6)/2+11
  && ((num_bars-6)/2)%2==0){  /* should be balanced */
    if (!result) result=decode_UPC(wb,num_bars);
  }
  /* test UPC_addon by Michael van Rooyen, often on books */
  if (num_bars==7 || num_bars==16)
    if (!result) result=decode_UPC_addon(wb,num_bars);

  /* test code39 characteristics */
  if ((num_bars)%5==0 && num_bars>14){
    if (!result) result=decode_39(wb,num_bars);
  }
  /* test i2of5 chartacteristics */
  if ((num_bars)%5==4 && num_bars>3) {
    if (!result) result=decode_i25(wb,num_bars);
  }

  /* test codabar chartacteristics */
  if ((num_bars)%4==0 && num_bars>3) {
    if (!result) result=decode_27(wb,num_bars);
  }

  free(wb);
  return result;
}

// RS Reed Solomon Code
// Definition of Galois Field GF(2^m) (de: Zahlenraum, endl. Koerper)
//  1bit: m=1 dual GF2={0,1}
//    0+0=0 0+1=1 1+0=1 1+1=0 0*0=0*1=1*0=0 1*1=1 a^1=1?
//    a^0=1 a^1=1
//  8bit: m=8 byte GF256=    a=primitiv_element=2 a^255=1
//    exp[0]=1; expa[i+1]=expa[i]*a;
// i:   0 1 2 3  4  5  6   7  8  9  10  11  12  13 14 ... 254 255
// a^i: 1 2 4 8 16 32 64 128 29 58 116 232 205 135 19 ... 142   1
//  generated by shift-register
// representation of GF(256) using the given primitive polynomial
// GF256_QR_CODE_FIELD     = GF256(0x011D); // x^8 + x^4 + x^3 + x^2 + 1
// GF256_DATA_MATRIX_FIELD = GF256(0x012D); // x^8 + x^5 + x^3 + x^2 + 1
// based on LGPL code by Phil Karn, KA9Q 2004 + qrencode by Kentaro Fukuchi

typedef unsigned char uchar;
/**
 * Reed-Solomon codec control block
 */
struct _RS {
  int mm;              /* Bits per symbol, max=8 */
  int nn;              /* Symbols per block (= (1<<mm)-1) */
  uchar alpha_exp[256]; /* log lookup table x=alpha^i, max_mm=8 */
  uchar alpha_log[256]; /* Antilog lookup table i=loga(x), max_mm=8 */
  uchar genpoly[256];   /* Generator polynomial, nroots_man=2^8-1 */
  int nroots;     /* Number of generator roots = number of parity symbols */
  int fcr;        /* First consecutive root, index form */
  int prim;       /* Primitive element, index form */
  int iprim;      /* prim-th root of 1, index form */
  int pad;        /* Padding bytes in shortened block */
  int gfpoly;
};

static struct _RS rs;

  
static int GF256_mult(int a, int b) {  // a*b
  int i, r=0, t=b; // result + temp var
  int primitive = 0x011D;
  for (i=0; i<8; i++) {
    // <<= 1 is multiplication by a=2, ^= primitive_polynomial
    r <<= 1;  if (r & 0x100) r ^= primitive;
    t <<= 1;  if (t & 0x100) r ^= a;
  }
  return r;
}

static int GF256_invers_mult(int b) {  // 1/b,  (a/b)=a*(1/b)
  int i, r = b;
  for (i=1; i<7; i++) r = GF256_mult( GF256_mult(r,r), b);
  return r;
}
/* Initialize a Reed-Solomon codec
 * symsize = symbol size, bits (8 for GF256=GF(2^8))
 * gfpoly = Field generator polynomial coefficients (0x011D for QR-Code)
 * fcr = 1st root of RS code generator polynomial, index form (0..2^symsize-1)
 *       fcr = 0
 * prim = primitive element to generate polynomial roots (1..2^symsize-1)
 *        prim = 1
 * nroots = RS code generator polynomial degree (number of roots) (0..2^8-1)
          nroots = num_ecc_bytes
 * pad = padding bytes at front of shortened block (0..2^8-2-nroots)
 *        pad = 255 - num_ecc_bytes - num_data_bytes
 */
static inline int modnn(struct _RS *rs, int x){
  while (x >= rs->nn) {   // 255
         x -= rs->nn;     // 255
         x = (x >> rs->mm) + (x & rs->nn); // 8 , 255
  }
  return x;
}
static void init_rs(int symsize, int gfpoly, int fcr,
                    int prim, int nroots, int pad) {
  int i,j,x,root,iprim;
  rs.mm= symsize;
  rs.nn= (1<<symsize)-1;
  rs.pad= pad;
  rs.nroots= nroots;

  g_debug(fprintf(stderr,"\n# init_rs symsize= %d gfpoly=0x%04x necc= %4d\n# ",
     symsize, gfpoly, nroots);)
  /* Generate Galois field lookup tables using
   *  primitive field generator polynomial gfpoly */
  rs.alpha_log[0]= rs.nn; // nn=255, log(0) = -inf
  rs.alpha_exp[rs.nn]= 0; // alha^(-inf) = 0
  x=1;
  for (i=0; i<255; i++) {
    rs.alpha_log[x] = i;
    rs.alpha_exp[i] = x;
    x <<= 1; if (x >= 0x100) { x ^= gfpoly; }
    // g_debug(fprintf(stderr," %3d",x);)
  }
  if (x!=1) fprintf(stderr,"init_rs failed, bad primitive gfpoly x=%d\n# ",x);
  // for (i=0; i<256; i++)
  //   printf(" i a^i loga(i) %3d %3d %3d\n", i, alpha_exp[i], alpha_log[i]);
  /* Form RS code generator polynomial from its roots */
  /* Find prim-th root of 1, used in decoding, prim=1, rs.nn=255, iprim=1 */
  for(iprim=1; (iprim % prim) != 0; iprim += rs.nn);
  rs.iprim = iprim / prim;
  rs.genpoly[0]=1; // alpha0*x^nroot + ...
  for (i = 0, root=fcr*prim; i < nroots; i++, root += prim) {
    rs.genpoly[i+1] = 1;
    /* Multiply rs.genpoly[] by  alpha^(root + x) */
    for (j = i; j > 0; j--){
      if (rs.genpoly[j] != 0)
        rs.genpoly[j] = rs.genpoly[j-1] ^ rs.alpha_exp[
                                modnn(&rs,rs.alpha_log[rs.genpoly[j]] + root)];
      else
        rs.genpoly[j] = rs.genpoly[j-1];
    }
    /* rs.genpoly[0] can never be zero */   
    rs.genpoly[0] = rs.alpha_exp[modnn(&rs,rs.alpha_log[rs.genpoly[0]] + root)];
  }
#if DO_DEBUG
  if (OCR_JOB->cfg.verbose&1) {
    int i;
    for (i=0; i <= nroots; i++)
      fprintf(stderr,"%3d ", i);
    fprintf(stderr,"\n# ");
    for (i=0; i <= nroots; i++)
      fprintf(stderr,"%3d ", rs.genpoly[i]);  // coefficient * x^i
    fprintf(stderr,"\n# ");
   }
#endif
  /* convert rs.genpoly[] to index form for quicker encoding */
  for (i = 0; i <= nroots; i++)
    rs.genpoly[i] = rs.alpha_log[rs.genpoly[i]];
#if DO_DEBUG
  if (OCR_JOB->cfg.verbose&1) {
    int i;
    for (i=0; i <= nroots; i++)
      fprintf(stderr,"%3d ", rs.genpoly[i]); // exponent i of alpha^i
    fprintf(stderr,"\n# ");
   }
#endif
}
void encode_rs_char(struct _RS *rs, const uchar *data, uchar *parity) {
  int i, j; uchar feedback;
  memset(parity,0,rs->nroots*sizeof(uchar));

  for(i=0;i<rs->nn - rs->nroots - rs->pad;i++){
    feedback = rs->alpha_log[data[i] ^ parity[0]];
    if(feedback != rs->nn){      /* feedback term is non-zero */
#ifdef UNNORMALIZED
      // unnecessary when genpoly[nroots] = 1, as constructed by init_rs()
      feedback = modnn(rs, rs->nn - rs->genpoly[rs->nroots] + feedback);
#endif
      for(j=1;j<rs->nroots;j++)
        parity[j] ^= rs->alpha_exp[modnn(rs, feedback + rs->genpoly[rs->nroots-j])];
    }
    /* Shift */
    memmove(&parity[0],&parity[1],sizeof(uchar)*(rs->nroots-1));
    if(feedback != rs->nn)
      parity[rs->nroots-1] = rs->alpha_exp[modnn(rs, feedback + rs->genpoly[0])];
    else
      parity[rs->nroots-1] = 0;
  }
#if DO_DEBUG
  if (OCR_JOB->cfg.verbose&1) {
    int i;
    fprintf(stderr,"\n# ecc\n# ");
    for (i=0; i <= rs->nroots; i++)
      fprintf(stderr,"%3d ", parity[i]); // exponent i of alpha^i
    fprintf(stderr,"\n# ");
    for (i=0; i <= rs->nroots; i++)
      fprintf(stderr," %02x ", parity[i]); // exponent i of alpha^i
    fprintf(stderr,"\n# ");
   }
#endif
}  

/*
 * taking the list of boxes and search for groups of bars (1D-barcodes)
 */
int detect_barcode(job_t *job)
{
  int j=0, j2=0, bx0, by0, bx1, by1, bdx, bdy, bbx, bby, rm,
     nbars, x0, y0, dx, dy, cs, x, y, yl0, yl1, yr0, yr1,
     regx, regy; // regions for 2D barcode
  struct box *box2, *box3;

  if(job->cfg.verbose) 
    fprintf(stderr,"# barcode.c detect_barcode ");
  x0=y0=0; rm=0; dx=job->src.p.x;  dy=job->src.p.y; cs=job->cfg.cs;
  bdx=0; bdy=0;
  for_each_data(&(job->res.boxlist)) {
    box2 = (struct box *)list_get_current(&(job->res.boxlist));
    /* detect width (bdx) and height (bdy) of possible bar */
    /* ToDo: better check for a line */
    bdx=box2->x1-box2->x0+1  /* substract correction for skewed bars */
       -loop(box2->p,box2->x1,(box2->y0+box2->y1)/2,box2->x1-box2->x0,cs,0,LE)
       -loop(box2->p,box2->x0,(box2->y0+box2->y1)/2,box2->x1-box2->x0,cs,0,RI);
    bdy=box2->y1-box2->y0+1;
    if (box2->c == PICTURE || box2->c == UNKNOWN)
    if (box2->y0 >= y0 && box2->y1 <= y0 + dy  /* within frame? */
     && box2->x0 >= x0 && box2->x1 <= x0 + dx
     && box2->y1 - box2->y0 > 19               /* min. length */
     && box2->y1 - box2->y0 >  8 * bdx
    ) { /* a bar? */
       j=1; /* number of bars */
       bx0=box2->x0; bx1=box2->x1;  /* initial values for barcode frame */
       by0=box2->y0; by1=box2->y1;
       bbx=bx1-bx0+2; /* width of bar */
       /* this is for scans which are not exactly horizontal */
       yl0=yr0=by0; /* left and right upper bound */
       yl1=yr1=by1; /* left and right lower bound */
       /* --- iteratively take into account next nearest bar ---
        * this is important, because bar-boxes are not in right order */
       for (j2=1;j2;) {
         j2=0;
         /* expand a frame around the potential barcode (bx0,by0,bx1,by1) */
         for_each_data(&(job->res.boxlist)) {
           box3 = (struct box *)list_get_current(&(job->res.boxlist));
           /* bdy=box3->y1-box3->y0+1; */
           if (box2!=box3)
           if (box3->c == PICTURE || box3->c == UNKNOWN)
           if (box3->y0 >= y0 && box3->y1 <= y0 + dy  /* within image */
            && box3->x0 >= x0 && box3->x1 <= x0 + dx
            && box3->y1 - box3->y0 > 19               /* min. length */
            && box3->y1 - box3->y0 >  4 * (bdx) /* height > 4*width2 */
            && box3->x1 - box3->x0 <  4 * (bdy) /* width  < height/4 = bar */
            && ((  abs(box3->y0-by0)<bdy/16+4   /* within bar-box ? */
                && abs(box3->y1-by1)<bdy/2   )  /* lower ends of UPC could be longer */
               ||( abs(box3->y0-yl0)<bdy/16+4   /* left side of frame */
                && abs(box3->y1-yl1)<bdy/2
                && box3->x0 <= bx0           )
               ||( abs(box3->y0-yr0)<bdy/16+4   /* right side of frame */
                && abs(box3->y1-yr1)<bdy/2
                && box3->x0 >= bx1           ) )
            && box3->x0 > bx0 - 12*bbx /* startspace=5...10 */
            && box3->x1 < bx1 + 12*bbx
            && box3->x0 > bx0 - bdy/2  /* dont glue two barcodes together */
            && box3->x1 < bx1 + bdy/2                   /* ex: ean13a.jpg */
            /* dont check bars which already within the frame twice ? */
            && (  box3->x1 > bx1 || box3->x0 < bx0 )
           ) { /* a bar? -> extend barcode frame only in x direction */
               /* take minimum of y to have valid barcode for all y */
              if (box3->x0<bx0) { bx0=box3->x0; yl0=box3->y0; yl1=box3->y1; }
              if (box3->x1>bx1) { bx1=box3->x1; yr0=box3->y0; yr1=box3->y1; }
              if (4*(box3->y1-box3->y0)>3*(by1-by0)) { /* carefull reduce */
                if (box3->y0>by0) by0=box3->y0; /* ToDo: fix for non-horizontal */
                if (box3->y1<by1) by1=box3->y1;
              }
              j++;  /* found a near bar and count to num bars */
              j2=1; /* continue searching (endless loop?) */
           }
         } end_for_each(&(job->res.boxlist));
       }
       /* j is the num of bars found above, some inner bars are not counted */
       /* ToDo: better iterative add next nearest bars from sorted list near bars? */
       if (j>5) {
         char *code=0;
         box2->c=PICTURE; /* BARCODE */
         box2->x0=bx0;       box2->y0=by0;
         box2->x1=bx1;       box2->y1=by1;
         /* ToDo: add pointer to decoded text */

         y=(box2->y0+box2->y1)/2;
         if (job->cfg.verbose){
           int nbars;
           nbars=num_cross(box2->x0,box2->x1,y,y,box2->p,job->cfg.cs);
           fprintf(stderr,"\n# barcode at %3d %3d size %3d %3d nbars %d (%d)",
             bx0,by0,bx1-bx0+1,by1-by0+1,nbars,j);
           if (j!=nbars)
             fprintf(stderr,"\n# ... trouble: num_found_bars != num_cross");
           /* this is because some far bars are detected before near bars */
         }
         /* transport the info to the gocr-output (development) */
         /* ToDo: decode and print/store barcode bars=j */
         code=decode_barcode(box2); /* ToDo: char *dest, int len */
         if (!code) { /* failed */
           code=(char *)malloc(128);
           /* ToDo: analyze and output num_bars, width of bars etc. */
           if(code) strncpy(code,"<barcode type=\"unknown\" />",128);
         }
         if (job->cfg.verbose)  
           fprintf(stderr,"\n# ... decoded as: %s", code);
         setas(box2,code,99); /* ToDo: set a better weight */
         free(code);

         /* remove inner boxes, only if sure!? (ToDo: use cfg.certainty) */
         for_each_data(&(job->res.boxlist)) {
           box3 = (struct box *)list_get_current(&(job->res.boxlist));
           /* bdy=box3->y1-box3->y0+1; */
           if (box2!=box3)
           if (box3->c == PICTURE || box3->c == UNKNOWN)
           if (    abs(box3->y0-by0)<bdy/16+4   /* within bar-box ? */
                && abs(box3->y1-by1)<bdy/2      /* lower ends of UPC could be longer */
                && box3->x1 <= bx1
                && box3->x0 >= bx0
           ) {
              rm++; /* count removed boxes */
              list_del(&(job->res.boxlist),box3);
              free_box(box3);
           }
         } end_for_each(&(job->res.boxlist));
         if (job->cfg.verbose)  
           fprintf(stderr,"\n# ... removed boxes: %d", rm);
         rm=0;
       }
   }
  } end_for_each(&(job->res.boxlist));

  /* recalculate averages without bars */
  job->res.numC=job->res.sumX=job->res.sumY=j2=0;
  for_each_data(&(job->res.boxlist)) {
    j2++;
    box3 = (struct box *)list_get_current(&(job->res.boxlist));
    if (box3->c==PICTURE) continue;
    job->res.numC++; /* count remaining boxes */
    job->res.sumX+=box3->x1-box3->x0+1;
    job->res.sumY+=box3->y1-box3->y0+1;
  } end_for_each(&(job->res.boxlist));
  if(job->cfg.verbose)  
    fprintf(stderr,"\n# ... boxes %d nC %d\n",
            j2, job->res.numC);
            

  /* ---------------------------------------------------------------
   * ToDo: detect DataMatrix = iec16022  (ecc200, 24 sizes)
   * search square of 2 lines and 2 dottet lines (first no rotation)
   * output characteristics pixel size, bytes, code type, etc. 
   * symbolsize: 10^2...26^2,   32^2 ... 104^2, 120^2 ... 144^2
   * dataregion:  8^2...24^2, (4,16)*(14...24)^2, 36*(18,20,22)^2 
   * codewords:     3...44,      62...816,       1050...1558
   * errorwords:    5...28,      36...336,        408...620
   *  fill byte = 129, ASCIIdata = ASCII + 1
   *
   * ToDo: !!! no Reed Solomon Error Correction at the moment !!!
   * ToDo: !!! raw data output, no ASCII decoding !!!
   *   see http://grandzebu.net/ ... datamatrix.htm
   * sample: iec16022 -f PNG 123456 > datamatrix_123456.png
   */

  if(job->cfg.verbose)  
    fprintf(stderr,"# barcode.c detect_barcode search datamatrix ");
  x0=y0=0; rm=0; dx=job->src.p.x;  dy=job->src.p.y; cs=job->cfg.cs;
  for_each_data(&(job->res.boxlist)) {
    box2 = (struct box *)list_get_current(&(job->res.boxlist));
    /* detect width (bdx) and height (bdy) of possible matrix */
    /* ToDo: better check for a line */
    bdx=box2->x1-box2->x0+1;  /* ToDo: correction for skewed matrix */
    bdy=box2->y1-box2->y0+1;
    if (bdx<10 || bdy<10) continue; // 2010-09-28 reduce output + computation
//  g_debug(fprintf(stderr,"\n# datamatrix box size %4d %4d", bdx, bdy);)
    by0=0; bx1=0; /* x of hor.  max_num_crosses, max_num_crosses */
    bx0=0; by1=0; /* y of vert. max_num_crosses, max_num_crosses */
    x=num_cross(box2->x0,box2->x1,box2->y1,box2->y1,box2->p,job->cfg.cs);
    y=num_cross(box2->x0,box2->x0,box2->y0,box2->y1,box2->p,job->cfg.cs);
    for (j = box2->y0; j <= box2->y1; j++) {
      nbars=num_cross(box2->x0,box2->x1,j,j,box2->p,job->cfg.cs);
      for (j2=0; j2<nbars; j2++) {
        int t = box2->x0+j2*bdx/(nbars);
//        fprintf(stderr,"\n# %3d %3d %d %d",j,j2,((getpixel(box2->p,t+1*bdx/(4*nbars),j)<cs)?1:0),
//                                   ((getpixel(box2->p,t+3*bdx/(4*nbars),j)<cs)?1:0));
        if  (((getpixel(box2->p,t+1*bdx/(4*nbars),j)<cs)?1:0)!=1) break;
        if  (((getpixel(box2->p,t+3*bdx/(4*nbars),j)<cs)?1:0)!=0) break;
      } if (j2!=nbars) continue;
      if (nbars> bx1) { bx1=nbars; by0=j; }  // search most upper
    }
    for (j = box2->x0; j <= box2->x1; j++) {
      nbars=num_cross(j,j,box2->y0,box2->y1,box2->p,job->cfg.cs);
      for (j2=0; j2<nbars; j2++) {
        int t = box2->y0+j2*bdy/(nbars);
//        fprintf(stderr,"\n# %3d %3d %d %d",j,j2,((getpixel(box2->p,j,t+1*bdy/(4*nbars))<cs)?1:0),
//                                   ((getpixel(box2->p,j,t+3*bdy/(4*nbars))<cs)?1:0));
        if  (((getpixel(box2->p,j,t+1*bdy/(4*nbars))<cs)?1:0)!=0) break;
        if  (((getpixel(box2->p,j,t+3*bdy/(4*nbars))<cs)?1:0)!=1) break;
      } if (j2!=nbars) continue;
      if (nbars>=by1) { by1=nbars; bx0=j; }  // search most right
    }
    bbx=(bx1)?bdx/(2*bx1):1; /* width  of base square */
    bby=(by1)?bdy/(2*by1):1; /* height of base square*/
//  ToDo: check upper and left finder pattern
    if (box2->c != PICTURE && box2->c != UNKNOWN) continue;
    if (x!=1 || y!=1) continue;
    // 30 possible ECC 200 datamatrix size versions
    if (( ( ( (bx1>=5  && bx1<=13)
           || (bx1>=16 && bx1<=26 && bx1%2==0)
           || (bx1>=32 && bx1<=52 && bx1%4==0)
           || (bx1>=60 && bx1<=72 && bx1%6==0))
          && bx1==by1)
         || (by1==4 && bx1==9)
         || (by1==6 && bx1==13)
         || (by1==8 && bx1==36)
         || (by1==4 && bx1==16)
         || (by1==6 && bx1==18)
         || (by1==8 && bx1==24)) 
        && by0 <  box2->y0 + bby  // alternating b/w border 
        && bx0 >  box2->x1 - bbx  // alternating b/w border 
        ) { /* a bar? */
       g_debug(fprintf(stderr,"\n# datamatrix box size %4d %4d ncross %d %d %d %d bb %d %d", bdx, bdy, x, y, bx1, by1, bbx, bby);)
       regx=1; regy=1; // regx*regy regions (2x2,4x4,6x6,1x2)
       if (bx1>=16) { regx=2; } // 13 < x <= 16
       if (bx1>=32) { regx=4; } // 26 < x <= 32
       if (bx1>=60) { regx=6; } // 52 < x <= 60
       if (by1>=16) { regy=2; }
       if (by1>=32) { regy=4; }
       if (by1>=60) { regy=6; }
       g_debug(fprintf(stderr," mark%03d %dx%d reg %d %d bb %d %d bytes %d",
         __LINE__,2*bx1,2*by1,regx,regy,bbx,bby,(bx1-regx)*(by1-regy)/2);)
       /* j is the num of bars found above, some inner bars are not counted */
       /* ToDo: better iterative add next nearest bars from sorted list near bars? */
       {
         int row, col;
         char *dm_bitmap=NULL;

         // store pattern without finder pattern into dm_bitmap
         dm_bitmap=(char *)malloc(4*(bx1-regx)*(by1-regy));
         if (!dm_bitmap) { fprintf(stderr," ERROR: mallocDM1 failed\n"); continue; }
         for (row=0;row<2*(by1-regy);row++) {
           for (col=0;col<2*(bx1-regx);col++) {
              x = box2->x0+bbx*(col+1+2*((col+2)/(2*bx1/regx)))+bbx/2;
              y = box2->y0+bby*(row+1+2*((row+2)/(2*by1/regy)))+bby/2;
              dm_bitmap[row*2*(bx1-regx)+col]=
                ((getpixel(box2->p,x,y)<cs)?1:0);
           }
         }

         /* transport the info to the gocr-output (development) */
         if (job->cfg.verbose) {
           fprintf(stderr,"\n#      ");
           for (col=0;col<2*bx1;col++)
              if (col<=8) fprintf(stderr," %1d",col); else
              if (col<=98 && col%2==0) fprintf(stderr," %3d",col); else
              if (col%4==0) fprintf(stderr," %7d",col);
           for (row=0;row<2*by1;row++) {
             fprintf(stderr,"\n# %3d: ", row);
             for (col=0;col<2*bx1;col++)
               fprintf(stderr," %c",
                ((getpixel(box2->p,box2->x0+bbx*col+bbx/2,
                                   box2->y0+bby*row+bby/2)<cs)?
                      ((   col%(2*bx1/regx)==0
                        || col%(2*bx1/regx)==2*bx1/regx-1
                        || row%(2*by1/regy)==0
                        || row%(2*by1/regy)==2*by1/regy-1
                        )?'x':'o'):' ')); // 'o' = data1, 'x' = finder1
           }
           // show pure data
           fprintf(stderr,"\n# now without finder pattern\n#      ");
           for (col=0;col<2*(bx1-regx);col++)
              if (col<=8) fprintf(stderr," %1d",col); else
              if (col<=98 && col%2==0) fprintf(stderr," %3d",col); else
              if (col%4==0) fprintf(stderr," %7d",col);
           for (row=0;row<2*(by1-regy);row++) {
             fprintf(stderr,"\n# %3d: ", row);
             for (col=0;col<2*(bx1-regx);col++) {
                fprintf(stderr," %c",
                (dm_bitmap[row*2*(bx1-regx)+col])?'o':' ');
             }
           }
         }

         char *code=0; int cpos=0;
         box2->c=PICTURE; /* BARCODE */
         code=NULL;
         code=(char *)malloc(6*4*bx1*by1/8+128); /* maxlen: &#%3d; = 6 */
         if (!code) { fprintf(stderr," ERROR: mallocDM2 failed\n"); continue; }
         code[0]=0;
         strncpy(code,"<barcode type=\"datamatrix ecc200\" rawcode=\"\" />",128);
         cpos=43; // insert chars at position 40
         /* pixel 32x32 = (2*2)*(2*7+2)^2 = 4*196/8bit - 12B (Reed Solomon),
          *   = 98-12 B = 86B */

         // code=decode_datamatrix(box2); /* ToDo: char *dest, int len */
         // for 8x8 (10x10) first CW is at 1: -2,+2, 2: +0,+0, 3: +2,-2,
         //     4: +5,-1, 5: +3,+1, 6: +1,+3, 7: -1,+5, 8: +4,+4
         //     = diagonal zick/zack
         // --> x=c    7 6    (start: r=4, c=0) up/right=(r-=2, c+=2)
         // |          5 4 3                    down/left=(r+=2, c-=2)
         // v y=r      2 1 0                    turn=(r+=3, c+=1)
         // sample ascii=\x30='0' \x40='@' \x20=' '
         /* ToDo: decode and print/store barcode bars=j */
         x = +0; // col += 2
         y = +4; // row -= 2
         int nc=2*(bx1-regx), nr=2*(by1-regy),
             // dm_mode=0,  // ECC200-mode: 0=ASCII+digitpair, 230=C40
             dm_d=+1; // direction right/down
         for (j=0;j<(bx1-regx)*(by1-regy)/2;j++) { // each byte
           int dm_byte=0;
           const int *pp; /* pointer to (const int) */ 
           const int  // bitmatrix +  4 special cases for lower left corner
             pn[8*2]={ 0, 0, -1, 0, -2, 0,  0,-1, -1,-1, -2,-1, -1,-2, -2,-2},
             pa[8*2]={-1,+3, -1,+2, -1,+1, -1,+0, -2,+0, +2,-1, +1,-1, +0,-1},
             pb[8*2]={-1,+3, -1,+2, -2,+2, -3,+2, -4,+2, +0,+1, +0,+0, +0,-1},
             pc[8*2]={-1,+5, -1,+4, -1,+3, -1,+2, -2,+2, +0,+1, +0,+0, +0,-1},
             pd[8*2]={-3,-3, -4,-3, -5,-3, -3,-4, -4,-4, -5,-4, -3,-5, -2,-5};
           pp=pn;
           if (x==0 && y==nr)                { pp=pa; }
           if (x==0 && y==nr-2 && (nc%4))    { pp=pb; }
           if (x==0 && y==nr-2 && (nc%8)==4) { pp=pc; }
           if (x==2 && y==nr+4 && (nc%8)==0) { pp=pd; }
           for (j2=0;j2<8;j2++) { // each bit
             col= (x + pp[2*j2+0]);
             row= (y + pp[2*j2+1]);
             if (pp!=pn) { col=(col+nc)%nc; row=(row+nr)%nr; }
             if (row<0) { row+=nr; col+=4-((nr+4)%8); }
             if (col<0) { col+=nc; row+=4-((nc+4)%8); }
             col=(col+nc)%nc; row=(row+nr)%nr; 
             dm_byte += (dm_bitmap[row*nc+col])<<j2;
             // fprintf(stderr," @ %3d %3d",col,row);
           }
           if ((dm_d>0 && x>=0 && y<nr)
             ||(dm_d<0 && y>=0 && x<nc)) {
             fprintf(stderr,"\n# @ %3d %3d : %02x %3d d %2d pos %3d decode= ",
                     x, y, dm_byte, dm_byte, dm_d, cpos);
             if (dm_byte>=' '+1 && dm_byte<=128)
               { code[cpos++]=(char)(dm_byte-1);
                 fprintf(stderr,"%c", dm_byte-1); }
             else if (dm_byte>=130 && dm_byte<=229) // 130 + 00..99
               { code[cpos++]=(char)((dm_byte-130)/10)+'0';
                 code[cpos++]=(char)((dm_byte-130)%10)+'0';
                 fprintf(stderr,"%02d", dm_byte-130); }
             else {
               int nout=0;
               if (dm_byte==129) fprintf(stderr,"[Padding]");
               if (dm_byte==230) fprintf(stderr,"[C40]"); // 1.5 uppercase/B
               if (dm_byte==231) fprintf(stderr,"[Base256]"); // 1 byte/B
               if (dm_byte==232) fprintf(stderr,"[FNC1]");
               if (dm_byte==235) fprintf(stderr,"[ShiftASC]"); // next -127
               if (dm_byte==238) fprintf(stderr,"[AnsiX12]");
               if (dm_byte==239) fprintf(stderr,"[Text]"); // 1.5 lowercase/B
               if (dm_byte==240) fprintf(stderr,"[EDIFACT]"); // 1.33char/byte
               if (dm_byte==254) fprintf(stderr,"[EOTorRET2Text]");
               // ToDo: store bytes + interprete it later for output
               {
                 nout = sprintf(code+cpos,"&#%d;",dm_byte);
                 if (nout>0) cpos+=nout;
               }
             }
           } else j--; // missing reed-solomon chars from skipping!?
           if (cpos > 6*4*bx1*by1/8+128 - 10) break; // avoid buffer overflow

           x += dm_d * 2;
           y -= dm_d * 2;
           if (dm_d>0 && (y<0 || x>=nc)) { y++; x+=3; dm_d*=-1; } else
           if (dm_d<0 && (x<0 || y>=nr)) { x++; y+=3; dm_d*=-1; }
           if (dm_d>0 && x>=nc && y>=nr) break;
         }

         if (job->cfg.verbose){
           fprintf(stderr,"\n# datamatrix at %3d %3d size %3d %3d npix %d*%d unit %d*%d",
             box2->x0,box2->y0,bdx,bdy,2*bx1,2*by1,bbx,bby);
         }
         if (code && cpos<2*4*bx1*by1/8+128-6)
           strncpy(code+cpos,"\" />",6); // terminate xml string
         code[2*4*bx1*by1/8+127]=0;
         if (!code) { /* failed */
           code=(char *)malloc(128);
           /* ToDo: analyze and output num_bars, width of bars etc. */
           if (code) strncpy(code,"<barcode type=\"unknown datamatrix\" />",128);
         }
         if (job->cfg.verbose)
           fprintf(stderr,"\n# ... decoded as: %s", code);
         setas(box2,code,99); /* ToDo: set a better weight */
         free(code);

         /* remove inner boxes, only if sure!? (ToDo: use cfg.certainty) */
         for_each_data(&(job->res.boxlist)) {
           box3 = (struct box *)list_get_current(&(job->res.boxlist));
           /* bdy=box3->y1-box3->y0+1; */
           if (box2!=box3)
           if (box3->c == PICTURE || box3->c == UNKNOWN)
           if (    box3->y0 >= box2->y0   /* within datamatrix ? */
                && box3->y1 <= box2->y1
                && box3->x1 <= box2->x1
                && box3->x0 >= box2->x0
           ) {
              rm++; /* count removed boxes */
              list_del(&(job->res.boxlist),box3);
              free_box(box3);
           }
         } end_for_each(&(job->res.boxlist));
         if (job->cfg.verbose)  
           fprintf(stderr,"\n# ... removed boxes: %d", rm);
         rm=0;
         free(dm_bitmap);
       }
   }
  } end_for_each(&(job->res.boxlist));

/* ---------------------------------------------------------------
 * ToDo: QR-Code (Quick-Response)
 *   Version 1..40: size= ((17+version*4) modules)^2 = 21,25,...,177 ^2
 *     Data-Bits = size^2-3*64-2*version-2-formatbits
 *     Data-Bits for ECC-Level=L: 152 ... 23648 (2953B)
 *  (21,21): start(lower right corner=20,20)
 *    - go up (width=2) +(-1,0) +(+1,-1) until upper border ??
 *    - than go down (width=2) until lower border, etc. ??
 *    - bits masked (8versions)
 *    ...
 *  two weeks of work to find out all the mysteries of QR-Code 2010-10-JS
 *  (no access to the iso papers, which cost money)
             bit0
             v
     @@@@@@@.fxxxx.@@@@@@@  fff= format-bits (2*14bit)
     @.....@.fxxxx.@.....@  xxx= data-bits starting right bottom, going up
     @.@@@.@.fxxxx.@.@@@.@  @@.= finder pattern + timing pattern
     @.@@@.@.fxxxx.@.@@@.@
     @.@@@.@.fxxxx.@.@@@.@
     @.....@.fxxxx.@.....@
     @@@@@@@.@.@.@.@@@@@@@  
     ........fxxxx........
     ffffff@ffxxxxffffffff<-bit0
     xxxxxx.xxxxxxxxxxxxxx
     xxxxxx@xxxxxxxxxxxxxx
     xxxxxx.xxxxxxxxxxxxxx
     xxxxxx@xxxxxxxxxxxxxx
     ........@xxxxxxxxxxxx
     @@@@@@@.fxxxxxxxxxxxx
     @.....@.fxxxxxxxxxxxx
     @.@@@.@.fxxxxxxxxxxxx
     @.@@@.@.fxxxxxxxxxxxx   
     @.@@@.@.fxxxxxxxxxxxx
     @.....@.fxxxxxxxxxxxx
     @@@@@@@.fxxxxxxxxxxxx
             ^-bit14
 */

{ // qrcode 2010-10-13
  // taken from qrencode-3.0.3/qrspec.c RS blocks
  // ToDo: rawbytes and bits can be computed, but what about ecc0..3 ???
  //  rawbytes mod (b1+b2) == b2
  //  ecc mod (b1+b2) == 0
  static int qrConst[40][6+8]= {
  // raw_bytes+bitrest, ecc_bytes, byte_interleaving
  //           L    M     Q     H     L       M       Q       H
  //  rawB  R  ecc0 ecc1  ecc2  ecc3  b1  b2  b1  b2  b1  b2  b1  b2 
    {   26, 0,   7,   10,   13,   17,  1,  0,  1,  0,  1,  0,  1,  0}, // 1
    {   44, 7,  10,   16,   22,   28,  1,  0,  1,  0,  1,  0,  1,  0},
    {   70, 7,  15,   26,   36,   44,  1,  0,  1,  0,  2,  0,  2,  0},
    {  100, 7,  20,   36,   52,   64,  1,  0,  2,  0,  2,  0,  4,  0},
    {  134, 7,  26,   48,   72,   88,  1,  0,  2,  0,  2,  2,  2,  2}, // 5
    {  172, 7,  36,   64,   96,  112,  2,  0,  4,  0,  4,  0,  4,  0},
    {  196, 0,  40,   72,  108,  130,  2,  0,  4,  0,  2,  4,  4,  1},
    {  242, 0,  48,   88,  132,  156,  2,  0,  2,  2,  4,  2,  4,  2},
    {  292, 0,  60,  110,  160,  192,  2,  0,  3,  2,  4,  4,  4,  4},
    {  346, 0,  72,  130,  192,  224,  2,  2,  4,  1,  6,  2,  6,  2}, //10
    {  404, 0,  80,  150,  224,  264,  4,  0,  1,  4,  4,  4,  3,  8},
    {  466, 0,  96,  176,  260,  308,  2,  2,  6,  2,  4,  6,  7,  4},
    {  532, 0, 104,  198,  288,  352,  4,  0,  8,  1,  8,  4, 12,  4},
    {  581, 3, 120,  216,  320,  384,  3,  1,  4,  5, 11,  5, 11,  5},
    {  655, 3, 132,  240,  360,  432,  5,  1,  5,  5,  5,  7, 11,  7}, //15
    {  733, 3, 144,  280,  408,  480,  5,  1,  7,  3, 15,  2,  3, 13},
    {  815, 3, 168,  308,  448,  532,  1,  5, 10,  1,  1, 15,  2, 17},
    {  901, 3, 180,  338,  504,  588,  5,  1,  9,  4, 17,  1,  2, 19},
    {  991, 3, 196,  364,  546,  650,  3,  4,  3, 11, 17,  4,  9, 16},
    { 1085, 3, 224,  416,  600,  700,  3,  5,  3, 13, 15,  5, 15, 10}, //20
    { 1156, 4, 224,  442,  644,  750,  4,  4, 17,  0, 17,  6, 19,  6},
    { 1258, 4, 252,  476,  690,  816,  2,  7, 17,  0,  7, 16, 34,  0},
    { 1364, 4, 270,  504,  750,  900,  4,  5,  4, 14, 11, 14, 16, 14},
    { 1474, 4, 300,  560,  810,  960,  6,  4,  6, 14, 11, 16, 30,  2},
    { 1588, 4, 312,  588,  870, 1050,  8,  4,  8, 13,  7, 22, 22, 13}, //25
    { 1706, 4, 336,  644,  952, 1110, 10,  2, 19,  4, 28,  6, 33,  4},
    { 1828, 4, 360,  700, 1020, 1200,  8,  4, 22,  3,  8, 26, 12, 28},
    { 1921, 3, 390,  728, 1050, 1260,  3, 10,  3, 23,  4, 31, 11, 31},
    { 2051, 3, 420,  784, 1140, 1350,  7,  7, 21,  7,  1, 37, 19, 26},
    { 2185, 3, 450,  812, 1200, 1440,  5, 10, 19, 10, 15, 25, 23, 25}, //30
    { 2323, 3, 480,  868, 1290, 1530, 13,  3,  2, 29, 42,  1, 23, 28},
    { 2465, 3, 510,  924, 1350, 1620, 17,  0, 10, 23, 10, 35, 19, 35},
    { 2611, 3, 540,  980, 1440, 1710, 17,  1, 14, 21, 29, 19, 11, 46},
    { 2761, 3, 570, 1036, 1530, 1800, 13,  6, 14, 23, 44,  7, 59,  1},
    { 2876, 0, 570, 1064, 1590, 1890, 12,  7, 12, 26, 39, 14, 22, 41}, //35
    { 3034, 0, 600, 1120, 1680, 1980,  6, 14,  6, 34, 46, 10,  2, 64},
    { 3196, 0, 630, 1204, 1770, 2100, 17,  4, 29, 14, 49, 10, 24, 46},
    { 3362, 0, 660, 1260, 1860, 2220,  4, 18, 13, 32, 48, 14, 42, 32},
    { 3532, 0, 720, 1316, 1950, 2310, 20,  4, 40,  7, 43, 22, 10, 67},
    { 3706, 0, 750, 1372, 2040, 2430, 19,  6, 18, 31, 34, 34, 20, 61}}; //40
  //  rawbytes/blocks = 3706 / (19+6) = 148 Bytes per Block (30 ecc bytes)
  //  rawbytes/blocks = 3706 / (20+61) = 45 Bytes per Block (30 ecc bytes)
  // 4 bits (mode) + 10,9,8,8 | 12,11,16,10 | 14,13,16,12 bits (size_of_len)
  //                           012 AB  byte     kanji
  static int head_bits09[16]={0,14,13,0,12,0,0,0,12,0,0,0,0,0,0,0};
  static int head_bits26[16]={0,16,15,0,20,0,0,0,14,0,0,0,0,0,0,0};
  static int head_bits40[16]={0,18,17,0,20,0,0,0,16,0,0,0,0,0,0,0};
  static int word_bits[16]=  {0,10,11,0, 8,0,0,0,13,0,0,0,0,0,0,0};
  static int word_nchr[16]=  {0, 3, 2,0, 1,0,0,0, 2,0,0,0,0,0,0,0};
  int *head_bits=NULL;
  int x02,y02,dx2,dy2, x03,y03,dx3,dy3,
      interleave=1, // = qrConst[qr_version-1][6+2*qr_ecclevel+0];
      num_marker=0, /* number of detected big marker squares */
      qrcode=0;     /* 1=detected, -1=detected_but_invalid_code */
  int qr_marker[3][4]; // x,y,dx,dy
  unsigned char *qrbytes=NULL, *qrtext=NULL; // for real data
  char *bits=NULL, *code=NULL;
  int fbits=0, // 15 formatbits (put in a 16..32bit word)
      bbits, wbits; // 8bits_per_byte, 11bits_per_word
  int i, j, num_bars, block_nbits=0, nbits=0, nwbits, ix, iy,
     nchars=0,                  // number chars encoded per block
     dchars=0, block_dchars=0,  // number of decoded chars
     qr_mode=0, qr_mask=0, qr_version=0, qr_ecclevel=0;
  int an2, ad1, ad2, // allignment parts, rest distance, main distance
    num_rawbits;

  if(job->cfg.verbose)  
    fprintf(stderr,"#\n# barcode.c detect_barcode search qrcode ");
#if 1
  for (j=0;j<4;j++) // LMQH:  ecc % (b1+b2) == 0
  for (i=0;i<40;i++)
    if (qrConst[i][2+j]%(qrConst[i][6+2*j+0]+qrConst[i][6+2*j+1])!=0)
      fprintf(stderr,"ERROR qrcode L%04d i=%d j=%d\n", __LINE__,i,j);
  for (j=0;j<4;j++) // LMQH:  rawbytes % (b1+b2) == b2
  for (i=0;i<40;i++)
    if (qrConst[i][0]%(qrConst[i][6+2*j+0]+qrConst[i][6+2*j+1])
                                         !=qrConst[i][6+2*j+1])
      fprintf(stderr,"ERROR qrcode L%04d i=%d j=%d\n", __LINE__,i,j);
#endif
  // first searching biggest square objects = marker (min=3)
  x0=y0=0; rm=0; dx=job->src.p.x;  dy=job->src.p.y; cs=job->cfg.cs;
  for_each_data(&(job->res.boxlist)) {
    box2 = (struct box *)list_get_current(&(job->res.boxlist));
    x02=box2->x0; dx2=box2->x1 - x02 + 1;  /* ToDo: correction for skewed matrix */
    y02=box2->y0; dy2=box2->y1 - y02 + 1;
    /* detect width (bdx) and height (bdy) of possible matrix */
    /* ToDo: better check for a line */
    if (dx2<7 || dy2<7 || 8*abs(dx2-dy2)>dx2+dy2) continue;
    // ToDo: get center point c0, get max distance point from center = i1,
    //  (in upper left region)
    //  get max distance point from i1 = i2, get max dist from i0,i2 = i3
    //  get max distance from i3 = i4 , check square
#if 0
    int i1, i2, i3, i4, d;
    if (!box2->num_frames) continue;
    j=0; ix=x0+dx/2; iy=y0+dy/2;
    for (i=0;i<box2->num_frame_vectors[0];i++) {
      x=box2->frame_vector[i][0]; /* take a vector */
      y=box2->frame_vector[i][1];
      /* distance to upper left end, normalized to 128 */
      // d=sq((x-rx)*128/dx)+sq((y-ry)*128/dy); // old 2009-07
      d=abs(ix-x) + abs(iy-y);
      if (d>=j) { j=d; i1=i;  }
    }
#endif
    y= y02+dy2/2;
    x= loop(box2->p,x02  ,y,dx2,cs,0,RI); if (    x         >dx2/16) continue;
    x+=loop(box2->p,x02+x,y,dx2,cs,1,RI); if (abs(x-  dx2/7)>dx2/16) continue; 
    x+=loop(box2->p,x02+x,y,dx2,cs,0,RI); if (abs(x-2*dx2/7)>dx2/16) continue; 
    x+=loop(box2->p,x02+x,y,dx2,cs,1,RI); if (abs(x-5*dx2/7)>dx2/16) continue; 
    x+=loop(box2->p,x02+x,y,dx2,cs,0,RI); if (abs(x-6*dx2/7)>dx2/16) continue; 
    y= y02+dy2/14;
    x= loop(box2->p,x02  ,y,dx2,cs,0,RI); if (abs(x-0*dx2/7)>dx2/16) continue; 
    x+=loop(box2->p,x02+x,y,dx2,cs,1,RI); if (abs(x-7*dx2/7)>dx2/16) continue; 
    y= y02+13*dy2/14;
    x= loop(box2->p,x02  ,y,dx2,cs,0,RI); if (abs(x-0*dx2/7)>dx2/16) continue; 
    x+=loop(box2->p,x02+x,y,dx2,cs,1,RI); if (abs(x-7*dx2/7)>dx2/16) continue; 
    y= y02+3*dy2/14;
    x= loop(box2->p,x02  ,y,dx2,cs,0,RI); if (abs(x-0*dx2/7)>dx2/16) continue; 
    x+=loop(box2->p,x02+x,y,dx2,cs,1,RI); if (abs(x-1*dx2/7)>dx2/16) continue; 
    x+=loop(box2->p,x02+x,y,dx2,cs,0,RI); if (abs(x-6*dx2/7)>dx2/16) continue; 
    y= y02+11*dy2/14;
    x= loop(box2->p,x02  ,y,dx2,cs,0,RI); if (abs(x-0*dx2/7)>dx2/16) continue; 
    x+=loop(box2->p,x02+x,y,dx2,cs,1,RI); if (abs(x-1*dx2/7)>dx2/16) continue; 
    x+=loop(box2->p,x02+x,y,dx2,cs,0,RI); if (abs(x-6*dx2/7)>dx2/16) continue; 
    x= x02+dx2/2;
    y= loop(box2->p,x,y02  ,dy2,cs,0,DO); if (    y         >dy2/16) continue;
    y+=loop(box2->p,x,y02+y,dy2,cs,1,DO); if (abs(y-  dy2/7)>dy2/16) continue; 
    y+=loop(box2->p,x,y02+y,dy2,cs,0,DO); if (abs(y-2*dy2/7)>dy2/16) continue; 
    y+=loop(box2->p,x,y02+y,dy2,cs,1,DO); if (abs(y-5*dy2/7)>dy2/16) continue; 
    y+=loop(box2->p,x,y02+y,dy2,cs,0,DO); if (abs(y-6*dy2/7)>dy2/16) continue; 
    x= x02+dx2/14;
    y= loop(box2->p,x,y02  ,dy2,cs,0,DO); if (abs(y-0*dy2/7)>dy2/16) continue; 
    y+=loop(box2->p,x,y02+y,dy2,cs,1,DO); if (abs(y-7*dy2/7)>dy2/16) continue; 
    x= x02+13*dx2/14;
    y= loop(box2->p,x,y02  ,dy2,cs,0,DO); if (abs(y-0*dy2/7)>dy2/16) continue; 
    y+=loop(box2->p,x,y02+y,dy2,cs,1,DO); if (abs(y-7*dy2/7)>dy2/16) continue; 
    x= x02+3*dx2/14;
    y= loop(box2->p,x,y02  ,dy2,cs,0,DO); if (abs(y-0*dy2/7)>dy2/16) continue; 
    y+=loop(box2->p,x,y02+y,dy2,cs,1,DO); if (abs(y-1*dy2/7)>dy2/16) continue; 
    y+=loop(box2->p,x,y02+y,dy2,cs,0,DO); if (abs(y-6*dy2/7)>dy2/16) continue; 
    x= x02+11*dx2/14;
    y= loop(box2->p,x,y02  ,dy2,cs,0,DO); if (abs(y-0*dy2/7)>dy2/16) continue; 
    y+=loop(box2->p,x,y02+y,dy2,cs,1,DO); if (abs(y-1*dy2/7)>dy2/16) continue; 
    y+=loop(box2->p,x,y02+y,dy2,cs,0,DO); if (abs(y-6*dy2/7)>dy2/16) continue; 
    g_debug(fprintf(stderr,"\n# qrcode marker %d %4d %4d at %4d %4d",num_marker,dx2,dy2,x02,y02);)
    if (num_marker<3) {
      qr_marker[num_marker][0]=x02;
      qr_marker[num_marker][1]=y02;
      qr_marker[num_marker][2]=dx2;
      qr_marker[num_marker][3]=dy2;
    } else qrcode=-1;
    num_marker++;
  } end_for_each(&(job->res.boxlist));
  if (num_marker==3 && qr_marker[0][0]>qr_marker[1][0]) {
    // sort upper markers
    i=qr_marker[0][0]; qr_marker[0][0]=qr_marker[1][0]; qr_marker[1][0]=i;
    i=qr_marker[0][1]; qr_marker[0][1]=qr_marker[1][1]; qr_marker[1][1]=i;
    i=qr_marker[0][2]; qr_marker[0][2]=qr_marker[1][2]; qr_marker[1][2]=i;
    i=qr_marker[0][3]; qr_marker[0][3]=qr_marker[1][3]; qr_marker[1][3]=i;
  }
  if (num_marker==3  // check right order (ToDo: sort it)
   //      a.x0           a.dx           b.x0
   && qr_marker[0][0]+qr_marker[0][2]<qr_marker[1][0]
   //      a.y0           a.dy           c.y0
   && qr_marker[0][1]+qr_marker[0][3]<qr_marker[2][1]) { // qrcode detected
    x03=qr_marker[0][0];
    y03=qr_marker[0][1];
    dx3=qr_marker[1][0]+qr_marker[1][2]-qr_marker[0][0];
    dy3=qr_marker[2][1]+qr_marker[2][3]-qr_marker[0][1];
    i = num_cross(x03,x03+dx3-1,y03+13*qr_marker[1][3]/14,
                                y03+13*qr_marker[1][3]/14,box2->p,job->cfg.cs);
    i = 2*(i-2)+15; // num_pixel from timing pattern
    j = num_cross(x03+13*qr_marker[1][2]/14,
                  x03+13*qr_marker[1][2]/14,y03,y03+dy3-1,box2->p,job->cfg.cs);
    j = 2*(j-2)+15; // num_pixel from timing pattern
    x= 14 * dx3 / (qr_marker[0][2]+qr_marker[1][2]);
    y= 14 * dy3 / (qr_marker[0][3]+qr_marker[2][3]);
    num_bars= i;
    if ((i-17)%4!=0 && (j-17)%4==0) num_bars=j; // bad i, but good j ?
    qr_version= (num_bars-17) / 4; // size 21..177 to version 1..40
    // ToDo: check syncs and mark all boxes within qr_code as picture
    // num_cross = distance / base
    g_debug(fprintf(stderr,"\n# qrcode at %4d %4d %4d %4d px %d %d = %d %d %d v= %d ",
      x03,y03,dx3,dy3,x,y, i,j,num_bars, qr_version);)
    x=y=num_bars; // better?
    //  num alignments/per_direction: 1-1 0, 2-11 1, 12-20++ 2
    //  num alignments = (na+1)^2-3 , adist= (x-13)/(2*na)
    //  distance from 6 to first and further alignment patterns (ad1,ad2,ad2,..)
    //     v1: +8 
    //   v2-6: +12      +16      +20      +24      +28
    //  v7-13: +16,16   +18,18   +20,20   +22,22   +24,24   +26,26   +28,28
    // v14-20: +20,20*2 +20,22*2 +20,24*2 +24,24*2 +24,26*2 +24,28*2 +28,28*2
    // v21-27: +22,22*3 +20,24*3 +24,24*3 +22,26*3 +26,26*3 +24,28*3 +28,28*3 
    // v28-34: +20,24*4 +24,24*4 +20,26*4 +24,26*4 +28,26*4 +24,28*4 +28,28*4
    // v35-40: +24,24*5 +18,26*5 +22,26*5 +26,26*5 +20,28*5 +24,28*5
    //  start: v=2
    // ad2 must be set, to avoid endeless loop later!?
    ad1=ad2=28; an2=0; // num alignments - 1 (after initial alignment)
    for (i=2;i<=qr_version;i++){
      if (an2) ad2=(4*i+17-13+an2-an2/4*2)/(an2+1); // main distance
      ad2=2*((ad2+1)/2);       // round up
      ad1=(4*i+17-13)-an2*ad2; // rest distance for the leftmost pattern
      if (ad1+an2*ad2 >= 28+an2*28) an2++; 
      // max distance alignments reached
    }
    num_rawbits= (4*qr_version+17)*(4*qr_version+17)  // square area
               - 3 * 8*8            //  - 8*8 finder pattern
               -   ((an2>=0) ? 5*5 * (an2+1)*(an2+1) : 0) // alignment pattern
               - 2*((an2>=1) ? 4*5 * (an2  ) : 0) // alignment pattern
               - 2*(4*qr_version+17-16)  // timing pattern
               - ((qr_version<=6)?0:2*3*6) // undocumented extra pattern?
               - 2*15    // - 2 * 15 bit format pattern (hor + vert)
               - 1;      // black bit at (8,maxy-7)
    g_debug(fprintf(stderr,"\n# qrcode v= %2d dist= %2d %2d * %d  rawbits= %5d bytes= %5d",
      qr_version, ad1, ad2, an2, num_rawbits, num_rawbits/8);)
    // additional alignment patterns (against skewness)
    //   v1M= head=2Byte + data=16Byte=128bit + ecc=7B? = 25Byte=206bit?
    //  v9  53  v9L=1856bits=230byte(8bit)
    // v40 177 v40L=2953 bytes (2^12) = 23624+24 Bit 
    if (x==y && (x-17)%4==0 && x>=21 && x<=177) { // if square and v=1..40
      bits= (char *)malloc(x*y);
      if (bits) {
        for (i=0;i<x*y;i++) {
          bits[i]=((getpixel(box2->p,
            x03 + ((i%x)*dx3 + dx3/2) / x,
            y03 + ((i/x)*dy3 + dy3/2) / y) < job->cfg.cs) ? 1 : 0);
          //g_debug(if (i%x==0) fprintf(stderr,"\n# qrcode ");)
          //g_debug(fprintf(stderr,"%c",((bits[i])?'@':'.'));)
        }
        qrcode=1;
        // ToDo: check finder pattern
        for (i=0;i<x-14;i++) {
          if ((bits[6*x+(7+i)]&1)!=(i&1)){
            qrcode=-1;
            g_debug(fprintf(stderr,"\n# qrcode bad finder bit at %d %d",7+i,6);)
          }
          if ((bits[6+(7+i)*x]&1)!=(i&1)){
            qrcode=-2;
            g_debug(fprintf(stderr,"\n# qrcode bad finder bit at %d %d",6,7+i);)
          }
          bits[6*x+(7+i)]|=2; // mark as finder
          bits[6+(7+i)*x]|=2;
        }
        if ((bits[8+(x-7-1)*x]&1)==0){ qrcode=-3;
          g_debug(fprintf(stderr,"\n# qrcode bad bit at %d %d",8,x-7);)
        }
        bits[8+(x-7-1)*x]|=2;
        if (ad1) { // mark alignment pattern
          for (i=6;i<y;i+=(i==6 || ad2==0)?ad1:ad2)
          for (j=6;j<x;j+=(j==6 || ad2==0)?ad1:ad2)
          if ((i<8 && j>6 && j<x-8)
           || (j<8 && i>6 && i<y-8)
           || (i>6 && j>6)) {
            int ti, tj;
            for (ti=-2;ti<3;ti++)
            for (tj=-2;tj<3;tj++) bits[(i+ti)*x+(j+tj)]|=2;
          } 
        }
        for (i=0;i<8*8;i++) { // qr-marker pixel
          bits[    (i%8)+x*(    i/8)]|=2;
          bits[x-8+(i%8)+x*(    i/8)]|=2;
          bits[    (i%8)+x*(x-8+i/8)]|=2;
        }
        if (qr_version>6)
        for (i=0;i<3*6;i++) { // qr-marker pixel
          bits[x-11+(i%3)+x*(     i/3)]|=2;
          bits[     (i%6)+x*(x-11+i/6)]|=2;
        }
        // ToDo: check format bits (30 for v<=6, 66 for v>6) ???
        // from right to left
        g_debug(fprintf(stderr,"\n# qrcode h-format bits 0..14: ");)
        for (i=0;i<15;i++) {
          fbits|= (bits[8*x+((i<8)?x-i-1:((i<9)?7:5+9-i))]&1)<<i;
          g_debug(fprintf(stderr,"%d",(fbits>>i)&1);) // bit0 first
          bits[8*x+((i<8)?x-i-1:((i<9)?7:5+9-i))]|=2;
        }
        // from top to bottom
        g_debug(fprintf(stderr,"\n# qrcode v-format bits 0..14: ");)
        for (i=0;i<15;i++) {
          j= (bits[8+x*((i<6)?i:((i<8)?i+1:i+x-7-8))]&1);
          if (((fbits>>i)&1)!=j) qrcode=-4;
          g_debug(fprintf(stderr,"%d",j);)  // bit0 first
          bits[8+x*((i<6)?i:((i<8)?i+1:i+x-7-8))]|=2;
        }
        g_debug(if(qrcode<0)fprintf(stderr,"\n# qrcode error %d ",qrcode);)
        //                  err mask ecc
        fbits ^= 0x5412; //  10 101 0000010010 = 0x5412
        g_debug(fprintf(stderr,"\n# qrcode   format bits 0..14: ");)
        // ToDo: check ECC
        for (i=0;i<15;i++) {
          g_debug(fprintf(stderr,"%d",(fbits>>i)&1);)  // bit0 first
        }
        // errorlevel: 0..3 = 00=M(15%) 01=L(7%) 10=H(30%) 11=Q(25%) maxlost
        //  21x21 = level1 H: 9 bytes + 17 bytes RedSolomon
        // mask pattern: 0..7: invers pixel rules
        //   mask needed to avoid finder and timing pattern in data
        qr_mask= 7 & (fbits>>10); // 0..7
        { // BCH_15_5 (3*5bit) Reed-Solomon-encode
          int data, wk=0;
          data= 31 & (fbits>>10);
          data <<= 5;
          for (i=0; i<5; i++) {
            wk <<= 1; data <<= 1;
            if ((wk^data) & 0x400)  wk ^= 0x137;
          } data = (data & 0x7c00) | (wk & 0x3ff);
          g_debug(fprintf(stderr,"\n# qrcode ECC check: 0x%04x == 0x%04x",fbits,data);)
          // ToDo: if not equal try to encode all 5-bit-BCH-words and compute
          //   number of different bits, if num_diff_bits<=3 we found it 
        }
        qr_ecclevel= 1 ^ (3 & (fbits>>13));
        g_debug(fprintf(stderr,"\n# qrcode errorlevel^1 = %d (2bit)",qr_ecclevel);)
        g_debug(fprintf(stderr,"\n# qrcode mask pattern = %d (3bit)",qr_mask);)
        g_debug(fprintf(stderr,"\n# qrcode 10bit-ECC = 0x%04x",1023&(fbits>>0));)
        for (i=0;i<x*y;i++) {
          const char xx[4]=".o_@";
          g_debug(if (i%x==0) fprintf(stderr,"\n# qrcode ");)
          g_debug(fprintf(stderr,"%c",xx[bits[i]&3]);)
        }
        // ToDo: check ECC Bose-Chaudhuri-Hocquenghem(BCH)(15,5) 15bit,5data
        //   G(x)=x^10+x^8+x^5+x^4+x^2+x+1 = 10100110111 = 0x0A37 ???
        //   F(x)=x^14+x^11+x^10       = 10011.......... = 0x4C00 (data=10011)
        //   R(x)=x^8+x^7+x^6+x        =      0111000010 = 0x01C2 (ecc)
        // http://de.wikipedia.org/wiki/BCH-Code
        // http://www.swetake.com/qr/qr6_en.html
        // first 4+8..10 bit data
        // data: 1:3*[0-9]=10bit + 7bit_for_rest2*[0-9] + 3bit_for_rest1*[0..9]
        //       2:2*[0-9A-Z $%*+-./:]=11bit + 6bit_rest1 (45*char1+char2)
        //       4:8byte, 8:Kanji=13bit
        // 4bit-mode={1=numeric,2=alpha,4=byte,8=kanji}
        // 8..10bit-len: 8bit for byte+kanjy, 9bit for alpha, 10bit for numeric
        //  fillbits=0, fillbytes=0xEC,0x11 (see below)
        // get data, start at x,y
        // ToDo: mark non_data_pixel using 2nd+3th bit?
        i=0; // count data bits = valid bits
        for (iy=0;iy<x;iy++)
        for (ix=0;ix<x;ix++) {
          int i2 = iy*x + ix;
          if ((bits[i2]&6)==0) // valid pixel?
          if ( (qr_mask==0 && (iy+ix)%2==0)
            || (qr_mask==1 && (iy   )%2==0)
            || (qr_mask==2 && (   ix)%3==0)
            || (qr_mask==3 && (iy+ix)%3==0)     // OK
            || (qr_mask==4 && (iy/2+ix/3)%2==0) // OK
            || (qr_mask==5 &&  (iy*ix)%2 + (iy*ix)%3 ==0) // OK
            || (qr_mask==6 && ((iy*ix)%2 + (iy*ix)%3) %2 ==0)
            || (qr_mask==7 && ((iy*ix)%3 + (iy+ix)%2) %2 ==0) ) bits[i2]^=1;
          if ((bits[i2]&6)==0) i++;
        }
        num_rawbits= i; // overwrite bad computed num_rawbits
        g_debug(fprintf(stderr,"\n# qrcode rawbits= %5d bytes= %5d", i, i/8);)
#if 1
        g_debug(fprintf(stderr,"\n# qrcode unmasked: ");)
        for (i=0;i<x*y;i++) {
          const char xx[4]=".x _";
          g_debug(if (i%x==0) fprintf(stderr,"\n# qrcode ");)
          g_debug(fprintf(stderr,"%c",xx[bits[i]&3]);)
        }
#endif
// testing deinterleave 2+2 for v5 = 46 data + 88 ecc, head=12bit nchars=44
//  bit-data fitting to mod 8: no way (best fit is 4bit-shift)
//  interleave-sequence data 11 11 12 12 (!!) ecc 22 22 22 22 (??)
//  qrencode -8 -lH -v5 -oa.png '333333333D3333333333U33333333333f3333333333w'
//  # 3=0x33 D=0x44 U=0x55 f=0x66 w=0x77 as byte position marker!
//  # nbytes=2+100=5*12+3 interleave=2+2
// testing b1+b2=3+2  data=292raw-110ecc=182 182/(3+2)=36
//  interleave sequence: 36 36 36 37 37
//  qrencode -8 -lM -v9 -oa.png '(34*3)D(34*3)4U(34*3)3f(34*3)33w(34*3)3"'
//  (34*3)=3333333333333333333333333333333333
        qrbytes=(unsigned char *)malloc(x*x/8); // enough space for data bits + ecc
        nbits=0; // num valid data bits 0..x*x-- of all data blocks
        bbits=0; // 8 bits
        int num_data_bytes, num_ecc_bytes; // data bytes include header bits
        interleave= qrConst[qr_version-1][6+2*qr_ecclevel+0]  // 1-40 0123=LMQH
                  + qrConst[qr_version-1][6+2*qr_ecclevel+1];
        // raw_bytes, raw_bits_mod, ecc0 .. ecc3
        num_ecc_bytes=  qrConst[qr_version-1][2+qr_ecclevel];
        num_data_bytes= qrConst[qr_version-1][0]-num_ecc_bytes;
        g_debug(fprintf(stderr,"\n# qrcode v%d numbytes= %4d == %4d = %4d data + %4d ecc",
          qr_version, num_rawbits/8, num_data_bytes+num_ecc_bytes,
          num_data_bytes, num_ecc_bytes);)
        g_debug(fprintf(stderr,"\n# qrcode v%d interleave= %d = %d + %d\n# ",
           qr_version,interleave,qrConst[qr_version-1][6+2*qr_ecclevel+0],
                                 qrConst[qr_version-1][6+2*qr_ecclevel+1]);)
        j=-1; // -x means upwards, +x means downwards
        iy=ix=x-1; // start pixel
        if (qrbytes)
        while (ix>=0 && iy>=0) { // de-interleave bytes
          int i2 = iy*x+ix, idx; // help pixel index, old+new byte index
          int b1, b2;
          b1 = qrConst[qr_version-1][6+2*qr_ecclevel+0];
          b2 = qrConst[qr_version-1][6+2*qr_ecclevel+1];
          if ((bits[i2]&6)==0) {  // valid pixel?
            // g_debug(fprintf(stderr,"\n %2d %2d %2d %d",i2%x,i2/x,j,bits[i2]);)
            g_debug(fprintf(stderr,"%d",bits[i2]);)
            bbits =     (bbits << 1) | (bits[i2]&1);  // byte
            nbits++;  // all valid data bits
            // store all bits in 8bit words
            // no warranty that this impirical code works 
            // ToDo: replace by better readable code, or create
            //     better 2D-coding standart replacing QR-Code
            if ((nbits&7)==0) {
              if (nbits/8-1 < num_data_bytes) {
                idx= (nbits/8-1)/interleave
                   +((nbits/8-1)%interleave)*(num_data_bytes/interleave);
                if (idx >= b1*(num_data_bytes/interleave)) // interleaveblock
                  idx= (nbits/8-1-b1)/interleave
                     +((nbits/8-1-b1)%interleave)*(num_data_bytes/interleave+1)
                     + b1*(num_data_bytes/interleave);
                if (nbits/8-1 >= num_data_bytes-b2)
                  idx= (nbits/8-1)/interleave
                     +((nbits/8-1)%interleave)*(num_data_bytes/interleave+1)
                     + b1*(num_data_bytes/interleave);
              }
              else { // ToDo: ecc de-interleave is not proved
                idx= (nbits/8-num_data_bytes-1)/interleave
                   +((nbits/8-num_data_bytes-1)%interleave)*(num_ecc_bytes/interleave)
                   +num_data_bytes;
                if ((nbits/8-1)/interleave >= num_rawbits/8-b2) // interleaveblock
                  idx+= num_rawbits/8-b2 + ((nbits/8-1)%interleave);
              }
              qrbytes[idx]= bbits;
              g_debug(fprintf(stderr," %3d %02x ",idx,bbits);)
              g_debug(if (nbits/8==num_data_bytes) fprintf(stderr,"\n# end_data\n#");)
              g_debug(fprintf(stderr,(((nbits/8)%interleave==0)?"\n# ":" "));)
              if (nbits/8==num_data_bytes - b2)
                for (i=0;i<b1;i++) {
                  g_debug(fprintf(stderr,"%17s"," ");)
                }
              bbits=0; 
            } // used for head+data+ECC
          } // valid bit
          //  (x,maxy) x=max,..,20,18,16,14,12,10,8,(skip6)5,3,1
          // next step (up, down or 2 left)
          // g_debug(fprintf(stderr,"\n# qr1 xy= %3d %3d %+2d ", ix, iy, j);)
          if (ix%2==((ix<6)?1:0) || ix==6) ix--;  // go left
          else if (iy+j>=0 && iy+j<x) { iy+=j; ix++; } // go right up/down
          else { ix--; j*=-1; } // go 2*left + change direction
          // g_debug(fprintf(stderr,"\n# qr2 xy= %3d %3d %+2d ", ix, iy, j);)
        } // i=max(x*x-x-1)..0
        // RS-check/decoding
        //  needed to define addition and multiplication and finaly a^i
        // now wen need the RS generator polynom g(x) depending from size
        // ToDo: ECC check and correction, test=tmp10/qrcode_21c4m4e2.png
        // qrencode 3.1.1 Kentaro Fukuchi 2010 0123=LMQH
        //  -l H -v 10 -o a.png '000000000000000000000000000'
        // v1 H m1=17= 3*5+2= 57bit   57..59  bit+18 raw= 9+17ecc
        //    Q                                      raw=13+13ecc
        //    L m1=41=3*13+2=137bit  137..139 bit+18 raw=19 +7ecc
        // v2 H m1=34=3*11+1=114bit
        //    L m1=77=3*25+2=257bit
        // v3 e2=Q m1= raw=34+36ecc=70(ok)rest7
        int b1, b2;
        int dl=0, el=0, i_ecc=num_data_bytes, i_data=0; // data and ecc length
        unsigned char qr_ecc[256]; // buffer for generated ecc data
        b1 = qrConst[qr_version-1][6+2*qr_ecclevel+0];
        b2 = qrConst[qr_version-1][6+2*qr_ecclevel+1];
        // for b1 and b2 we have different datasize ???
        for (i=0; i<b1+b2; i++) { // (interleaved) block nr.
          if (i==0 || i==b1) {
            dl = num_data_bytes/(b1+b2); // divided in blocks to reduce RS size
            if (i==b1) dl++;
            el =  num_ecc_bytes/(b1+b2);
            init_rs(8,0x11D,0,1,el,255-dl-el);
          }
          // gfpoly = 0x11D is the primitive polynom for QR-Code
          // max. data+ecc=255
          encode_rs_char(&rs, qrbytes + i_data, qr_ecc);
          g_debug(for(j=0;j<el;j++)fprintf(stderr," %02x ",qr_ecc[j]);fprintf(stderr,"\n# ");)
          g_debug(for(j=0;j<el;j++)fprintf(stderr," %02x ",qrbytes[i_ecc+j]);fprintf(stderr,"\n# ");)
          for (j=0;j<el;j++) if (qr_ecc[j]!=qrbytes[i_ecc+j])
            {qrcode=-3;g_debug(fprintf(stderr," ECC-Error ");)break;}
          i_data += dl;
          i_ecc  += el;
        }

        // get 1..2 bits from bits[i] and bits[i-1]
        // 1st bit + 2nd bit stored in i2, i2-1
        if (qr_version<=40) head_bits=head_bits40;
        if (qr_version<=26) head_bits=head_bits26;
        if (qr_version<= 9) head_bits=head_bits09;
        block_nbits=0; // num valid data bits per block
        nwbits=0; // num bits per local word 0..14
        nchars=0; // num chars (nwords*cpw+rest) expected
        dchars=0; // num chars decoded
        wbits=0;  // data bits of local word
        int next_wbits=1023; // bits of the next dataword
        unsigned char *ptext=NULL;    // pointer to char tuple of next word
        // get bits and words from deinterleaved byte stream
        g_debug(fprintf(stderr,"\n# qrcode bytes: %02x %02x %02x ...\n# qr new_block ",
            255&(int)qrbytes[0], 255&(int)qrbytes[1], 255&(int)qrbytes[2]);)
        // read all blocks
        //  qrencode  -l H -v 5 -o a.png '0123456789abcdefghijklmnopqrstuvwxyz'
        //  # 10c1=0123456789=34bit + 26c4=abcdefghijklmnopqrstuvwxyz=26byte
        if (!qrtext) qrtext= (unsigned char *)malloc(3*num_rawbits/10+1); // 70%
        if (qrtext)
        // for (nbits=0; nbits<num_rawbits; nbits++)
        for (nbits=0; nbits<num_data_bytes*8; nbits++)
        {
          // g_debug(fprintf(stderr,"\n %2d %2d %2d %d",i2%x,i2/x,j,bits[i2]);)
          g_debug(fprintf(stderr,"%d",1&(qrbytes[nbits/8]>>(7-nbits%8)));)
          wbits = (wbits << 1)  |    (1&(qrbytes[nbits/8]>>(7-nbits%8)));  // word
          block_nbits++;
          nwbits++; // local word

          if (qr_mode==0 && block_nbits==4) {
            qr_mode= wbits & 15;
            wbits=0; nwbits=0; // word bits and valid number of bits
            // if (qr_mode==3) qr_mode=1; // auto correction ???
            g_debug(fprintf(stderr," mode=%d numbits=%d wordbits=%d wchr=%d\n"
               "# qr data ", qr_mode, head_bits[qr_mode]-4,
                                      word_bits[qr_mode],
                                      word_nchr[qr_mode]);)
            nchars=0; // flag new block
          }
          // set extra nchars flag!?
          // ToDo: what about bad qr_mode? (not 1,2,4,8)
          if (nchars==0 && head_bits[qr_mode]!=0
                        && head_bits[qr_mode]==block_nbits) {
            nchars= wbits;    // 8..14 bits
            wbits=0; nwbits= 0; // sync to data words
            next_wbits= word_bits[qr_mode];
            if (nchars==0) { qr_mode=0; block_nbits=0; } // reset, new block?
            g_debug(fprintf(stderr," nchars=%d\n# qr data ", nchars);)
          }
          if (dchars==0) qrtext[0]=0;
          if (qr_mode==0 || !nchars) continue; // we dont have chars to read
          if (block_dchars>=nchars) continue;  // all block chars read
          if (nwbits < next_wbits) continue; // not enough bits read
          ptext = &(qrtext[dchars]); // for debugging word
          // reading chars
          if (dchars + word_nchr[qr_mode] >= 3*num_rawbits/10) // safety
            { fprintf(stderr,"qrcode.unexpected_overflow\n");break; }
          // decode
          if (qr_mode==8) {  // 13bit??? UTF ??? JIS ? 
            int c1 = (wbits/192) + wbits % 192;
            if (c1+0x8140 <= 0x9FFC) c1+=0x8140;
            else                     c1+=0xC140;
            qrtext[dchars  ]= c1>>8;  // ToDo ??
            qrtext[dchars+1]= c1&255; // ToDo
            dchars       += 2;
            block_dchars += 2;
            if (nchars-block_dchars==1) next_wbits=8;
          }
          if (qr_mode==4){  // 8bit
            qrtext[dchars]= wbits; // ToDo: what about ""<>&?
            dchars       += 1;
            block_dchars += 1;
          }
          if (qr_mode==2) { // 45*45=2025=11bit ToDo: error if 2025++
            int c1 = (wbits/45)%45, c2 = wbits%45;
            char crest[9+1]=" $%*+-./:";
            if (next_wbits==11) {
              qrtext[dchars  ]= c1+'0';
              qrtext[dchars+1]= c2+'0';
              if (c1> 9) qrtext[dchars  ]= c1-10+'A';
              if (c2> 9) qrtext[dchars+1]= c2-10+'A';
              if (c1>35) qrtext[dchars  ]= crest[c1-36];
              if (c2>35) qrtext[dchars+1]= crest[c2-36];
              dchars       += 2;
              block_dchars += 2;
              if (nchars-block_dchars==1) next_wbits=6;
            } else if (next_wbits==6) {
              qrtext[dchars  ]= c2+'0';
              if (c2> 9) qrtext[dchars  ]= c2-10+'A';
              if (c2>35) qrtext[dchars  ]= crest[c2-36];
              dchars       += 1;
              block_dchars += 1;
              next_wbits=0;
            }
            // ToDo: odd numchars?
          }
          if (qr_mode==1) { // 10*10*10=1000=10bit ToDo: error 1001++
            if (next_wbits==10) {
              qrtext[dchars  ]= '0'+ (wbits)/100;
              qrtext[dchars+1]= '0'+((wbits)/10)%10;
              qrtext[dchars+2]= '0'+ (wbits)%10;
              dchars       += 3;
              block_dchars += 3;
            }
            if (next_wbits==7) {
              qrtext[dchars  ]= '0'+ (wbits)/10;
              qrtext[dchars+1]= '0'+ (wbits)%10;
              dchars       += 2;
              block_dchars += 2;
              next_wbits=0;
            }
            if (next_wbits==4) {
              qrtext[dchars  ]= '0'+ (wbits)%10;
              dchars       += 1;
              block_dchars += 1;
              next_wbits=0;
            }
            if (nchars-block_dchars==1) next_wbits=4;
            if (nchars-block_dchars==2) next_wbits=7;
            // ToDo: %3!=0 rest nchars?
          }
          if (dchars<=3*num_rawbits/10) qrtext[dchars]=0; // end of string
#if DO_DEBUG
          if ((job->cfg.verbose&1) && block_dchars < nchars+word_nchr[qr_mode])
            fprintf(stderr," %4s  next_wbits= %2d byte= %3d", ptext, next_wbits, nbits/8);
          if ((job->cfg.verbose&1) && block_dchars < nchars)
            fprintf(stderr,"\n# qr data ");
#endif
          wbits=0; nwbits=0;
          if (block_dchars >= nchars) { // reset block
            block_dchars=0; nchars=0; qr_mode=0; block_nbits=0;
            g_debug(fprintf(stderr,"\n# qr new_block ");)
          }
          // end reading data word = char tuple
        } // i=0..num_rawbits
      } else fprintf(stderr,"qrcode.malloc failed\n");
    } // if square and v=1..40
    
    g_debug(fprintf(stderr,"\n# qr dchars=%d nbits=%d ", dchars, nbits);)
    // Reed-Solomon
    // size+errlevel = headbits+databits+fillbits + ecbits + ?
    // 21H  9*8 17*8 215 RS: 1block (26,9,8) = (allbytes,databytes,errbytes)
    // sample 21H 9data+17ecc=26byte+
    // f(x)=byte0*x^25+byte1*x^24+...+byte8*x^17 (9byte data)
    //      byte0=32=a^5  byte1=7=a^198 ... (table4)
    // n=17 g(x)=sum(i=0..n)a^ai*x^i   where a^255=1
    //    ai=136,163,243,39,150,99,24,147,214,206,123,239,43,78,206,139,43,17,0
    //  a^ai=79,99,125,53,85,134,143,41,249,83,197,22,119,120,83,66,119,152,1
    //  rest of g(x)/f(x) is r(x)=byte16*x^16+byte15*x^15+...bye1*x+byte0
    // 21L  19*8 7*8 ... RS: 1block (26,19,2)
    //  n=7 g(x)=sum(i=0..n)a^ai*x^i
    //    ai=21,102,238,149,146,229,87,0
    // check? f/g=x+R?
    // gpg --export -a 0x26D124F8 | qrencode    -oa.png # v31 nc=1723
    // gpg --export -a --export-options export-minimal 0x26D124F8
    //   | qrencode -8 -oa.png # v30 137*137 nc=1723
    //  300dpi(12dot/mm) 3dot=0.25mm 4dot=0.33mm 5dot=0.42mm 6dot=0.5mm
    //   177x177 = 45x45mm^2
    if (qrcode>0) {
      code= (char *)malloc(4000);
      if (code && qrtext) {
        code[0]='_'; code[1]=0;
//        if (dchars<512) // ToDo: limited output buffer? or stdout?
        sprintf(code,"<barcode type=\"qrcode%d\" chars=\"%d\""
          " ecclevel=\"%d\" >\n%s\n</barcode>",
          qr_version, dchars, qr_ecclevel, qrtext);
//        else printf("<barcode type=\"qrcode%d\" chars=\"%d\""
//          " ecclevel=\"%d\" >\n%s\n</barcode>",
//           qr_version, dchars, qr_ecclevel, qrtext);
        // ToDo: error=...
      }
    }
    if (qrcode<0) {
      code= (char *)malloc(128);
      if (code) {
        strncpy(code,"<barcode type=\"unknown qrcode\" />",128);
      }
    }
    if (qrtext)  free(qrtext);
    if (qrbytes) free(qrbytes);
    box3=NULL;
    for_each_data(&(job->res.boxlist)) {
      box2 = (struct box *)list_get_current(&(job->res.boxlist));
      x02=box2->x0; dx2=box2->x1-x02+1;  /* ToDo: correction for skewed matrix */
      y02=box2->y0; dy2=box2->y1-y02+1;
      if (x02>=x03-qr_marker[0][2]/14
       && y02>=y03-qr_marker[0][3]/14
       && x02+dx2<=x03+dx3+qr_marker[0][2]/14
       && y02+dy2<=y03+dy3+qr_marker[0][3]/14 ) { // object inside QR area
        box2->c=PICTURE; /* BARCODE */
        box2->x0=x03;
        box2->y0=y03;
        box2->x1=x03+dx3-1;
        box2->y1=y03+dy3-1;
        if (!box3) {
          box3=box2;
          if (code) setas(box3,code,99); /* ToDo: set a better weight */
        } else {
          // ToDo: list_del except one
          rm++; /* count removed boxes */
          list_del(&(job->res.boxlist),box2);
          free_box(box2);
        }
      }
    } end_for_each(&(job->res.boxlist));
    if (code) free(code);
    if (job->cfg.verbose)  
      fprintf(stderr,"\n# ... removed boxes: %d", rm);
    rm=0;
  } // qrcode detected
} // qrcode

  /* recalculate averages without bars */
  job->res.numC=job->res.sumX=job->res.sumY=j2=0;
  for_each_data(&(job->res.boxlist)) {
    j2++;
    box3 = (struct box *)list_get_current(&(job->res.boxlist));
    if (box3->c==PICTURE) continue;
    job->res.numC++; /* count remaining boxes */
    job->res.sumX+=box3->x1-box3->x0+1;
    job->res.sumY+=box3->y1-box3->y0+1;
  } end_for_each(&(job->res.boxlist));
  if(job->cfg.verbose)  
    fprintf(stderr,"\n# ... boxes %d nC %d\n",
            j2, job->res.numC);
            
  return 0;
}

