]> git.sur5r.net Git - iec16022/blob - iec16022ecc200.c
Imported Upstream version 0.1
[iec16022] / iec16022ecc200.c
1 /** 
2  *
3  * IEC16022 bar code generation
4  * Adrian Kennard, Andrews & Arnold Ltd
5  * with help from Cliff Hones on the RS coding
6  * 
7  * (c) 2004 Adrian Kennard, Andrews & Arnold Ltd
8  * (c) 2006 Stefan Schmidt <stefan@datenfreihafen.org>
9  * 
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
23  *
24  */
25
26
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <ctype.h>
30 #include <string.h>
31 #include <time.h>
32 #include <popt.h>
33 #include <malloc.h>
34 #include "reedsol.h"
35 #include "iec16022ecc200.h"
36
37 static struct ecc200matrix_s
38 {
39    int H,
40      W;
41    int FH,
42      FW;
43    int bytes;
44    int datablock,
45      rsblock;
46 }
47 ecc200matrix[] =
48 {
49    10, 10, 10, 10, 3, 3, 5,     //
50       12, 12, 12, 12, 5, 5, 7,  //
51       8, 18, 8, 18, 5, 5, 7,    //
52       14, 14, 14, 14, 8, 8, 10, //
53       8, 32, 8, 16, 10, 10, 11, //
54       16, 16, 16, 16, 12, 12, 12,       //
55       12, 26, 12, 26, 16, 16, 14,       //
56       18, 18, 18, 18, 18, 18, 14,       //
57       20, 20, 20, 20, 22, 22, 18,       //
58       12, 36, 12, 18, 22, 22, 18,       //
59       22, 22, 22, 22, 30, 30, 20,       //
60       16, 36, 16, 18, 32, 32, 24,       //
61       24, 24, 24, 24, 36, 36, 24,       //
62       26, 26, 26, 26, 44, 44, 28,       //
63       16, 48, 16, 24, 49, 49, 28,       //
64       32, 32, 16, 16, 62, 62, 36,       //
65       36, 36, 18, 18, 86, 86, 42,       //
66       40, 40, 20, 20, 114, 114, 48,     //
67       44, 44, 22, 22, 144, 144, 56,     //
68       48, 48, 24, 24, 174, 174, 68,     //
69       52, 52, 26, 26, 204, 102, 42,     //
70       64, 64, 16, 16, 280, 140, 56,     //
71       72, 72, 18, 18, 368, 92, 36,      //
72       80, 80, 20, 20, 456, 114, 48,     //
73       88, 88, 22, 22, 576, 144, 56,     //
74       96, 96, 24, 24, 696, 174, 68,     //
75       104, 104, 26, 26, 816, 136, 56,   //
76       120, 120, 20, 20, 1050, 175, 68,  //
77       132, 132, 22, 22, 1304, 163, 62,  //
78       144, 144, 24, 24, 1558, 156, 62,  // 156*4+155*2
79       0                         // terminate
80 };
81
82  // simple checked response malloc
83 static void *
84 safemalloc (int n)
85 {
86    void *p = malloc (n);
87    if (!p)
88    {
89       fprintf (stderr, "Malloc(%d) failed\n", n);
90       exit (1);
91    }
92    return p;
93 }
94
95 // Annex M placement alorithm low level
96 static void
97 ecc200placementbit (int *array, int NR, int NC, int r, int c, int p, char b)
98 {
99    if (r < 0)
100    {
101       r += NR;
102       c += 4 - ((NR + 4) % 8);
103    }
104    if (c < 0)
105    {
106       c += NC;
107       r += 4 - ((NC + 4) % 8);
108    }
109    array[r * NC + c] = (p << 3) + b;
110 }
111
112 static void
113 ecc200placementblock (int *array, int NR, int NC, int r, int c, int p)
114 {
115    ecc200placementbit (array, NR, NC, r - 2, c - 2, p, 7);
116    ecc200placementbit (array, NR, NC, r - 2, c - 1, p, 6);
117    ecc200placementbit (array, NR, NC, r - 1, c - 2, p, 5);
118    ecc200placementbit (array, NR, NC, r - 1, c - 1, p, 4);
119    ecc200placementbit (array, NR, NC, r - 1, c - 0, p, 3);
120    ecc200placementbit (array, NR, NC, r - 0, c - 2, p, 2);
121    ecc200placementbit (array, NR, NC, r - 0, c - 1, p, 1);
122    ecc200placementbit (array, NR, NC, r - 0, c - 0, p, 0);
123 }
124
125 static void
126 ecc200placementcornerA (int *array, int NR, int NC, int p)
127 {
128    ecc200placementbit (array, NR, NC, NR - 1, 0, p, 7);
129    ecc200placementbit (array, NR, NC, NR - 1, 1, p, 6);
130    ecc200placementbit (array, NR, NC, NR - 1, 2, p, 5);
131    ecc200placementbit (array, NR, NC, 0, NC - 2, p, 4);
132    ecc200placementbit (array, NR, NC, 0, NC - 1, p, 3);
133    ecc200placementbit (array, NR, NC, 1, NC - 1, p, 2);
134    ecc200placementbit (array, NR, NC, 2, NC - 1, p, 1);
135    ecc200placementbit (array, NR, NC, 3, NC - 1, p, 0);
136 }
137
138 static void
139 ecc200placementcornerB (int *array, int NR, int NC, int p)
140 {
141    ecc200placementbit (array, NR, NC, NR - 3, 0, p, 7);
142    ecc200placementbit (array, NR, NC, NR - 2, 0, p, 6);
143    ecc200placementbit (array, NR, NC, NR - 1, 0, p, 5);
144    ecc200placementbit (array, NR, NC, 0, NC - 4, p, 4);
145    ecc200placementbit (array, NR, NC, 0, NC - 3, p, 3);
146    ecc200placementbit (array, NR, NC, 0, NC - 2, p, 2);
147    ecc200placementbit (array, NR, NC, 0, NC - 1, p, 1);
148    ecc200placementbit (array, NR, NC, 1, NC - 1, p, 0);
149 }
150
151 static void
152 ecc200placementcornerC (int *array, int NR, int NC, int p)
153 {
154    ecc200placementbit (array, NR, NC, NR - 3, 0, p, 7);
155    ecc200placementbit (array, NR, NC, NR - 2, 0, p, 6);
156    ecc200placementbit (array, NR, NC, NR - 1, 0, p, 5);
157    ecc200placementbit (array, NR, NC, 0, NC - 2, p, 4);
158    ecc200placementbit (array, NR, NC, 0, NC - 1, p, 3);
159    ecc200placementbit (array, NR, NC, 1, NC - 1, p, 2);
160    ecc200placementbit (array, NR, NC, 2, NC - 1, p, 1);
161    ecc200placementbit (array, NR, NC, 3, NC - 1, p, 0);
162 }
163
164 static void
165 ecc200placementcornerD (int *array, int NR, int NC, int p)
166 {
167    ecc200placementbit (array, NR, NC, NR - 1, 0, p, 7);
168    ecc200placementbit (array, NR, NC, NR - 1, NC - 1, p, 6);
169    ecc200placementbit (array, NR, NC, 0, NC - 3, p, 5);
170    ecc200placementbit (array, NR, NC, 0, NC - 2, p, 4);
171    ecc200placementbit (array, NR, NC, 0, NC - 1, p, 3);
172    ecc200placementbit (array, NR, NC, 1, NC - 3, p, 2);
173    ecc200placementbit (array, NR, NC, 1, NC - 2, p, 1);
174    ecc200placementbit (array, NR, NC, 1, NC - 1, p, 0);
175 }
176
177 // Annex M placement alorithm main function
178 static void
179 ecc200placement (int *array, int NR, int NC)
180 {
181    int r,
182      c,
183      p;
184    // invalidate
185    for (r = 0; r < NR; r++)
186       for (c = 0; c < NC; c++)
187          array[r * NC + c] = 0;
188    // start
189    p = 1;
190    r = 4;
191    c = 0;
192    do
193    {
194       // check corner
195       if (r == NR && !c)
196          ecc200placementcornerA (array, NR, NC, p++);
197       if (r == NR - 2 && !c && NC % 4)
198          ecc200placementcornerB (array, NR, NC, p++);
199       if (r == NR - 2 && !c && (NC % 8) == 4)
200          ecc200placementcornerC (array, NR, NC, p++);
201       if (r == NR + 4 && c == 2 && !(NC % 8))
202          ecc200placementcornerD (array, NR, NC, p++);
203       // up/right
204       do
205       {
206          if (r < NR && c >= 0 && !array[r * NC + c])
207             ecc200placementblock (array, NR, NC, r, c, p++);
208          r -= 2;
209          c += 2;
210       }
211       while (r >= 0 && c < NC);
212       r++;
213       c += 3;
214       // down/left
215       do
216       {
217          if (r >= 0 && c < NC && !array[r * NC + c])
218             ecc200placementblock (array, NR, NC, r, c, p++);
219          r += 2;
220          c -= 2;
221       }
222       while (r < NR && c >= 0);
223       r += 3;
224       c++;
225    }
226    while (r < NR || c < NC);
227    // unfilled corner
228    if (!array[NR * NC - 1])
229       array[NR * NC - 1] = array[NR * NC - NC - 2] = 1;
230 }
231
232 // calculate and append ecc code, and if necessary interleave
233 static void
234 ecc200 (unsigned char *binary, int bytes, int datablock, int rsblock)
235 {
236    int blocks = (bytes + 2) / datablock,
237       b;
238    rs_init_gf (0x12d);
239    rs_init_code (rsblock, 1);
240    for (b = 0; b < blocks; b++)
241    {
242       unsigned char buf[256],
243         ecc[256];
244       int n,
245         p = 0;
246       for (n = b; n < bytes; n += blocks)
247          buf[p++] = binary[n];
248       rs_encode (p, buf, ecc);
249       p = rsblock - 1;          // comes back reversed
250       for (n = b; n < rsblock * blocks; n += blocks)
251          binary[bytes + n] = ecc[p--];
252    }
253 }
254
255 // perform encoding for ecc200, source s len sl, to target t len tl, using optional encoding control string e
256 // return 1 if OK, 0 if failed. Does all necessary padding to tl
257 char
258 ecc200encode (unsigned char *t, int tl, unsigned char *s, int sl, char *encoding, int *lenp)
259 {
260    char enc = 'a';              // start in ASCII encoding mode
261    int tp = 0,
262       sp = 0;
263    if (strlen (encoding) < sl)
264    {
265       fprintf (stderr, "Encoding string too short\n");
266       return 0;
267    }
268    // do the encoding
269    while (sp < sl && tp < tl)
270    {
271       char newenc = enc;        // suggest new encoding
272       if (tl - tp <= 1 && (enc == 'c' || enc == 't') || tl - tp <= 2 && enc == 'x')
273          enc = 'a';             // auto revert to ASCII
274       newenc = tolower (encoding[sp]);
275       switch (newenc)
276       {                         // encode character
277       case 'c':                // C40
278       case 't':                // Text
279       case 'x':                // X12
280          {
281             char out[6],
282               p = 0;
283             const char *e,
284              *s2 = "!\"#$%&'()*+,-./:;<=>?@[\\]_",
285                *s3 = 0;
286             if (newenc == 'c')
287             {
288                e = " 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
289                s3 = "`abcdefghijklmnopqrstuvwxyz{|}~\177";
290             }
291             if (newenc == 't')
292             {
293                e = " 0123456789abcdefghijklmnopqrstuvwxyz";
294                s3 = "`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~\177";
295             }
296             if (newenc == 'x')
297                e = " 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\r*>";
298             do
299             {
300                unsigned char c = s[sp++];
301                char *w;
302                if (c & 0x80)
303                {
304                   if (newenc == 'x')
305                   {
306                      fprintf (stderr, "Cannot encode char 0x%02X in X12\n", c);
307                      return 0;
308                   }
309                   c &= 0x7f;
310                   out[p++] = 1;
311                   out[p++] = 30;
312                }
313                w = strchr (e, c);
314                if (w)
315                   out[p++] = ((w - e) + 3) % 40;
316                else
317                {
318                   if (newenc == 'x')
319                   {
320                      fprintf (stderr, "Cannot encode char 0x%02X in X12\n", c);
321                      return 0;
322                   }
323                   if (c < 32)
324                   {             // shift 1
325                      out[p++] = 0;
326                      out[p++] = c;
327                   } else
328                   {
329                      w = strchr (s2, c);
330                      if (w)
331                      {          // shift 2
332                         out[p++] = 1;
333                         out[p++] = (w - s2);
334                      } else
335                      {
336                         w = strchr (s3, c);
337                         if (w)
338                         {
339                            out[p++] = 2;
340                            out[p++] = (w - s3);
341                         } else
342                         {
343                            fprintf (stderr, "Could not encode 0x%02X, should not happen\n", c);
344                            return 0;
345                         }
346                      }
347                   }
348                }
349                if (p == 2 && tp + 2 == tl && sp == sl)
350                   out[p++] = 0; // shift 1 pad at end
351                while (p >= 3)
352                {
353                   int v = out[0] * 1600 + out[1] * 40 + out[2] + 1;
354                   if (enc != newenc)
355                   {
356                      if (enc == 'c' || enc == 't' || enc == 'x')
357                         t[tp++] = 254;  // escape C40/text/X12
358                      else if (enc == 'x')
359                         t[tp++] = 0x7C; // escape EDIFACT
360                      if (newenc == 'c')
361                         t[tp++] = 230;
362                      if (newenc == 't')
363                         t[tp++] = 239;
364                      if (newenc == 'x')
365                         t[tp++] = 238;
366                      enc = newenc;
367                   }
368                   t[tp++] = (v >> 8);
369                   t[tp++] = (v & 0xFF);
370                   p -= 3;
371                   out[0] = out[3];
372                   out[1] = out[4];
373                   out[2] = out[5];
374                }
375             }
376             while (p && sp < sl);
377          }
378          break;
379       case 'e':                // EDIFACT
380          {
381             unsigned char out[4],
382               p = 0;
383             if (enc != newenc)
384             {                   // can only be from C40/Text/X12
385                t[tp++] = 254;
386                enc = 'a';
387             }
388             while (sp < sl && tolower (encoding[sp]) == 'e' && p < 4)
389                out[p++] = s[sp++];
390             if (p < 4)
391             {
392                out[p++] = 0x1F;
393                enc = 'a';
394             }                   // termination
395             t[tp] = ((s[0] & 0x3F) << 2);
396             t[tp++] |= ((s[1] & 0x30) >> 4);
397             t[tp] = ((s[1] & 0x0F) << 4);
398             if (p == 2)
399                tp++;
400             else
401             {
402                t[tp++] |= ((s[2] & 0x3C) >> 2);
403                t[tp] = ((s[2] & 0x03) << 6);
404                t[tp++] |= (s[3] & 0x3F);
405             }
406          }
407          break;
408       case 'a':                // ASCII
409          if (enc != newenc)
410          {
411             if (enc == 'c' || enc == 't' || enc == 'x')
412                t[tp++] = 254;   // escape C40/text/X12
413             else
414                t[tp++] = 0x7C;  // escape EDIFACT
415          }
416          enc = 'a';
417          if (sl - sp >= 2 && isdigit (s[sp]) && isdigit (s[sp + 1]))
418          {
419             t[tp++] = (s[sp] - '0') * 10 + s[sp + 1] - '0' + 130;
420             sp += 2;
421          } else if (s[sp] > 127)
422          {
423             t[tp++] = 235;
424             t[tp++] = s[sp++] - 127;
425          } else
426             t[tp++] = s[sp++] + 1;
427          break;
428       case 'b':                // Binary
429          {
430             int l = 0;          // how much to encode
431             if (encoding)
432             {
433                int p;
434                for (p = sp; p < sl && tolower (encoding[p]) == 'b'; p++)
435                   l++;
436             }
437             t[tp++] = 231;      // base256
438             if (l < 250)
439                t[tp++] = l;
440             else
441             {
442                t[tp++] = 249 + (l / 250);
443                t[tp++] = (l % 250);
444             }
445             while (l-- && tp < tl)
446             {
447                t[tp] = s[sp++] + (((tp + 1) * 149) % 255) + 1;  // see annex H
448                tp++;
449             }
450             enc = 'a';          // reverse to ASCII at end
451          }
452          break;
453       default:
454          fprintf (stderr, "Unknown encoding %c\n", newenc);
455          return 0;              // failed
456       }
457    }
458    if (lenp)
459       *lenp = tp;
460    if (tp < tl && enc != 'a')
461    {
462       if (enc == 'c' || enc == 'x' || enc == 't')
463          t[tp++] = 254;         // escape X12/C40/Text
464       else
465          t[tp++] = 0x7C;        // escape EDIFACT
466    }
467    if (tp < tl)
468       t[tp++] = 129;            // pad
469    while (tp < tl)
470    {                            // more padding
471       int v = 129 + (((tp + 1) * 149) % 253) + 1;       // see Annex H
472       if (v > 254)
473          v -= 254;
474       t[tp++] = v;
475    }
476    if (tp > tl || sp < sl)
477       return 0;                 // did not fit
478    //for (tp = 0; tp < tl; tp++) fprintf (stderr, "%02X ", t[tp]); fprintf (stderr, "\n");
479    return 1;                    // OK 
480 }
481
482 // Auto encoding format functions
483 static char encchr[] = "ACTXEB";
484
485 enum
486 {
487    E_ASCII,
488    E_C40,
489    E_TEXT,
490    E_X12,
491    E_EDIFACT,
492    E_BINARY,
493    E_MAX
494 };
495
496 unsigned char switchcost[E_MAX][E_MAX] = {
497    0, 1, 1, 1, 1, 2,            // From E_ASCII
498    1, 0, 2, 2, 2, 3,            // From E_C40
499    1, 2, 0, 2, 2, 3,            // From E_TEXT
500    1, 2, 2, 0, 2, 3,            // From E_X12
501    1, 2, 2, 2, 0, 3,            // From E_EDIFACT
502    0, 1, 1, 1, 1, 0,            // From E_BINARY
503 };
504
505 // Creates a encoding list (malloc)
506 // returns encoding string
507 // if lenp not null, target len stored
508 // if error, null returned
509 // if exact specified, then assumes shortcuts applicable for exact fit in target
510 // 1. No unlatch to return to ASCII for last encoded byte after C40 or Text or X12
511 // 2. No unlatch to return to ASCII for last 1 or 2 encoded bytes after EDIFACT
512 // 3. Final C40 or text encoding exactly in last 2 bytes can have a shift 0 to pad to make a tripple
513 // Only use the encoding from an exact request if the len matches the target, otherwise free the result and try again with exact=0
514 static char *
515 encmake (int l, unsigned char *s, int *lenp, char exact)
516 {
517    char *encoding = 0;
518    int p = l;
519    char e;
520    struct
521    {
522       short s;                  // number of bytes of source that can be encoded in a row at this point using this encoding mode
523       short t;                  // number of bytes of target generated encoding from this point to end if already in this encoding mode
524    } enc[MAXBARCODE][E_MAX];
525    memset (&enc, 0, sizeof (enc));
526    if (!l)
527       return "";                // no length
528    if (l > MAXBARCODE)
529       return 0;                 // not valid
530    while (p--)
531    {
532       char b = 0,
533          sub;
534       int sl,
535         tl,
536         bl,
537         t;
538       // consider each encoding from this point
539       // ASCII
540       sl = tl = 1;
541       if (isdigit (s[p]) && p + 1 < l && isdigit (s[p + 1]))
542          sl = 2;                // double digit
543       else if (s[p] & 0x80)
544          tl = 2;                // high shifted
545       bl = 0;
546       if (p + sl < l)
547          for (e = 0; e < E_MAX; e++)
548             if (enc[p + sl][e].t && ((t = enc[p + sl][e].t + switchcost[E_ASCII][e]) < bl || !bl))
549             {
550                bl = t;
551                b = e;
552             }
553       enc[p][E_ASCII].t = tl + bl;
554       enc[p][E_ASCII].s = sl;
555       if (bl && b == E_ASCII)
556          enc[p][b].s += enc[p + sl][b].s;
557       // C40
558       sub = tl = sl = 0;
559       do
560       {
561          unsigned char c = s[p + sl++];
562          if (c & 0x80)
563          {                      // shift + upper
564             sub += 2;
565             c &= 0x7F;
566          }
567          if (c != ' ' && !isdigit (c) && !isupper (c))
568             sub++;              // shift
569          sub++;
570          while (sub >= 3)
571          {
572             sub -= 3;
573             tl += 2;
574          }
575       } while (sub && p + sl < l);
576       if (exact && sub == 2 && p + sl == l)
577       {                         // special case, can encode last block with shift 0 at end (Is this valid when not end of target buffer?)
578          sub = 0;
579          tl += 2;
580       }
581       if (!sub)
582       {                         // can encode C40
583          bl = 0;
584          if (p + sl < l)
585             for (e = 0; e < E_MAX; e++)
586                if (enc[p + sl][e].t && ((t = enc[p + sl][e].t + switchcost[E_C40][e]) < bl || !bl))
587                {
588                   bl = t;
589                   b = e;
590                }
591          if (exact && enc[p + sl][E_ASCII].t == 1 && 1 < bl)
592          {                      // special case, switch to ASCII for last bytes
593             bl = 1;
594             b = E_ASCII;
595          }
596          enc[p][E_C40].t = tl + bl;
597          enc[p][E_C40].s = sl;
598          if (bl && b == E_C40)
599             enc[p][b].s += enc[p + sl][b].s;
600       }
601       // Text
602       sub = tl = sl = 0;
603       do
604       {
605          unsigned char c = s[p + sl++];
606          if (c & 0x80)
607          {                      // shift + upper
608             sub += 2;
609             c &= 0x7F;
610          }
611          if (c != ' ' && !isdigit (c) && !islower (c))
612             sub++;              // shift
613          sub++;
614          while (sub >= 3)
615          {
616             sub -= 3;
617             tl += 2;
618          }
619       } while (sub && p + sl < l);
620       if (exact && sub == 2 && p + sl == l)
621       {                         // special case, can encode last block with shift 0 at end (Is this valid when not end of target buffer?)
622          sub = 0;
623          tl += 2;
624       }
625       if (!sub && sl)
626       {                         // can encode Text
627          bl = 0;
628          if (p + sl < l)
629             for (e = 0; e < E_MAX; e++)
630                if (enc[p + sl][e].t && ((t = enc[p + sl][e].t + switchcost[E_TEXT][e]) < bl || !bl))
631                {
632                   bl = t;
633                   b = e;
634                }
635          if (exact && enc[p + sl][E_ASCII].t == 1 && 1 < bl)
636          {                      // special case, switch to ASCII for last bytes
637             bl = 1;
638             b = E_ASCII;
639          }
640          enc[p][E_TEXT].t = tl + bl;
641          enc[p][E_TEXT].s = sl;
642          if (bl && b == E_TEXT)
643             enc[p][b].s += enc[p + sl][b].s;
644       }
645       // X12
646       sub = tl = sl = 0;
647       do
648       {
649          unsigned char c = s[p + sl++];
650          if (c != 13 && c != '*' && c != '>' && c != ' ' && !isdigit (c) && !isupper (c))
651          {
652             sl = 0;
653             break;
654          }
655          sub++;
656          while (sub >= 3)
657          {
658             sub -= 3;
659             tl += 2;
660          }
661       } while (sub && p + sl < l);
662       if (!sub && sl)
663       {                         // can encode X12
664          bl = 0;
665          if (p + sl < l)
666             for (e = 0; e < E_MAX; e++)
667                if (enc[p + sl][e].t && ((t = enc[p + sl][e].t + switchcost[E_X12][e]) < bl || !bl))
668                {
669                   bl = t;
670                   b = e;
671                }
672          if (exact && enc[p + sl][E_ASCII].t == 1 && 1 < bl)
673          {                      // special case, switch to ASCII for last bytes
674             bl = 1;
675             b = E_ASCII;
676          }
677          enc[p][E_X12].t = tl + bl;
678          enc[p][E_X12].s = sl;
679          if (bl && b == E_X12)
680             enc[p][b].s += enc[p + sl][b].s;
681       }
682       // EDIFACT
683       sl = bl = 0;
684       if (s[p + 0] >= 32 && s[p + 0] <= 94)
685       {                         // can encode 1
686          char bs = 0;
687          if (p + 1 == l && (!bl || bl < 2))
688          {
689             bl = 2;
690             bs = 1;
691          } else
692             for (e = 0; e < E_MAX; e++)
693                if (e != E_EDIFACT && enc[p + 1][e].t && ((t = 2 + enc[p + 1][e].t + switchcost[E_ASCII][e]) < bl || !bl))       // E_ASCII as allowed for unlatch
694                {
695                   bs = 1;
696                   bl = t;
697                   b = e;
698                }
699          if (p + 1 < l && s[p + 1] >= 32 && s[p + 1] <= 94)
700          {                      // can encode 2
701             if (p + 2 == l && (!bl || bl < 2))
702             {
703                bl = 3;
704                bs = 2;
705             } else
706                for (e = 0; e < E_MAX; e++)
707                   if (e != E_EDIFACT && enc[p + 2][e].t && ((t = 3 + enc[p + 2][e].t + switchcost[E_ASCII][e]) < bl || !bl))    // E_ASCII as allowed for unlatch
708                   {
709                      bs = 2;
710                      bl = t;
711                      b = e;
712                   }
713             if (p + 2 < l && s[p + 2] >= 32 && s[p + 2] <= 94)
714             {                   // can encode 3
715                if (p + 3 == l && (!bl || bl < 3))
716                {
717                   bl = 3;
718                   bs = 3;
719                } else
720                   for (e = 0; e < E_MAX; e++)
721                      if (e != E_EDIFACT && enc[p + 3][e].t && ((t = 3 + enc[p + 3][e].t + switchcost[E_ASCII][e]) < bl || !bl)) // E_ASCII as allowed for unlatch
722                      {
723                         bs = 3;
724                         bl = t;
725                         b = e;
726                      }
727                if (p + 4 < l && s[p + 3] >= 32 && s[p + 3] <= 94)
728                {                // can encode 4
729                   if (p + 4 == l && (!bl || bl < 3))
730                   {
731                      bl = 3;
732                      bs = 4;
733                   } else
734                   {
735                      for (e = 0; e < E_MAX; e++)
736                         if (enc[p + 4][e].t && ((t = 3 + enc[p + 4][e].t + switchcost[E_EDIFACT][e]) < bl || !bl))
737                         {
738                            bs = 4;
739                            bl = t;
740                            b = e;
741                         }
742                      if (exact && enc[p + 4][E_ASCII].t && enc[p + 4][E_ASCII].t <= 2 && (t = 3 + enc[p + 4][E_ASCII].t) < bl)
743                      {          // special case, switch to ASCII for last 1 ot two bytes
744                         bs = 4;
745                         bl = t;
746                         b = E_ASCII;
747                      }
748                   }
749                }
750             }
751          }
752          enc[p][E_EDIFACT].t = bl;
753          enc[p][E_EDIFACT].s = bs;
754          if (bl && b == E_EDIFACT)
755             enc[p][b].s += enc[p + bs][b].s;
756       }
757       // Binary
758       bl = 0;
759       for (e = 0; e < E_MAX; e++)
760          if (enc[p + 1][e].t
761              && ((t = enc[p + 1][e].t + switchcost[E_BINARY][e] + ((e == E_BINARY && enc[p + 1][e].t == 249) ? 1 : 0)) < bl || !bl))
762          {
763             bl = t;
764             b = e;
765          }
766       enc[p][E_BINARY].t = 1 + bl;
767       enc[p][E_BINARY].s = 1;
768       if (bl && b == E_BINARY)
769          enc[p][b].s += enc[p + 1][b].s;
770       //fprintf (stderr, "%d:", p); for (e = 0; e < E_MAX; e++) fprintf (stderr, " %c*%d/%d", encchr[e], enc[p][e].s, enc[p][e].t); fprintf (stderr, "\n");
771    }
772    encoding = safemalloc (l + 1);
773    p = 0;
774    {
775       char cur = E_ASCII;       // starts ASCII
776       while (p < l)
777       {
778          int t,
779            m = 0;
780          char b = 0;
781          for (e = 0; e < E_MAX; e++)
782             if (enc[p][e].t && ((t = enc[p][e].t + switchcost[cur][e]) < m || t == m && e == cur || !m))
783             {
784                b = e;
785                m = t;
786             }
787          cur = b;
788          m = enc[p][b].s;
789          if (!p && lenp)
790             *lenp = enc[p][b].t;
791          while (p < l && m--)
792             encoding[p++] = encchr[b];
793       }
794    }
795    encoding[p] = 0;
796    return encoding;
797 }
798
799 // Main encoding function
800 // Returns the grid (malloced) containing the matrix. L corner at 0,0.
801 // Takes suggested size in *Wptr, *Hptr, or 0,0. Fills in actual size.
802 // Takes barcodelen and barcode to be encoded
803 // Note, if *encodingptr is null, then fills with auto picked (malloced) encoding
804 // If lenp not null, then the length of encoded data before any final unlatch or pad is stored
805 // If maxp not null, then the max storage of this size code is stored
806 // If eccp not null, then the number of ecc bytes used in this size is stored
807 // Returns 0 on error (writes to stderr with details).
808 unsigned char *
809 iec16022ecc200 (int *Wptr, int *Hptr, char **encodingptr, int barcodelen, unsigned char *barcode, int *lenp, int *maxp, int *eccp)
810 {
811    unsigned char binary[3000];  // encoded raw data and ecc to place in barcode
812    int W = 0,
813       H = 0;
814    char *encoding = 0;
815    unsigned char *grid = 0;
816    struct ecc200matrix_s *matrix;
817    memset (binary, 0, sizeof (binary));
818    if (encodingptr)
819       encoding = *encodingptr;
820    if (Wptr)
821       W = *Wptr;
822    if (Hptr)
823       H = *Hptr;
824
825    // encoding
826    if (W)
827    {                            // known size
828       for (matrix = ecc200matrix; matrix->W && (matrix->W != W || matrix->H != H); matrix++);
829       if (!matrix->W)
830       {
831          fprintf (stderr, "Invalid size %dx%d\n", W, H);
832          return 0;
833       }
834       if (!encoding)
835       {
836          int len;
837          char *e = encmake (barcodelen, barcode, &len, 1);
838          if (e && len != matrix->bytes)
839          {                      // try not an exact fit
840             free (e);
841             e = encmake (barcodelen, barcode, &len, 0);
842             if (len > matrix->bytes)
843             {
844                fprintf (stderr, "Cannot make barcode fit %dx%d\n", W, H);
845                return 0;
846             }
847          }
848          encoding = e;
849       }
850    } else
851    {                            // find size
852       if (encoding)
853       {                         // find one that fits chosen encoding
854          for (matrix = ecc200matrix; matrix->W; matrix++)
855             if (ecc200encode (binary, matrix->bytes, barcode, barcodelen, encoding, 0))
856                break;
857       } else
858       {
859          int len;
860          char *e;
861          e = encmake (barcodelen, barcode, &len, 1);
862          for (matrix = ecc200matrix; matrix->W && matrix->bytes != len; matrix++);
863          if (e && !matrix->W)
864          {                      // try for non exact fit
865             free (e);
866             e = encmake (barcodelen, barcode, &len, 0);
867             for (matrix = ecc200matrix; matrix->W && matrix->bytes < len; matrix++);
868          }
869          encoding = e;
870       }
871       if (!matrix->W)
872       {
873          fprintf (stderr, "Cannot find suitable size, barcode too long\n");
874          return 0;
875       }
876       W = matrix->W;
877       H = matrix->H;
878    }
879    if (!ecc200encode (binary, matrix->bytes, barcode, barcodelen, encoding, lenp))
880    {
881       fprintf (stderr, "Barcode too long for %dx%d\n", W, H);
882       return 0;
883    }
884    // ecc code
885    ecc200 (binary, matrix->bytes, matrix->datablock, matrix->rsblock);
886    {                            // placement
887       int x,
888         y,
889         NC,
890         NR,
891        *places;
892       NC = W - 2 * (W / matrix->FW);
893       NR = H - 2 * (H / matrix->FH);
894       places = safemalloc (NC * NR * sizeof (int));
895       ecc200placement (places, NR, NC);
896       grid = safemalloc (W * H);
897       memset (grid, 0, W * H);
898       for (y = 0; y < H; y += matrix->FH)
899       {
900          for (x = 0; x < W; x++)
901             grid[y * W + x] = 1;
902          for (x = 0; x < W; x += 2)
903             grid[(y + matrix->FH - 1) * W + x] = 1;
904       }
905       for (x = 0; x < W; x += matrix->FW)
906       {
907          for (y = 0; y < H; y++)
908             grid[y * W + x] = 1;
909          for (y = 0; y < H; y += 2)
910             grid[y * W + x + matrix->FW - 1] = 1;
911       }
912       for (y = 0; y < NR; y++)
913       {
914          for (x = 0; x < NC; x++)
915          {
916             int v = places[(NR - y - 1) * NC + x];
917             //fprintf (stderr, "%4d", v);
918             if (v == 1 || v > 7 && (binary[(v >> 3) - 1] & (1 << (v & 7))))
919                grid[(1 + y + 2 * (y / (matrix->FH - 2))) * W + 1 + x + 2 * (x / (matrix->FW - 2))] = 1;
920          }
921          //fprintf (stderr, "\n");
922       }
923       free (places);
924    }
925    if (Wptr)
926       *Wptr = W;
927    if (Hptr)
928       *Hptr = H;
929    if (encodingptr)
930       *encodingptr = encoding;
931    if (maxp)
932       *maxp = matrix->bytes;
933    if (eccp)
934       *eccp = (matrix->bytes + 2) / matrix->datablock * matrix->rsblock;
935    return grid;
936 }