Import Debian changes 0.2.4-1.2
[iec16022] / iec16022.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 "image.h"
34 #include "iec16022ecc200.h"
35 #include "config.h"
36
37  // simple checked response malloc
38 void *safemalloc(int n)
39 {
40         void *p = malloc(n);
41         if (!p) {
42                 fprintf(stderr, "Malloc(%d) failed\n", n);
43                 exit(1);
44         }
45         return p;
46 }
47
48 // hex dump - bottom left pixel first
49 void dumphex(unsigned char *grid, int W, int H, unsigned char p)
50 {
51         int c = 0, y;
52         for (y = 0; y < H; y++) {
53                 int v = 0, x, b = 128;
54                 for (x = 0; x < W; x++) {
55                         if (grid[y * W + x])
56                                 v |= b;
57                         b >>= 1;
58                         if (!b) {
59                                 printf("%02X", v ^ p);
60                                 v = 0;
61                                 b = 128;
62                                 c++;
63                         }
64                 }
65                 if (b != 128) {
66                         printf("%02X", v ^ p);
67                         c++;
68                 }
69                 printf(" ");
70                 c++;
71                 if (c >= 80) {
72                         printf("\n");
73                         c = 0;
74                 }
75         }
76         if (c)
77                 printf("\n");
78 }
79
80 int main(int argc, const char *argv[])
81 {
82         char c;
83         int W = 0, H = 0;
84         int ecc = 0;
85         int barcodelen = 0;
86         char *encoding = 0;
87         char *outfile = 0;
88         char *infile = 0;
89         char *barcode = 0;
90         char *format = "Text";
91         char *size = 0;
92         char *eccstr = 0;
93         int len = 0, maxlen = 0, ecclen = 0;
94         unsigned char *grid = 0;
95         poptContext optCon;     // context for parsing command-line options
96         const struct poptOption optionsTable[] = {
97                 {
98                  "size", 's', POPT_ARG_STRING, &size, 0, "Size", "WxH"},
99                 {
100                  "barcode", 'c', POPT_ARG_STRING, &barcode, 0, "Barcode",
101                  "text"},
102                 {
103                  "ecc", 0, POPT_ARG_STRING, &eccstr, 0, "ECC",
104                  "000/050/080/100/140/200"},
105                 {
106                  "infile", 'i', POPT_ARG_STRING, &infile, 0, "Barcode file",
107                  "filename"},
108                 {
109                  "outfile", 'o', POPT_ARG_STRING, &outfile, 0,
110                  "Output filename",
111                  "filename"},
112                 {
113                  "encoding", 'e', POPT_ARG_STRING, &encoding, 0,
114                  "Encoding template",
115                  "[CTXEAB]* for ecc200 or 11/27/41/37/128/256"},
116                 {
117                  "format", 'f', POPT_ARGFLAG_SHOW_DEFAULT | POPT_ARG_STRING,
118                  &format, 0,
119                  "Output format", "Text/EPS/PNG/Bin/Hex/Stamp"},
120                 POPT_AUTOHELP {
121                                NULL, 0, 0, NULL, 0}
122         };
123         optCon = poptGetContext(NULL, argc, argv, optionsTable, 0);
124         poptSetOtherOptionHelp(optCon, "[barcode]");
125         if ((c = poptGetNextOpt(optCon)) < -1) {
126                 /* an error occurred during option processing */
127                 fprintf(stderr, "%s: %s\n", poptBadOption(optCon,
128                                                           POPT_BADOPTION_NOALIAS),
129                         poptStrerror(c));
130                 return 1;
131         }
132
133         if (poptPeekArg(optCon) && !barcode && !infile)
134                 barcode = (char *)poptGetArg(optCon);
135         if (poptPeekArg(optCon) || !barcode && !infile || barcode && infile) {
136                 fprintf(stderr, "Version: %s\n", PACKAGE_VERSION);
137                 poptPrintUsage(optCon, stderr, 0);
138                 return -1;
139         }
140         if (outfile && !freopen(outfile, "w", stdout)) {
141                 perror(outfile);
142                 return 1;
143         }
144
145         if (infile) {           // read from file
146                 FILE *f = fopen(infile, "rb");
147                 barcode = safemalloc(4001);
148                 if (!f) {
149                         perror(infile);
150                         return 1;
151                 }
152                 barcodelen = fread(barcode, 1, 4000, f);
153                 if (barcodelen < 0) {
154                         perror(infile);
155                         return 1;
156                 }
157                 barcode[barcodelen] = 0;        // null terminate anyway
158                 close(f);
159         } else
160                 barcodelen = strlen(barcode);
161         // check parameters
162         if (size) {
163                 char *x = strchr(size, 'x');
164                 W = atoi(size);
165                 if (x)
166                         H = atoi(x + 1);
167                 if (!H)
168                         W = H;
169         }
170         if (eccstr)
171                 ecc = atoi(eccstr);
172         if (W & 1) {            // odd size
173                 if (W != H || W < 9 || W > 49) {
174                         fprintf(stderr, "Invalid size %dx%d\n", W, H);
175                         return 1;
176                 }
177                 if (!eccstr) {
178                         if (W >= 17)
179                                 ecc = 140;
180                         else if (W >= 13)
181                                 ecc = 100;
182                         else if (W >= 11)
183                                 ecc = 80;
184                         else
185                                 ecc = 0;
186                 }
187                 if (ecc && ecc != 50 && ecc != 80 && ecc != 100 && ecc != 140 ||
188                     ecc == 50 && W < 11 || ecc == 80 && W < 13 || ecc == 100
189                     && W < 13 || ecc == 140 && W < 17) {
190                         fprintf(stderr, "ECC%03d invalid for %dx%d\n", ecc, W,
191                                 H);
192                         return 1;
193                 }
194
195         } else if (W) {         // even size
196                 if (W < H) {
197                         int t = W;
198                         W = H;
199                         H = t;
200                 }
201                 if (!eccstr)
202                         ecc = 200;
203                 if (ecc != 200) {
204                         fprintf(stderr, "ECC%03d invalid for %dx%d\n", ecc, W,
205                                 H);
206                         return 1;
207                 }
208         }
209
210         else {                  // auto size
211                 if (!eccstr)
212                         // default is even sizes only unless explicit ecc set to force odd
213                         // sizes
214                         ecc = 200;
215         }
216
217         if (tolower(*format) == 's') {  // special stamp format checks & defaults
218                 if (!W)
219                         W = H = 32;
220                 if (ecc != 200 || W != 32 || H != 32)
221                         fprintf(stderr, "Stamps must be 32x32\n");
222                 if (encoding)
223                         fprintf(stderr, "Stamps should use auto encoding\n");
224                 else {
225                         int n;
226                         for (n = 0; n < barcodelen && (barcode[n] == ' ' ||
227                                                        isdigit(barcode[n])
228                                                        || isupper(barcode[n]));
229                              n++) ;
230                         if (n < barcodelen)
231                                 fprintf(stderr,
232                                         "Has invalid characters for a stamp\n");
233                         else {
234                                 // Generate simplistic encoding rules as used by the windows app
235                                 // TBA - does not always match the windows app...
236                                 n = 0;
237                                 encoding = safemalloc(barcodelen + 1);
238                                 while (n < barcodelen) {
239                                         // ASCII
240                                         while (1) {
241                                                 if (n == barcodelen
242                                                     || n + 3 <= barcodelen
243                                                     && (!isdigit(barcode[n])
244                                                         ||
245                                                         !isdigit(barcode
246                                                                  [n + 1])))
247                                                         break;
248                                                 encoding[n++] = 'A';
249                                                 if (n < barcodelen
250                                                     && isdigit(barcode[n - 1])
251                                                     && isdigit(barcode[n]))
252                                                         encoding[n++] = 'A';
253                                         }
254                                         // C40
255                                         while (1) {
256                                                 int r = 0;
257                                                 while (n + r < barcodelen
258                                                        &&
259                                                        isdigit(barcode[n + r]))
260                                                         r++;
261                                                 if (n + 3 > barcodelen
262                                                     || r >= 6)
263                                                         break;
264                                                 encoding[n++] = 'C';
265                                                 encoding[n++] = 'C';
266                                                 encoding[n++] = 'C';
267                                         }
268                                 }
269                                 encoding[n] = 0;
270                                 //fprintf (stderr, "%s\n%s\n", barcode, encoding);
271                         }
272                 }
273         }
274         // processing stamps
275         if ((W & 1) || ecc < 200) {     // odd sizes
276                 fprintf(stderr, "Not done odd sizes yet, sorry\n");
277         } else {                // even sizes
278                 grid =
279                     iec16022ecc200(&W, &H, &encoding, barcodelen, barcode, &len,
280                                    &maxlen, &ecclen);
281         }
282
283         // output
284         if (!grid || !W) {
285                 fprintf(stderr, "No barcode produced\n");
286                 return 1;
287         }
288         switch (tolower(*format)) {
289         case 'i':               // info
290                 printf("Size    : %dx%d\n", W, H);
291                 printf("Encoded : %d of %d bytes with %d bytes of ecc\n", len,
292                        maxlen, ecclen);
293                 printf("Barcode : %s\n", barcode);
294                 printf("Encoding: %s\n", encoding);
295                 break;
296         case 'h':               // hex
297                 dumphex(grid, W, H, 0);
298                 break;
299         case 'b':               // bin
300                 {
301                         int y;
302                         for (y = 0; y < H; y++) {
303                                 int v = 0, x, b = 128;
304                                 for (x = 0; x < W; x++) {
305                                         if (grid[y * W + x])
306                                                 v |= b;
307                                         b >>= 1;
308                                         if (!b) {
309                                                 putchar(v);
310                                                 v = 0;
311                                                 b = 128;
312                                         }
313                                 }
314                                 if (b != 128)
315                                         putchar(v);
316                         }
317                 }
318                 break;
319         case 't':               // text
320                 {
321                         int y;
322                         for (y = H - 1; y >= 0; y--) {
323                                 int x;
324                                 for (x = 0; x < W; x++)
325                                         printf("%c",
326                                                grid[W * y + x] ? '*' : ' ');
327                                 printf("\n");
328                         }
329                 }
330                 break;
331         case 'e':               // EPS
332                 printf("%%!PS-Adobe-3.0 EPSF-3.0\n"
333                        "%%%%Creator: IEC16022 barcode/stamp generator\n"
334                        "%%%%BarcodeData: %s\n" "%%%%BarcodeSize: %dx%d\n"
335                        "%%%%BarcodeFormat: ECC200\n"
336                        "%%%%DocumentData: Clean7Bit\n" "%%%%LanguageLevel: 1\n"
337                        "%%%%Pages: 1\n" "%%%%BoundingBox: 0 0 %d %d\n"
338                        "%%%%EndComments\n" "%%%%Page: 1 1\n"
339                        "%d %d 1[1 0 0 1 -1 -1]{<\n", barcode, W, H, W + 2,
340                        H + 2, W, H);
341                 dumphex(grid, W, H, 0xFF);
342                 printf(">}image\n");
343                 break;
344         case 's':               // Stamp
345                 {
346                         char temp[74], c;
347                         time_t now;
348                         struct tm t = {
349                                 0
350                         };
351                         int v;
352                         if (barcodelen < 74) {
353                                 fprintf(stderr,
354                                         "Does not look like a stamp barcode\n");
355                                 return 1;
356                         }
357                         memcpy(temp, barcode, 74);
358                         c = temp[5];
359                         temp[56] = 0;
360                         t.tm_year = atoi(temp + 54) + 100;
361                         t.tm_mday = 1;
362                         now = mktime(&t);
363                         temp[54] = 0;
364                         now += 86400 * (atoi(temp + 51) - 1);
365                         t = *gmtime(&now);
366                         temp[46] = 0;
367                         v = atoi(temp + 36);
368                         printf("%%!PS-Adobe-3.0 EPSF-3.0\n"
369                                "%%%%Creator: IEC16022 barcode/stamp generator\n"
370                                "%%%%BarcodeData: %s\n" "%%%%BarcodeSize: %dx%d\n" "%%%%DocumentData: Clean7Bit\n" "%%%%LanguageLevel: 1\n" "%%%%Pages: 1\n" "%%%%BoundingBox: 0 0 190 80\n" "%%%%EndComments\n" "%%%%Page: 1 1\n" "10 dict begin/f{findfont exch scalefont \
371                                  setfont}bind def/rm/rmoveto load def/m/moveto load \
372                                  def/rl/rlineto load def\n" "/l/lineto load def/cp/closepath load def/c{dup stringwidth \
373                                  pop -2 div 0 rmoveto show}bind def\n" "gsave 72 25.4 div dup scale 0 0 m 67 0 rl 0 28 rl -67 0 rl \
374                                  cp clip 1 setgray fill 0 setgray 0.5 0 translate 0.3 \
375                                  setlinewidth\n" "32 32 1[2 0 0 2 0 -11]{<\n", barcode, W, H);
376                         dumphex(grid, W, H, 0xFF);
377                         printf(">}image\n"
378                                "3.25/Helvetica-Bold f 8 25.3 m(\\243%d.%02d)c\n"
379                                "2.6/Helvetica f 8 22.3 m(%.4s %.4s)c\n"
380                                "1.5/Helvetica f 8 3.3 m(POST BY)c\n"
381                                "3.3/Helvetica f 8 0.25 m(%02d.%02d.%02d)c\n",
382                                v / 100, v % 100, temp + 6, temp + 10, t.tm_mday,
383                                t.tm_mon + 1, t.tm_year % 100);
384                         if (c == '1' || c == '2' || c == 'A' || c == 'S') {
385                                 if (c == '2')
386                                         printf
387                                             ("42 0 m 10 0 rl 0 28 rl -10 0 rl cp 57 0 m 5 0 rl 0 \
388                                            28 rl -5 0 rl cp");
389                                 else
390                                         printf
391                                             ("42 0 m 5 0 rl 0 28 rl -5 0 rl cp 52 0 m 10 0 rl 0 \
392                                            28 rl -10 0 rl cp");
393                                 printf
394                                     (" 21 0 m 16 0 rl 0 28 rl -16 0 rl cp fill\n"
395                                      "21.3 0.3 m 15.4 0 rl 0 13 rl -15.4 0 rl cp 1 setgray \
396                                         fill gsave 21.3 0.3 15.4 27.4 rectclip newpath\n");
397                                 switch (c) {
398                                 case '1':
399                                         printf
400                                             ("27/Helvetica-Bold f 27 8.7 m(1)show grestore 0 setgray \
401                                    1.5/Helvetica-Bold f 22 3.3 m(POSTAGE PAID GB)show \
402                                    1.7/Helvetica f 29 1.5 m(DumbStamp.co.uk)c\n");
403                                         break;
404                                 case '2':
405                                         printf
406                                             ("21/Helvetica-Bold f 23.5 13 m(2)1.25 1 scale show grestore \
407                                    0 setgray 1.5/Helvetica-Bold f 22 3.3 \
408                                    m(POSTAGE PAID GB)show 1.7/Helvetica f 29 1.5 \
409                                    m(DumbStamp.co.uk)c\n");
410                                         break;
411                                 case 'A':
412                                         printf
413                                             ("16/Helvetica-Bold f 29 14.75 m 1.1 1 scale(A)c grestore 0 \
414                                    setgray 1.5/Helvetica-Bold f 22 3.3 m(POSTAGE PAID GB)show \
415                                    1.7/Helvetica f 22 1.5 m(Par Avion)show\n");
416                                         break;
417                                 case 'S':
418                                         printf
419                                             ("10/Helvetica-Bold f 29 17 m(SU)c grestore 0 setgray \
420                                            1.5/Helvetica-Bold f 22 1.5 m(POSTAGE PAID GB)show\n");
421                                         break;
422                                 }
423                                 printf
424                                     ("2.3/Helvetica-Bold f 29 10 m(LOYAL MAIL)c\n");
425                         } else if (c == 'P') {  // Standard Parcels
426                                 printf("21 0 m 41 0 rl 0 28 rl -41 0 rl cp fill\n" "37.7 0.3 m 24 0 rl 0 27.4 rl -24 0 rl cp 1 setgray fill \
427                                         gsave 21.3 0.3 16.4 27.4 rectclip newpath\n" "22.5/Helvetica-Bold f 37.75 -1.25 m 90 rotate(SP)show \
428                                         grestore 0 setgray\n"
429                                        "3.5/Helvetica-Bold f 49.7 21.5 m(LOYAL MAIL)c\n" "2.3/Helvetica-Bold f 49.7 7 m(POSTAGE PAID GB)c\n" "2.6/Helveica f 49.7 4.25 m(DumbStamp.co.uk)c\n");
430                         } else if (c == '3')
431                                 printf("21.15 0.15 40.7 27.7 rectstroke\n"
432                                        "21 0 m 41 0 rl 0 5 rl -41 0 rl cp fill\n"
433                                        "0 1 2{0 1 18{dup 1.525 mul 22.9 add 24 3 index 1.525 mul \
434                                         add 3 -1 roll 9 add 29 div 0 360 arc fill}for pop}for\n" "50.5 23.07 m 11.5 0 rl 0 5 rl -11.5 0 rl cp fill\n"
435                                        "5.85/Helvetica f 23.7 15.6 m(Loyal Mail)show\n" "4.75/Helvetica-Bold f 24 11 m(special)show 4.9/Helvetica \
436                                         f(delivery)show\n" "gsave 1 setgray 3.2/Helvetica-Bold f 24 1.6 \
437                                         m(next day)show 26 10.15 m 2 0 rl stroke grestore\n" "21.15 9.9 m 53.8 9.9 l stroke 53.8 9.9 0.4 0 360 \
438                                         arc fill\n");
439                         printf("end grestore\n");
440                 }
441                 break;
442         case 'p':               // png
443                 {
444                         int x, y;
445                         Image *i = ImageNew(W + 2, H + 2, 2);
446                         i->Colour[0] = 0xFFFFFF;
447                         i->Colour[1] = 0;
448                         for (y = 0; y < H; y++)
449                                 for (x = 0; x < W; x++)
450                                         if (grid[y * W + x])
451                                                 ImagePixel(i, x + 1, H - y) = 1;
452                         ImageWritePNG(i, fileno(stdout), 0, -1, barcode);
453                         ImageFree(i);
454                 }
455                 break;
456         default:
457                 fprintf(stderr, "Unknown output format %s\n", format);
458                 break;
459         }
460         return 0;
461 }