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