File: codablock.c

package info (click to toggle)
zxing-cpp 3.0.0%2Bds-1~exp2
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 30,204 kB
  • sloc: ansic: 69,384; cpp: 34,587; php: 2,790; python: 199; makefile: 30; sh: 3
file content (898 lines) | stat: -rw-r--r-- 36,560 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
/* codablock.c - Handles Codablock-F */
/*
    libzint - the open source barcode library
    Copyright (C) 2016-2025 Harald Oehlmann

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in the
       documentation and/or other materials provided with the distribution.
    3. Neither the name of the project nor the names of its contributors
       may be used to endorse or promote products derived from this software
       without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
    FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
    DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
    OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
    OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    SUCH DAMAGE.
 */
/* SPDX-License-Identifier: BSD-3-Clause */

#include <assert.h>
#include <math.h>
#include <stdio.h>
#include "common.h"
#include "code128.h"

#define uchar unsigned char

/* FTab C128 flags - may be added */
#define CodeA    1
#define CodeB    2
#define CodeC    4
#define CEnd     8
#define CShift   16
#define CFill    32
#define CodeFNC1 64
#define CodeFNC4 128
#define ZTNum    (CodeA | CodeB | CodeC)
#define ZTFNC1   (CodeA | CodeB | CodeC | CodeFNC1)

/* ASCII-Extension for Codablock-F */
#define aFNC1  ((uchar) 128)
#define aFNC2  ((uchar) 129)
#define aFNC3  ((uchar) 130)
#define aFNC4  ((uchar) 131)
#define aCodeA ((uchar) 132)
#define aCodeB ((uchar) 133)
#define aCodeC ((uchar) 134)
#define aShift ((uchar) 135)

/* Code F Analysing-Chart */
typedef struct sCharacterSetTable {
    int CharacterSet; /* Still possible character sets for actual*/
    int AFollowing;   /* Still following Characters in Charset A */
    int BFollowing;   /* Still following Characters in Charset B */
    int CFollowing;   /* Still following Characters in Charset C */
} CharacterSetTable;

/* Find the possible Code-128 Character sets for a character
 * The result is an OR of CodeA, CodeB, CodeC, CodeFNC1, CodeFNC4 depending on the
 * possible Code 128 character sets.
 */
static int GetPossibleCharacterSet(const unsigned char C, const int prevNotFNC4) {
    if (C <= '\x1f') /* Control chars */
        return CodeA;
    if (z_isdigit(C) && prevNotFNC4)
        return ZTNum; /* ZTNum = CodeA | CodeB | CodeC */
    if (C == aFNC1) /* FNC1s (GS1) not used */
        return ZTFNC1; /* ZTFNC1 = CodeA | CodeB | CodeC | CodeFNC1 */ /* Not reached */
    if (C == aFNC4)
        return (CodeA | CodeB | CodeFNC4);
    if (C >= '\x60' && C <= '\x7f') /* 60 to 127 */
        return CodeB;
    return CodeA | CodeB;
}

/* Create a Table with the following information for each Data character:
 *  int CharacterSet            is an OR of CodeA, CodeB, CodeC, CodeFNC1, CodeFNC4,
 *                              depending on which character set is applicable.
 *                              (Result of GetPossibleCharacterSet)
 *  int AFollowing, BFollowing  The number of source characters you still may encode in this character set.
 *  int CFollowing              The number of characters encodable in CodeC if we start here.
 */
static void CreateCharacterSetTable(CharacterSetTable T[], const unsigned char *data, const int dataLength) {
    int charCur;
    int runChar;
    int prevNotFNC4;

    /* Treat the Data backwards */
    charCur = dataLength - 1;
    prevNotFNC4 = charCur > 0 ? data[charCur - 1] != aFNC4 : 1;
    T[charCur].CharacterSet = GetPossibleCharacterSet(data[charCur], prevNotFNC4);
    T[charCur].AFollowing = T[charCur].CharacterSet & CodeA ? 1 : 0;
    T[charCur].BFollowing = T[charCur].CharacterSet & CodeB ? 1 : 0;

    for (charCur--; charCur >= 0; charCur--) {
        prevNotFNC4 = charCur > 0 ? data[charCur - 1] != aFNC4 : 1;
        T[charCur].CharacterSet = GetPossibleCharacterSet(data[charCur], prevNotFNC4);
        T[charCur].AFollowing = T[charCur].CharacterSet & CodeA ? T[charCur + 1].AFollowing + 1 : 0;
        T[charCur].BFollowing = T[charCur].CharacterSet & CodeB ? T[charCur + 1].BFollowing + 1 : 0;
    }
    /* Find the CodeC-chains */
    for (charCur = 0; charCur < dataLength; charCur++) {
        T[charCur].CFollowing = 0;
        if (T[charCur].CharacterSet & CodeC) {
            /* CodeC possible */
            runChar = charCur;
            do {
                /* Whether this is FNC1, whether next is */
                /* numeric */
                if (T[runChar].CharacterSet == ZTFNC1) /* FNC1s (GS1) not used */
                    T[charCur].CFollowing++; /* Not reached */
                else {
                    if (++runChar >= dataLength)
                        break;
                    /* Only a Number may follow */
                    if (T[runChar].CharacterSet == ZTNum)
                        T[charCur].CFollowing += 2;
                    else
                        break;
                }
                ++runChar;
            } while (runChar < dataLength);
        }
    }
}

/* Find the amount of numerical characters in pairs which will fit in
 * one bundle into the line (up to here). This is calculated online because
 * it depends on the space in the line.
 */
static int RemainingDigits(const CharacterSetTable T[], const int charCur, int emptyColumns) {
    int digitCount = 0; /* Numerical digits fitting in the line */
    int runChar = charCur;
    while (emptyColumns > 0 && runChar < charCur + T[charCur].CFollowing) {
        if (T[runChar].CharacterSet != ZTFNC1) {
            /* NOT FNC1 */
            digitCount += 2;
            runChar++;
        }
        runChar++;
        emptyColumns--;
    }
    return digitCount;
}

/* Find the Character distribution at a given column count.
 * If too many rows (>44) are requested the columns are extended.
 * Parameters :
 *  T       Pointer on the Characters which fit in the row
 *          If a different count is calculated it is corrected
 *          in the callers workspace.
 *  pFillings   Output of filling characters
 *  pSet        Output of the character sets used, allocated by me.
 *  Return value    Resulting row count
 */
static int Columns2Rows(const CharacterSetTable T[], const int dataLength, int *pRows, int *pUseColumns, int *pSet,
                        int *pFillings, const int debug) {
    int useColumns;   /* Usable Characters per line */
    int fillings = 0; /* Number of filling characters */
    int rowsCur;
    int runChar;
    int emptyColumns;    /* Number of codes still empty in line. */
    int emptyColumns2;   /* Alternative emptyColumns to compare */
    int CPaires;         /* Number of digit pairs which may fit in the line */
    int characterSetCur; /* Current Character Set */
    int isFNC4;          /* Set if current character FNC4 */

    useColumns = *pUseColumns;

    /* >>> Loop until rowsCur <= 44 */
    do {
        int charCur = 0;
        memset(pSet, 0, sizeof(int) * dataLength);
        rowsCur = 0;

        /* >>> Line Loop */
        do {
            /* >> Start Character */
            emptyColumns = useColumns; /* Remaining space in line */

            /* >>Choose in Set A or B */
            /* (C is changed as an option later on) */

            pSet[charCur] = characterSetCur = (T[charCur].AFollowing > T[charCur].BFollowing) ? CodeA : CodeB;

            /* >> Test on Numeric Mode C */
            CPaires = RemainingDigits(T, charCur, emptyColumns);
            if (CPaires >= 4) {
                /* 4 Digits in Numeric compression ->OK */
                /* > May an odd start find more ? */
                /* Skip leading <FNC1>'s */
                /* Typical structure : <FNC1><FNC1>12... */
                /* Test if numeric after one isn't better.*/
                runChar = charCur;
                emptyColumns2 = emptyColumns;
                while (T[runChar].CharacterSet == ZTFNC1) { /* FNC1s (GS1) not used */
                    ++runChar; /* Not reached */
                    --emptyColumns2;
                }
                if (CPaires >= RemainingDigits(T, runChar + 1, emptyColumns2 - 1)) {
                    /* Start odd is not better */
                    /* We start in C */
                    pSet[charCur] = characterSetCur = CodeC;
                    /* Increment charCur */
                    if (T[charCur].CharacterSet != ZTFNC1)
                        ++charCur; /* 2 Num.Digits */
                }
            }
            ++charCur;
            --emptyColumns;

            /* >> Following characters */
            while (emptyColumns > 0 && charCur < dataLength) {
                isFNC4 = T[charCur].CharacterSet & CodeFNC4;
                switch (characterSetCur) {
                case CodeA:
                case CodeB:
                    /* >> Check switching to CodeC */
                    /* Switch if :
                     *  - Character not FNC1
                     *  - 4 real Digits will fit in line
                     *  - an odd Start will not be better
                     */
                    if (T[charCur].CharacterSet == ZTNum
                            && (CPaires = RemainingDigits(T, charCur, emptyColumns - 1)) >= 4
                            && CPaires > RemainingDigits(T, charCur + 1, emptyColumns - 2)) {
                        /* > Change to C */
                        pSet[charCur] = characterSetCur = CodeC;
                        charCur += 2; /* 2 Digit */
                        emptyColumns -= 2; /* <SwitchC>12 */
                    } else if (characterSetCur == CodeA) {
                        if (T[charCur].AFollowing == 0 || (isFNC4 && T[charCur].AFollowing == 1)) {
                            /* Must change to B */
                            if (emptyColumns == 1 || (isFNC4 && emptyColumns == 2)) {
                                /* Can't switch: */
                                pSet[charCur - 1] |= CEnd + CFill;
                                emptyColumns = 0;
                            } else {
                                /* <Shift> or <switchB>? */
                                if (T[charCur].BFollowing == 1 || (isFNC4 && T[charCur].BFollowing == 2)) {
                                    /* Note using order "FNC4 shift char" (same as CODE128) not "shift FNC4 char"
                                       as given in Table B.1 and Table B.2 */
                                    if (isFNC4) { /* So skip FNC4 and shift value instead */
                                        --emptyColumns;
                                        ++charCur;
                                        assert(charCur < dataLength); /* FNC4s always followed by char */
                                    }
                                    pSet[charCur] |= CShift;
                                } else {
                                    pSet[charCur] |= CodeB;
                                    characterSetCur = CodeB;
                                }
                                emptyColumns -= 2;
                                ++charCur;
                            }
                        } else if (isFNC4 && emptyColumns == 1) {
                            /* Can't fit extended ASCII on same line */
                            pSet[charCur - 1] |= CEnd + CFill;
                            emptyColumns = 0;
                        } else {
                            --emptyColumns;
                            ++charCur;
                        }
                    } else { /* Last possibility : CodeB */
                        if (T[charCur].BFollowing == 0 || (isFNC4 && T[charCur].BFollowing == 1)) {
                            /* Must change to A */
                            if (emptyColumns == 1 || (isFNC4 && emptyColumns == 2)) {
                                /* Can't switch: */
                                pSet[charCur - 1] |= CEnd + CFill;
                                emptyColumns = 0;
                            } else {
                                /* <Shift> or <switchA>? */
                                if (T[charCur].AFollowing == 1 || (isFNC4 && T[charCur].AFollowing == 2)) {
                                    /* Note using order "FNC4 shift char" (same as CODE128) not "shift FNC4 char"
                                       as given in Table B.1 and Table B.2 */
                                    if (isFNC4) { /* So skip FNC4 and shift value instead */
                                        --emptyColumns;
                                        ++charCur;
                                        assert(charCur < dataLength); /* FNC4s always followed by char */
                                    }
                                    pSet[charCur] |= CShift;
                                } else {
                                    pSet[charCur] |= CodeA;
                                    characterSetCur = CodeA;
                                }
                                emptyColumns -= 2;
                                ++charCur;
                            }
                        } else if (isFNC4 && emptyColumns == 1) {
                            /* Can't fit extended ASCII on same line */
                            pSet[charCur - 1] |= CEnd + CFill;
                            emptyColumns = 0;
                        } else {
                            --emptyColumns;
                            ++charCur;
                        }
                    }
                    break;
                case CodeC:
                    if (T[charCur].CFollowing > 0) {
                        charCur += (T[charCur].CharacterSet == ZTFNC1) ? 1 : 2;
                        emptyColumns--;
                    } else {
                        /* Must change to A or B */
                        if (emptyColumns == 1 || (isFNC4 && emptyColumns == 2)) {
                            /* Can't switch: */
                            pSet[charCur - 1] |= CEnd + CFill;
                            emptyColumns = 0;
                        } else {
                            /*<SwitchA> or <switchA>?*/
                            characterSetCur = pSet[charCur]
                                            = (T[charCur].AFollowing > T[charCur].BFollowing) ? CodeA : CodeB;
                            emptyColumns -= 2;
                            ++charCur;
                        }
                    }
                    break;
                } /* switch */
            } /* while */

            /* > End of Codeline */
            pSet[charCur - 1] |= CEnd;
            ++rowsCur;
        } while (charCur < dataLength); /* <= Data.Len-1 */

        /* Allow for check characters K1, K2 */
        switch (emptyColumns) {
        case 1:
            pSet[charCur - 1] |= CFill;
            /* fall through */
        case 0:
            ++rowsCur;
            fillings = useColumns - 2 + emptyColumns;
            break;
        case 2:
            fillings = 0;
            break;
        default:
            pSet[charCur - 1] |= CFill;
            fillings = emptyColumns - 2;
            break;
        }

        if (rowsCur > 44) {
            ++useColumns;
            if (useColumns > 62) {
                return ZINT_ERROR_TOO_LONG;
            }
        } else if (rowsCur == 1) {
            rowsCur = 2;
            fillings += useColumns;
        }
    } while (rowsCur > 44);
    if (debug) {
        printf("  -> out: rowsCur <%d>, useColumns <%d>, fillings <%d>\n", rowsCur, useColumns, fillings);
    }
    *pUseColumns = useColumns;
    *pRows = rowsCur;
    *pFillings = fillings;
    return 0;
}

/* Find columns if row count is given.
 */
static int Rows2Columns(const CharacterSetTable T[], const int dataLength, int *pRows, int *pUseColumns, int *pSet,
                        int *pFillings, const int debug) {
    int rowsCur;
    int rowsRequested;    /* Number of requested rows */
    int columnsRequested; /* Number of requested columns (if any) */
    int fillings;
    int useColumns;
    int testColumns; /* To enter into Width2Rows */
    int testListSize = 0;
    int pTestList[62 + 1];
    int *pBackupSet = (int *) z_alloca(sizeof(int) * dataLength);

    rowsRequested = *pRows;
    columnsRequested = *pUseColumns >= 4 ? *pUseColumns : 0;

    if (debug) {
        printf("Optimizer : Searching <%d> rows\n", rowsRequested);
    }

    if (columnsRequested) {
        testColumns = columnsRequested;
    } else {
        /* First guess */
        testColumns = dataLength / rowsRequested;
        if (testColumns > 62)
            testColumns = 62;
        else if (testColumns < 4)
            testColumns = 4;
    }

    for (;;) {
        int errorCur;
        pTestList[testListSize] = testColumns;
        testListSize++;
        useColumns = testColumns; /* Make a copy because it may be modified */
        errorCur = Columns2Rows(T, dataLength, &rowsCur, &useColumns, pSet, &fillings, debug);
        if (errorCur != 0)
            return errorCur;
        if (rowsCur <= rowsRequested) {
            /* Less or exactly line number found */
            /* check if column count below already tested or at smallest/requested */
            int fInTestList = (rowsCur == 2 || testColumns == 4 || testColumns == columnsRequested);
            int posCur;
            for (posCur = 0; posCur < testListSize && !fInTestList; posCur++) {
                if (pTestList[posCur] == testColumns - 1)
                    fInTestList = 1;
            }
            if (fInTestList) {
                /* >> Smaller Width already tested
                 */
                if (rowsCur < rowsRequested) {
                    fillings += useColumns * (rowsRequested - rowsCur);
                    rowsCur = rowsRequested;
                }
                /* Exit with actual */
                *pFillings = fillings;
                *pRows = rowsCur;
                *pUseColumns = useColumns;
                return 0;
            }
            /* > Test more rows (shorter CDB) */
            memcpy(pBackupSet, pSet, sizeof(int) * dataLength);
            --testColumns;
        } else {
            /* > Too many rows */
            /* > Test less rows (longer code) */
            memcpy(pBackupSet, pSet, sizeof(int) * dataLength);
            if (++testColumns > 62) {
                return ZINT_ERROR_TOO_LONG;
            }
        }
    }
}

/* Print a character in character set A
 */
static void A2C128_A(uchar **ppOutPos, const uchar c) {
    uchar *pOutPos = *ppOutPos;
    switch (c) {
    case aCodeB: *pOutPos = 100; break;
    case aFNC4: *pOutPos = 101; break;
    case aFNC1: *pOutPos = 102; break; /* FNC1s (GS1) not used */           /* Not reached */
    case aFNC2: *pOutPos = 97; break; /* FNC2s (Message Append) not used */ /* Not reached */
    case aFNC3: *pOutPos = 96; break;
    case aCodeC: *pOutPos = 99; break;
    case aShift: *pOutPos = 98; break;
    default:
        /* +++ HaO 13.11.98 c>' ' && c < '\x1F' corrected */
        if (c >= ' ' && c <= '_')
            *pOutPos = (uchar) (c - ' ');
        else
            *pOutPos = (uchar) (c + 64);
        break;
    }
    (*ppOutPos)++;
}

/* Output c in Set B
 */
static void A2C128_B(uchar **ppOutPos, const uchar c) {
    uchar *pOutPos = *ppOutPos;
    switch (c) {
    case aFNC1: *pOutPos = 102; break; /* FNC1s (GS1) not used */           /* Not reached */
    case aFNC2: *pOutPos = 97; break; /* FNC2s (Message Append) not used */ /* Not reached */
    case aFNC3: *pOutPos = 96; break;
    case aFNC4: *pOutPos = 100; break;
    case aCodeA: *pOutPos = 101; break;
    case aCodeC: *pOutPos = 99; break;
    case aShift: *pOutPos = 98; break;
    default: *pOutPos = (uchar) (c - ' '); break;
    }
    (*ppOutPos)++;
}

/* Output c1, c2 in Set C
 */
static void A2C128_C(uchar **ppOutPos, const uchar c1, const uchar c2) {
    uchar *pOutPos = *ppOutPos;
    switch (c1) {
    case aFNC1: *pOutPos = 102; break; /* FNC1s (GS1) not used */ /* Not reached */
    case aCodeB: *pOutPos = 100; break;
    case aCodeA: *pOutPos = 101; break;
    default: *pOutPos = (uchar) (10 * (c1 - '0') + (c2 - '0')); break;
    }
    (*ppOutPos)++;
}

/* Output a character in Characterset
 */
static void ASCIIZ128(uchar **ppOutPos, const int CharacterSet, const uchar c1, const uchar c2) {
    if (CharacterSet == CodeA)
        A2C128_A(ppOutPos, c1);
    else if (CharacterSet == CodeB)
        A2C128_B(ppOutPos, c1);
    else
        A2C128_C(ppOutPos, c1, c2);
}

/* XLate Tables D.2, D.3 and F.1 of Codablock-F Specification and call output
 */
static void SumASCII(uchar **ppOutPos, const int Sum, const int CharacterSet) {
    switch (CharacterSet) {
    case CodeA: /* Row # Indicators and Data Check Characters K1/K2 for CodeA and CodeB are the same */
    case CodeB:
        if (Sum <= 31)
            A2C128_B(ppOutPos, (uchar) (Sum + 96));
        else if (Sum <= 47)
            A2C128_B(ppOutPos, (uchar) Sum);
        else
            A2C128_B(ppOutPos, (uchar) (Sum + 10));
        break;
    case CodeC:
        A2C128_C(ppOutPos, (uchar) (Sum / 10 + '0'), (uchar) (Sum % 10 + '0'));
        break;
    }
}

/* Main function called by zint framework
 */
INTERNAL int zint_codablockf(struct zint_symbol *symbol, unsigned char source[], int length) {
    int charCur, dataLength;
    int error_number;
    int rows, columns, useColumns;
    int fillings;
    int Sum1, Sum2;
    uchar *pOutPos;
    int rowCur;
    int characterSetCur;
    int emptyColumns;
    char dest[1000];
    int r, c;
    CharacterSetTable *T;
    unsigned char *data;
    int *pSet;
    uchar *pOutput;
    const int content_segs = symbol->output_options & BARCODE_CONTENT_SEGS;
    const int debug = symbol->debug & ZINT_DEBUG_PRINT;

    /* Suppresses clang-analyzer-core.VLASize warning */
    assert(length > 0);

    /* Parameter check */
    /* option1: rows <= 0: automatic, 1..44 */
    rows = symbol->option_1;
    if (rows == 1) {
        error_number = zint_code128(symbol, source, length);
        if (error_number < ZINT_ERROR) {
            symbol->output_options |= BARCODE_BIND;
            if (symbol->border_width == 0) { /* Allow override if non-zero */
                symbol->border_width = 1; /* AIM ISS-X-24 Section 4.6.1 b) (note change from previous default 2) */
            }
            z_hrt_cpy_nochk(symbol, ZCUCP(""), 0); /* Zap HRT for compatibility with CODABLOCKF */
            /* Use `content_segs` from `zint_code128()` */
            if (symbol->output_options & COMPLIANT_HEIGHT) {
                /* AIM ISS-X-24 Section 4.6.1 minimum row height 8X (for compatibility with CODABLOCKF, not specced
                   for CODE128) */
                if (error_number == 0) {
                    error_number = z_set_height(symbol, 8.0f, 10.0f, 0.0f, 0 /*no_errtxt*/);
                } else {
                    (void) z_set_height(symbol, 8.0f, 10.0f, 0.0f, 1 /*no_errtxt*/);
                }
            } else {
                (void) z_set_height(symbol, 0.0f, 5.0f, 0.0f, 1 /*no_errtxt*/);
            }
        }
        return error_number;
    }
    if (rows > 44) {
        return z_errtxtf(ZINT_ERROR_INVALID_OPTION, symbol, 410, "Number of rows '%d' out of range (0 to 44)", rows);
    }
    /* option_2: (usable data) columns: <= 0: automatic, 9..67 (min 9 == 4 data, max 67 == 62 data) */
    columns = symbol->option_2;
    if (!(columns <= 0 || (columns >= 9 && columns <= 67))) {
        return z_errtxtf(ZINT_ERROR_INVALID_OPTION, symbol, 411, "Number of columns '%d' out of range (9 to 67)",
                        columns);
    }
    if (columns < 0) { /* Protect against negative overflow (ticket #300 (#9) Andre Maute) */
        columns = 0;
    }

    data = (unsigned char *) z_alloca(length * 2 + 1);

    dataLength = 0;
    if (symbol->output_options & READER_INIT) {
        data[dataLength++] = aFNC3;
    }
    /* Replace all Codes>127 with <fnc4>Code-128 */
    for (charCur = 0; charCur < length; charCur++) {
        if (!z_isascii(source[charCur])) {
            data[dataLength++] = aFNC4;
            data[dataLength++] = (unsigned char) (source[charCur] & 127);
        } else
            data[dataLength++] = source[charCur];
    }

    /* Build character set table */
    T = (CharacterSetTable *) z_alloca(sizeof(CharacterSetTable) * dataLength);
    pSet = (int *) z_alloca(sizeof(int) * dataLength);
    CreateCharacterSetTable(T, data, dataLength);

    /* Find final row and column count */

    /* Neither row nor column count given */
    if (rows <= 0 && columns <= 0) {
        /* Use 1/1 aspect/ratio */
        columns = (int) floor(sqrt(dataLength)) + 5;
        if (columns > 67) {
            columns = 67;
        } else if (columns < 9) {
            columns = 9;
        }
        if (debug) {
            printf("Auto column count for %d characters:%d\n", dataLength, columns);
        }
    }
    /* There are 5 Codewords for Organisation Start(2),row(1),CheckSum,Stop */
    useColumns = columns - 5;
    if (rows > 0) {
        /* Row count given */
        error_number = Rows2Columns(T, dataLength, &rows, &useColumns, pSet, &fillings, debug);
    } else {
        /* Column count given */
        error_number = Columns2Rows(T, dataLength, &rows, &useColumns, pSet, &fillings, debug);
    }
    if (error_number != 0) {
        return z_errtxt(error_number, symbol, 413,
                        "Input too long, requires too many symbol characters (maximum 2726)");
    }
    /* Suppresses clang-analyzer-core.VLASize warning */
    assert(rows >= 2 && useColumns >= 4);

    /* Data Check Characters K1 and K2, Annex F */
    Sum1 = Sum2 = 0;
    for (charCur = 0; charCur < length; charCur++) {
        Sum1 = (Sum1 + (charCur + 1) * source[charCur]) % 86; /* Mod as we go along to avoid overflow */
        Sum2 = (Sum2 + charCur * source[charCur]) % 86;
    }

    if (debug) {
        int DPos;
        fputs("\nData:", stdout);
        for (DPos = 0; DPos < dataLength; DPos++)
            fputc(data[DPos], stdout);
        fputs("\n Set:", stdout);
        for (DPos = 0; DPos < dataLength; DPos++) {
            switch (pSet[DPos] & (CodeA | CodeB | CodeC)) {
            case CodeA: fputc('A', stdout); break;
            case CodeB: fputc('B', stdout); break;
            case CodeC: fputc('C', stdout); break;
            default: fputc('.', stdout); break;
            }
        }
        fputs("\nFNC1:", stdout);
        for (DPos = 0; DPos < dataLength; DPos++)
            fputc((pSet[DPos] & CodeFNC1) == 0 ? '.' : 'X', stdout);
        fputs("\n END:", stdout);
        for (DPos = 0; DPos < dataLength; DPos++)
            fputc((pSet[DPos] & CEnd) == 0 ? '.' : 'X', stdout);
        fputs("\nShif:", stdout);
        for (DPos = 0; DPos < dataLength; DPos++)
            fputc((pSet[DPos] & CShift) == 0 ? '.' : 'X', stdout);
        fputs("\nFILL:", stdout);
        for (DPos = 0; DPos < dataLength; DPos++)
            fputc((pSet[DPos] & CFill) == 0 ? '.' : 'X', stdout);
        fputc('\n', stdout);
        printf("K1 %d, K2 %d\n", Sum1, Sum2);
    }

    columns = useColumns + 5;

    /* Feedback options */
    symbol->option_1 = rows;
    symbol->option_2 = columns;

    /* >>> Build C128 code numbers */
    /* The C128 column count contains Start (2CW), Row ID, Checksum, Stop */
    pOutput = (unsigned char *) z_alloca((size_t) columns * (size_t) rows);
    pOutPos = pOutput;
    charCur = 0;
    /* >> Loop over rows */
    for (rowCur = 0; rowCur < rows; rowCur++) {
        if (charCur >= dataLength) {
            /* >> Empty line with StartA, aCodeB, row #, and then filler aCodeC aCodeB etc */
            *pOutPos++ = '\x67';
            *pOutPos++ = 100; /* aCodeB */
            characterSetCur = CodeB;
            SumASCII(&pOutPos, rowCur + 42, characterSetCur); /* Row # */
            emptyColumns = useColumns;
            if (rowCur == rows - 1) {
                emptyColumns -= 2;
            }
            while (emptyColumns > 0) {
                if (characterSetCur == CodeC) {
                    A2C128_C(&pOutPos, aCodeB, '\0');
                    characterSetCur = CodeB;
                } else {
                    A2C128_B(&pOutPos, aCodeC);
                    characterSetCur = CodeC;
                }
                --emptyColumns;
            }
        } else {
            /* >> Normal line */
            /* > Startcode */
            switch (pSet[charCur] & (CodeA | CodeB | CodeC)) {
            case CodeA:
                *pOutPos++ = '\x67';
                *pOutPos++ = '\x62';
                characterSetCur = CodeA;
                break;
            case CodeB:
                *pOutPos++ = '\x67';
                *pOutPos++ = '\x64';
                characterSetCur = CodeB;
                break;
            case CodeC:
            default:
                *pOutPos++ = '\x67';
                *pOutPos++ = '\x63';
                characterSetCur = CodeC;
                break;
            }
            /* > Set F1 */
            /* In first line : # of rows */
            SumASCII(&pOutPos, rowCur == 0 ? rows - 2 : rowCur + 42, characterSetCur);
            /* >>> Data */
            emptyColumns = useColumns;
            /* >> Character loop */
            while (emptyColumns > 0 && charCur < dataLength) {
                /* ? Change character set */
                if (emptyColumns < useColumns) {
                    if (pSet[charCur] & CodeA) {
                        /* Change to A */
                        ASCIIZ128(&pOutPos, characterSetCur, aCodeA, '\0');
                        --emptyColumns;
                        characterSetCur = CodeA;
                    } else if (pSet[charCur] & CodeB) {
                        /* Change to B */
                        ASCIIZ128(&pOutPos, characterSetCur, aCodeB, '\0');
                        --emptyColumns;
                        characterSetCur = CodeB;
                    } else if (pSet[charCur] & CodeC) {
                        /* Change to C */
                        ASCIIZ128(&pOutPos, characterSetCur, aCodeC, '\0');
                        --emptyColumns;
                        characterSetCur = CodeC;
                    }
                }
                if (pSet[charCur] & CShift) {
                    /* >> Shift it and put out the shifted character */
                    ASCIIZ128(&pOutPos, characterSetCur, aShift, '\0');
                    emptyColumns -= 2;
                    characterSetCur = (characterSetCur == CodeB) ? CodeA : CodeB;
                    ASCIIZ128(&pOutPos, characterSetCur, data[charCur], '\0');
                    characterSetCur = (characterSetCur == CodeB) ? CodeA : CodeB;
                } else {
                    /* Normal Character */
                    if (characterSetCur == CodeC) {
                        if (data[charCur] == aFNC1) /* FNC1s (GS1) not used */
                            A2C128_C(&pOutPos, aFNC1, '\0'); /* Not reached */
                        else {
                            A2C128_C(&pOutPos, data[charCur],
                                     (uchar) (charCur + 1 < dataLength ? data[charCur + 1] : 0));
                            ++charCur;
                            /* We need this here to get the good index */
                            /* for the termination flags in Set. */
                        }
                    } else
                        ASCIIZ128(&pOutPos, characterSetCur, data[charCur], '\0');
                    --emptyColumns;
                }
                /* >> End Criteria */
                if (charCur < dataLength && ((pSet[charCur] & CFill) || (pSet[charCur] & CEnd))) {
                    /* Fill line but leave space for checks in last line */
                    if (rowCur == rows - 1) {
                        emptyColumns -= 2;
                    }
                    while (emptyColumns > 0) {
                        switch (characterSetCur) {
                        case CodeC:
                            A2C128_C(&pOutPos, aCodeB, '\0');
                            characterSetCur = CodeB;
                            break;
                        case CodeB:
                            A2C128_B(&pOutPos, aCodeC);
                            characterSetCur = CodeC;
                            break;
                        case CodeA:
                            A2C128_A(&pOutPos, aCodeC);
                            characterSetCur = CodeC;
                            break;
                        }
                        --emptyColumns;
                    }
                }
                ++charCur;
            } /* Loop over characters */
        } /* if filling line / normal line */

        /* Add checksum in last line */
        if (rowCur == rows - 1) {
            SumASCII(&pOutPos, Sum1, characterSetCur);
            SumASCII(&pOutPos, Sum2, characterSetCur);
        }
        assert(columns * rowCur + useColumns + 3 == (int) (pOutPos - pOutput)); /* Suppress clang-tidy warning */
        /* Add Code 128 checksum */
        {
            int Sum = pOutput[columns * rowCur] % 103;
            int Pos = 1;
            for (; Pos < useColumns + 3; Pos++) {
                Sum = (Sum + pOutput[columns * rowCur + Pos] * Pos) % 103;
            }
            *pOutPos++ = (uchar) Sum;
        }
        /* Add end character */
        *pOutPos++ = 106;
    } /* End Lineloop */

    if (debug) {
        int DPos, DPos2;
        fputs("\nCode 128 Code Numbers:\n", stdout);
        for (DPos = 0; DPos < rows; DPos++) {
            for (DPos2 = 0; DPos2 < columns; DPos2++) {
                printf("%3d ", (int) pOutput[DPos * columns + DPos2]);
            }
            fputc('\n', stdout);
        }
        printf("rows=%d columns=%d (%d data) fillings=%d\n", rows, columns, columns - 5, fillings);
    }
#ifdef ZINT_TEST
    if (symbol->debug & ZINT_DEBUG_TEST) {
        z_debug_test_codeword_dump(symbol, pOutput, rows * columns);
    }
#endif

    symbol->rows = 0; /* Stacked are not stackable */

    /* Paint the C128 patterns */
    for (r = 0; r < rows; r++) {
        const int rc = r * columns;
        char *d = dest;
        for (c = 0; c < columns - 1; c++, d += 6) {
            memcpy(d, zint_C128Table[pOutput[rc + c]], 6);
        }
        memcpy(d, "2331112", 7); /* Stop character (106, not in `zint_C128Table[]`) */
        d += 7;
        z_expand(symbol, dest, d - dest);
    }

    if (symbol->output_options & COMPLIANT_HEIGHT) {
        /* AIM ISS-X-24 Section 4.6.1 minimum row height; use 10 * rows as default */
        float min_row_height = z_stripf(0.55f * useColumns + 3.0f);
        if (min_row_height < 8.0f) {
            min_row_height = 8.0f;
        }
        error_number = z_set_height(symbol, min_row_height, (min_row_height > 10.0f ? min_row_height : 10.0f) * rows,
                                  0.0f, 0 /*no_errtxt*/);
    } else {
        (void) z_set_height(symbol, 0.0f, 10.0f * rows, 0.0f, 1 /*no_errtxt*/);
    }

    symbol->output_options |= BARCODE_BIND;

    if (symbol->border_width == 0) { /* Allow override if non-zero */
        symbol->border_width = 1; /* AIM ISS-X-24 Section 4.6.1 b) (note change from previous default 2) */
    }

    if (content_segs) {
        if ((symbol->input_mode & 0x07) == DATA_MODE) {
            if (z_ct_cpy(symbol, source, length)) {
                return ZINT_ERROR_MEMORY; /* `z_ct_cpy()` only fails with OOM */
            }
        } else if (z_ct_cpy_iso8859_1(symbol, source, length)) {
            return ZINT_ERROR_MEMORY; /* `z_ct_cpy_iso8859_1()` only fails with OOM */
        }
    }

    return error_number;
}

/* vim: set ts=4 sw=4 et : */