about summary refs log tree commit diff
path: root/converter/ppm/ppmtopcx.c
blob: b82a9d60067aa7839282ba343fbb6bd737425d9c (plain) (blame)
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
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
/* ppmtopcx.c - convert a portable pixmap to PCX
**
** Copyright (C) 1994 by Ingo Wilken (Ingo.Wilken@informatik.uni-oldenburg.de)
** based on ppmtopcx.c by Michael Davidson
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted, provided
** that the above copyright notice appear in all copies and that both that
** copyright notice and this permission notice appear in supporting
** documentation.  This software is provided "as is" without express or
** implied warranty.
**
** 11/Dec/94: first version
** 12/Dec/94: added handling of "packed" format (16 colors or less)
**
** ZSoft PCX File Format Technical Reference Manual
** http://bespin.org/~qz/pc-gpe/pcx.txt
** http://web.archive.org/web/20100206055706/http://www.qzx.com/pc-gpe/pcx.txt
*/
#include <assert.h>

#include "pm_c_util.h"
#include "ppm.h"
#include "shhopt.h"
#include "mallocvar.h"

#define MAXCOLORS       256

#define PCX_MAGIC       0x0a            /* PCX magic number             */
#define PCX_256_COLORS  0x0c            /* magic number for 256 colors  */
#define PCX_MAXVAL      (pixval)255


struct CmdlineInfo {
    /* All the information the user supplied in the command line,
       in a form easy for the program to use.
    */
    const char * inputFilespec;  /* '-' if stdin */
    unsigned int truecolor;   /* -24bit option */
    unsigned int use8Bit; /* -8bit option */
    unsigned int planes;    /* zero means minimum */
    unsigned int packed;
    unsigned int verbose;
    unsigned int stdpalette;
    const char * palette;   /* NULL means none */
    int xpos;
    int ypos;
};



struct PcxCmapEntry {
    unsigned char r;
    unsigned char g;
    unsigned char b;
};

static struct PcxCmapEntry
pcxCmapEntryFromPixel(pixel const colorPixel) {

    struct PcxCmapEntry retval;

    retval.r = PPM_GETR(colorPixel);
    retval.g = PPM_GETG(colorPixel);
    retval.b = PPM_GETB(colorPixel);

    return retval;
}



static void
parseCommandLine(int argc, const char ** argv,
                 struct CmdlineInfo * const cmdlineP) {
/*----------------------------------------------------------------------------
   parse program command line described in Unix standard form by argc
   and argv.  Return the information in the options as *cmdlineP.

   If command line is internally inconsistent (invalid options, etc.),
   issue error message to stderr and abort program.

   Note that the strings we return are stored in the storage that
   was passed to us as the argv array.  We also trash *argv.
-----------------------------------------------------------------------------*/
    optEntry * option_def;
        /* Instructions to pm_optParseOptions3 on how to parse our options.
         */
    optStruct3 opt;

    unsigned int option_def_index;

    unsigned int planesSpec, xposSpec, yposSpec, paletteSpec;

    MALLOCARRAY(option_def, 100);

    option_def_index = 0;   /* incremented by OPTENT3 */
    OPTENT3(0, "24bit",     OPT_FLAG,   NULL,
            &cmdlineP->truecolor,    0);
    OPTENT3(0, "8bit",      OPT_FLAG,   NULL,
            &cmdlineP->use8Bit,    0);
    OPTENT3(0, "planes",    OPT_UINT,   &cmdlineP->planes,
            &planesSpec,             0);
    OPTENT3(0, "packed",    OPT_FLAG,   NULL,
            &cmdlineP->packed,       0);
    OPTENT3(0, "verbose",   OPT_FLAG,   NULL,
            &cmdlineP->verbose,      0);
    OPTENT3(0, "stdpalette", OPT_FLAG,  NULL,
            &cmdlineP->stdpalette,   0);
    OPTENT3(0, "palette",    OPT_STRING, &cmdlineP->palette,
            &paletteSpec,   0);
    OPTENT3(0, "xpos",  OPT_INT, &cmdlineP->xpos, &xposSpec,   0);
    OPTENT3(0, "ypos",  OPT_INT, &cmdlineP->ypos, &yposSpec,   0);

    opt.opt_table = option_def;
    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */

    pm_optParseOptions3( &argc, (char **)argv, opt, sizeof(opt), 0 );
        /* Uses and sets argc, argv, and some of *cmdline_p and others. */

    if (!xposSpec)
        cmdlineP->xpos = 0;
    else if (cmdlineP->xpos < -32767 || cmdlineP->xpos > 32768)
        pm_error("-xpos value (%d) is outside acceptable range "
                 "(-32767, 32768)", cmdlineP->xpos);

    if (!yposSpec)
        cmdlineP->ypos = 0;
    else if (cmdlineP->ypos < -32767 || cmdlineP->ypos > 32768)
        pm_error("-ypos value (%d) is outside acceptable range "
                 "(-32767, 32768)", cmdlineP->ypos);

    if (!planesSpec)
        cmdlineP->planes = 0;  /* 0 means minimum */

    if (planesSpec) {
        if (cmdlineP->planes > 4 || cmdlineP->planes < 1)
            pm_error("The only possible numbers of planes are 1-4.  "
                     "You specified %u", cmdlineP->planes);
        if (cmdlineP->packed)
            pm_error("-planes is meaningless with -packed.");
        if (cmdlineP->truecolor)
            pm_error("-planes is meaningless with -24bit");
        if (cmdlineP->use8Bit)
            pm_error("-planes is meaningless with -8bit");
    }

    if (paletteSpec && cmdlineP->stdpalette)
        pm_error("You can't specify both -palette and -stdpalette");

    if (!paletteSpec)
        cmdlineP->palette = NULL;

    if (cmdlineP->use8Bit && cmdlineP->truecolor)
        pm_error("You cannot specify both -8bit and -truecolor");

    if (argc-1 < 1)
        cmdlineP->inputFilespec = "-";
    else if (argc-1 == 1)
        cmdlineP->inputFilespec = argv[1];
    else
        pm_error("Program takes at most one argument "
                 "(input file specification).  You specified %d",
                 argc-1);

    free(option_def);
}



/*
 * Write out a two-byte little-endian word to the PCX file
 */
static void
putword(int    const w,
        FILE * const fp) {

    int rc;

    rc = pm_writelittleshort(fp, w);

    if (rc != 0)
        pm_error("Error writing integer to output file");
}



/*
 * Write out a byte to the PCX file
 */
static void
putbyte(int    const b,
        FILE * const fp) {

    int rc;

    rc = fputc(b & 0xff, fp);

    if (rc == EOF)
        pm_error("Error writing byte to output file.");
}



static void
extractPlane(unsigned char * const rawrow,
             int             const cols,
             unsigned char * const buf,
             int             const plane) {
/*----------------------------------------------------------------------------
   From the image row 'rawrow', which is an array of 'cols' palette indices
   (as unsigned 8 bit integers), extract plane number 'plane' and return
   it at 'buf'.

   E.g. Plane 2 is all the 2nd bits from the palette indices, packed so
   that each byte represents 8 columns.
-----------------------------------------------------------------------------*/
    unsigned int const planeMask = 1 << plane;

    unsigned int col;
    int cbit;  /* Significance of bit representing current column in output */
    unsigned char *cp;  /* Ptr to next output byte to fill */
    unsigned char byteUnderConstruction;

    cp = buf;  /* initial value */

    cbit = 7;
    byteUnderConstruction = 0x00;
    for (col = 0; col < cols; ++col) {
        if (rawrow[col] & planeMask)
            byteUnderConstruction |= (1 << cbit);

        --cbit;
        if (cbit < 0) {
            /* We've filled a byte.  Output it and start the next */
            *cp++ = byteUnderConstruction;
            cbit = 7;
            byteUnderConstruction = 0x00;
        }
    }
    if (cbit < 7)
        /* A byte was partially built when we ran out of columns (the number
           of columns is not a multiple of 8.  Output the partial byte.
        */
        *cp++ = byteUnderConstruction;
}



static void
packBits(unsigned char * const rawrow,
         int             const width,
         unsigned char * const buf,
         int             const bits) {

    int x, i, shift;

    shift = i = -1;

    for (x = 0; x < width; ++x) {
        if (shift < 0) {
            shift = 8 - bits;
            buf[++i] = 0;
        }

        buf[i] |= (rawrow[x] << shift);
        shift -= bits;
    }
}



static void
writeHeader(FILE *              const fp,
            int                 const cols,
            int                 const rows,
            int                 const bitsPerPixel,
            int                 const planes,
            struct PcxCmapEntry const cmap16[],
            unsigned int        const xPos,
            unsigned int        const yPos) {

    int i, bytesPerLine;

    putbyte(PCX_MAGIC, fp);        /* .PCX magic number            */
    putbyte(0x05, fp);             /* PC Paintbrush version        */
    putbyte(0x01, fp);             /* .PCX run length encoding     */
    putbyte(bitsPerPixel, fp);     /* bits per pixel               */

    putword(xPos, fp);             /* x1   - image left            */
    putword(yPos, fp);             /* y1   - image top             */
    putword(xPos+cols-1, fp);      /* x2   - image right           */
    putword(yPos+rows-1, fp);      /* y2   - image bottom          */

    putword(cols, fp);             /* horizontal resolution        */
    putword(rows, fp);             /* vertical resolution          */

    /* Write out the Color Map for images with 16 colors or less */
    if (cmap16)
        for (i = 0; i < 16; ++i) {
            putbyte(cmap16[i].r, fp);
            putbyte(cmap16[i].g, fp);
            putbyte(cmap16[i].b, fp);
        }
    else {
        unsigned int i;
        for (i = 0; i < 16; ++i) {
            putbyte(0, fp);
            putbyte(0, fp);
            putbyte(0, fp);
        }
    }
    putbyte(0, fp);                /* reserved byte                */
    putbyte(planes, fp);           /* number of color planes       */

    bytesPerLine = ((cols * bitsPerPixel) + 7) / 8;
    putword(bytesPerLine, fp);    /* number of bytes per scanline */

    putword(1, fp);                /* palette info                 */

    {
        unsigned int i;
        for (i = 0; i < 58; ++i)        /* fill to end of header        */
            putbyte(0, fp);
    }
}



static void
pcxEncode(FILE *                const fp,
          const unsigned char * const buf,
          int                   const Size) {

    const unsigned char * const end = buf + Size;

    const unsigned char * currentP;
    int previous, count;

    currentP = buf;
    previous = *currentP++;
    count    = 1;

    while (currentP < end) {
        unsigned char const c = *currentP++;
        if (c == previous && count < 63)
            ++count;
        else {
            if (count > 1 || (previous & 0xc0) == 0xc0) {
                count |= 0xc0;
                putbyte ( count , fp );
            }
            putbyte(previous, fp);
            previous = c;
            count   = 1;
        }
    }

    if (count > 1 || (previous & 0xc0) == 0xc0) {
        count |= 0xc0;
        putbyte ( count , fp );
    }
    putbyte(previous, fp);
}



static unsigned int
indexOfColor(colorhash_table const cht,
             pixel           const color) {
/*----------------------------------------------------------------------------
   Return the index in the palette described by 'cht' of the color 'color'.

   Abort program with error message if the color is not in the palette.
-----------------------------------------------------------------------------*/

    int const rc = ppm_lookupcolor(cht, &color);

    if (rc < 0)
        pm_error("Image contains color which is not "
                 "in the palette: %u/%u/%u",
                 PPM_GETR(color), PPM_GETG(color), PPM_GETB(color));

    return rc;
}



static void
ppmTo16ColorPcx(pixel **            const pixels,
                int                 const cols,
                int                 const rows,
                struct PcxCmapEntry const pcxcmap[],
                int                 const colors,
                colorhash_table     const cht,
                bool                const packbits,
                unsigned int        const planesRequested,
                unsigned int        const xPos,
                unsigned int        const yPos) {

    int planes, bytesPerLine, bitsPerPixel;
    unsigned char * indexRow;  /* malloc'ed */
        /* indexRow[x] is the palette index of the pixel at column x of
           the row currently being processed
        */
    unsigned char * planesrow; /* malloc'ed */
        /* This is the input for a single row to the compressor */
    int row;

    if (packbits) {
        planes = 1;
        if (colors > 4)        bitsPerPixel = 4;
        else if (colors > 2)   bitsPerPixel = 2;
        else                   bitsPerPixel = 1;
    } else {
        bitsPerPixel = 1;
        if (planesRequested)
            planes = planesRequested;
        else {
            if (colors > 8)        planes = 4;
            else if (colors > 4)   planes = 3;
            else if (colors > 2)   planes = 2;
            else                   planes = 1;
        }
    }
    bytesPerLine = ((cols * bitsPerPixel) + 7) / 8;
    MALLOCARRAY_NOFAIL(indexRow, cols);
    MALLOCARRAY_NOFAIL(planesrow, bytesPerLine);

    writeHeader(stdout, cols, rows, bitsPerPixel, planes, pcxcmap,
                xPos, yPos);
    for (row = 0; row < rows; ++row) {
        int col;
        for (col = 0; col < cols; ++col)
            indexRow[col] = indexOfColor(cht, pixels[row][col]);

        if (packbits) {
            packBits(indexRow, cols, planesrow, bitsPerPixel);
            pcxEncode(stdout, planesrow, bytesPerLine);
        } else {
            unsigned int plane;
            for (plane = 0; plane < planes; ++plane) {
                extractPlane(indexRow, cols, planesrow, plane);
                pcxEncode(stdout, planesrow, bytesPerLine);
            }
        }
    }
    free(planesrow);
    free(indexRow);
}



static void
ppmTo256ColorPcx(pixel **            const pixels,
                 int                 const cols,
                 int                 const rows,
                 struct PcxCmapEntry const pcxcmap[],
                 int                 const colors,
                 colorhash_table     const cht,
                 unsigned int        const xPos,
                 unsigned int        const yPos) {

    int row;
    unsigned int i;
    unsigned char *rawrow;

    rawrow = (unsigned char *)pm_allocrow(cols, sizeof(unsigned char));

    /* 8 bits per pixel, 1 plane */
    writeHeader(stdout, cols, rows, 8, 1, NULL, xPos, yPos);
    for (row = 0; row < rows; ++row) {
        int col;
        for (col = 0; col < cols; ++col)
            rawrow[col] = indexOfColor(cht, pixels[row][col]);
        pcxEncode(stdout, rawrow, cols);
    }
    putbyte(PCX_256_COLORS, stdout);
    for (i = 0; i < MAXCOLORS; ++i) {
        putbyte(pcxcmap[i].r, stdout);
        putbyte(pcxcmap[i].g, stdout);
        putbyte(pcxcmap[i].b, stdout);
    }
    pm_freerow((void*)rawrow);
}



static void
ppmToTruecolorPcx(pixel **     const pixels,
                  int          const cols,
                  int          const rows,
                  pixval       const maxval,
                  unsigned int const xPos,
                  unsigned int const yPos) {

    unsigned char * redrow;
    unsigned char * greenrow;
    unsigned char * bluerow;
    int col, row;

    redrow   = (unsigned char *)pm_allocrow(cols, sizeof(unsigned char));
    greenrow = (unsigned char *)pm_allocrow(cols, sizeof(unsigned char));
    bluerow  = (unsigned char *)pm_allocrow(cols, sizeof(unsigned char));

    /* 8 bits per pixel, 3 planes */
    writeHeader(stdout, cols, rows, 8, 3, NULL, xPos, yPos);
    for( row = 0; row < rows; row++ ) {
        register pixel *pP = pixels[row];
        for( col = 0; col < cols; col++, pP++ ) {
            if( maxval != PCX_MAXVAL ) {
                redrow[col]   = (long)PPM_GETR(*pP) * PCX_MAXVAL / maxval;
                greenrow[col] = (long)PPM_GETG(*pP) * PCX_MAXVAL / maxval;
                bluerow[col]  = (long)PPM_GETB(*pP) * PCX_MAXVAL / maxval;
            }
            else {
                redrow[col]   = PPM_GETR(*pP);
                greenrow[col] = PPM_GETG(*pP);
                bluerow[col]  = PPM_GETB(*pP);
            }
        }
        pcxEncode(stdout, redrow, cols);
        pcxEncode(stdout, greenrow, cols);
        pcxEncode(stdout, bluerow, cols);
    }
    pm_freerow((void*)bluerow);
    pm_freerow((void*)greenrow);
    pm_freerow((void*)redrow);
}



static const struct PcxCmapEntry
stdPalette[] = {
    {   0,   0,   0 },
    {   0,   0, 170 },
    {   0, 170,   0 },
    {   0, 170, 170 },
    { 170,   0,   0 },
    { 170,   0, 170 },
    { 170, 170,   0 },
    { 170, 170, 170 },
    {  85,  85,  85 },
    {  85,  85, 255 },
    {  85, 255,  85 },
    {  85, 255, 255 },
    { 255,  85,  85 },
    { 255,  85, 255 },
    { 255, 255,  85 },
    { 255, 255, 255 }
};



static void
putPcxColorInHash(colorhash_table const cht,
                  pixel           const newPcxColor,
                  unsigned int    const newColorIndex,
                  pixval          const maxval) {

    pixel ppmColor;
        /* Same color as 'newPcxColor', but at the PPM image's color
           resolution: 'maxval'
        */
    int rc;

    PPM_DEPTH(ppmColor, newPcxColor, PCX_MAXVAL, maxval);

    rc = ppm_lookupcolor(cht, &ppmColor);

    if (rc == -1)
        /* This color is not in the hash yet, so we just add it */
        ppm_addtocolorhash(cht, &ppmColor, newColorIndex);
    else {
        /* This color is already in the hash.  That's because the
           subject image has less color resolution than PCX (i.e.
           'maxval' is less than PCX_MAXVAL), and two distinct
           colors in the standard palette are indistinguishable at
           subject image color resolution.

           So we have to figure out whether color 'newPcxColor' or
           'existingPcxColor' is a better match for 'ppmColor'.
        */

        unsigned int const existingColorIndex = rc;

        pixel idealPcxColor;
        pixel existingPcxColor;

        PPM_DEPTH(idealPcxColor, ppmColor, maxval, PCX_MAXVAL);

        PPM_ASSIGN(existingPcxColor,
                   stdPalette[existingColorIndex].r,
                   stdPalette[existingColorIndex].g,
                   stdPalette[existingColorIndex].b);

        if (PPM_DISTANCE(newPcxColor, idealPcxColor) <
            PPM_DISTANCE(existingPcxColor, idealPcxColor)) {
            /* The new PCX color is a better match.  Make it the new
               translation of image color 'ppmColor'.
            */
            ppm_delfromcolorhash(cht, &ppmColor);
            ppm_addtocolorhash(cht, &ppmColor, newColorIndex);
        }
    }
}



static void
generateStandardPalette(struct PcxCmapEntry ** const pcxcmapP,
                        pixval                 const maxval,
                        colorhash_table *      const chtP,
                        int *                  const colorsP) {

    unsigned int const stdPaletteSize = 16;
    unsigned int colorIndex;
    struct PcxCmapEntry * pcxcmap;
    colorhash_table cht;

    MALLOCARRAY_NOFAIL(pcxcmap, MAXCOLORS);

    *pcxcmapP = pcxcmap;

    cht = ppm_alloccolorhash();

    for (colorIndex = 0; colorIndex < stdPaletteSize; ++colorIndex) {
        pixel pcxColor;
            /* The color of this colormap entry, in PCX resolution */

        pcxcmap[colorIndex] = stdPalette[colorIndex];

        PPM_ASSIGN(pcxColor,
                   stdPalette[colorIndex].r,
                   stdPalette[colorIndex].g,
                   stdPalette[colorIndex].b);

        putPcxColorInHash(cht, pcxColor, colorIndex, maxval);
    }

    /* Set remaining slots in palette to black.  The values are not
       meaningful, but this suppresses a Valgrind warning about our writing
       undefined values to the file and makes our output constant with input.
    */
    for ( ; colorIndex < MAXCOLORS; ++colorIndex) {
        pcxcmap[colorIndex].r = 0;
        pcxcmap[colorIndex].g = 0;
        pcxcmap[colorIndex].b = 0;
    }

    *chtP = cht;
    *colorsP = stdPaletteSize;
}



static void
readPpmPalette(const char *   const paletteFileName,
               pixel       (* const ppmPaletteP)[],
               unsigned int * const paletteSizeP) {

    FILE * pfP;
    pixel ** pixels;
    int cols, rows;
    pixval maxval;

    pfP = pm_openr(paletteFileName);

    pixels = ppm_readppm(pfP, &cols, &rows, &maxval);

    pm_close(pfP);

    *paletteSizeP = rows * cols;
    if (*paletteSizeP > MAXCOLORS)
        pm_error("ordered palette image contains %d pixels.  Maximum is %d",
                 *paletteSizeP, MAXCOLORS);

    {
        int j;
        int row;
        j = 0;  /* initial value */
        for (row = 0; row < rows; ++row) {
            int col;
            for (col = 0; col < cols; ++col)
                (*ppmPaletteP)[j++] = pixels[row][col];
        }
    }
    ppm_freearray(pixels, rows);
}



static void
readPaletteFromFile(struct PcxCmapEntry ** const pcxcmapP,
                    const char *           const paletteFileName,
                    pixval                 const maxval,
                    colorhash_table *      const chtP,
                    int *                  const colorsP) {

    unsigned int colorIndex;
    pixel ppmPalette[MAXCOLORS];
    unsigned int paletteSize;
    struct PcxCmapEntry * pcxcmap;
    colorhash_table cht;

    readPpmPalette(paletteFileName, &ppmPalette, &paletteSize);

    MALLOCARRAY_NOFAIL(pcxcmap, MAXCOLORS);

    *pcxcmapP = pcxcmap;

    cht = ppm_alloccolorhash();

    for (colorIndex = 0; colorIndex < paletteSize; ++colorIndex) {
        pixel pcxColor;
            /* The color of this colormap entry, in PCX resolution */

        pcxcmap[colorIndex] = pcxCmapEntryFromPixel(ppmPalette[colorIndex]);

        PPM_ASSIGN(pcxColor,
                   ppmPalette[colorIndex].r,
                   ppmPalette[colorIndex].g,
                   ppmPalette[colorIndex].b);

        putPcxColorInHash(cht, pcxColor, colorIndex, maxval);
    }

    *chtP = cht;
    *colorsP = paletteSize;
}



static void
moveBlackToIndex0(colorhist_vector const chv,
                  int              const colors) {
/*----------------------------------------------------------------------------
   If black is in the palette, make it at Index 0.
-----------------------------------------------------------------------------*/
    pixel blackPixel;
    unsigned int i;
    bool blackPresent;

    PPM_ASSIGN(blackPixel, 0, 0, 0);

    blackPresent = FALSE;  /* initial assumption */

    for (i = 0; i < colors; ++i)
        if (PPM_EQUAL(chv[i].color, blackPixel))
            blackPresent = TRUE;

    if (blackPresent) {
        /* We use a trick here.  ppm_addtocolorhist() always adds to the
           beginning of the table and if the color is already elsewhere in
           the table, removes it.
        */
        int colors2;
        colors2 = colors;
        ppm_addtocolorhist(chv, &colors2, MAXCOLORS, &blackPixel, 0, 0);
        assert(colors2 == colors);
    }
}



static void
makePcxColormapFromImage(pixel **               const pixels,
                         int                    const cols,
                         int                    const rows,
                         pixval                 const maxval,
                         struct PcxCmapEntry ** const pcxcmapP,
                         colorhash_table *      const chtP,
                         int *                  const colorsP,
                         bool *                 const tooManyColorsP) {
/*----------------------------------------------------------------------------
   Make a colormap (palette) for the PCX header that can be used
   for the image described by 'pixels', 'cols', 'rows', and 'maxval'.

   Return it in newly malloc'ed storage and return its address as
   *pcxcmapP.

   Also return a lookup hash to relate a color in the image to the
   appropriate index in *pcxcmapP.  Return that in newly malloc'ed
   storage as *chtP.

   Iff there are too many colors to do that (i.e. more than 256),
   return *tooManyColorsP == TRUE.
-----------------------------------------------------------------------------*/
    int colors;
    colorhist_vector chv;

    pm_message("computing colormap...");

    chv = ppm_computecolorhist(pixels, cols, rows, MAXCOLORS, &colors);
    if (chv == NULL)
        *tooManyColorsP = TRUE;
    else {
        int i;
        struct PcxCmapEntry * pcxcmap;

        *tooManyColorsP = FALSE;

        pm_message("%d colors found", colors);

        moveBlackToIndex0(chv, colors);

        MALLOCARRAY_NOFAIL(pcxcmap, MAXCOLORS);

        *pcxcmapP = pcxcmap;

        for (i = 0; i < colors; ++i) {
            pixel p;

            PPM_DEPTH(p, chv[i].color, maxval, PCX_MAXVAL);

            pcxcmap[i].r = PPM_GETR(p);
            pcxcmap[i].g = PPM_GETG(p);
            pcxcmap[i].b = PPM_GETB(p);
        }

        /* Fill it out with black */
        for ( ; i < MAXCOLORS; ++i) {
            pcxcmap[i].r = 0;
            pcxcmap[i].g = 0;
            pcxcmap[i].b = 0;
        }

        *chtP = ppm_colorhisttocolorhash(chv, colors);

        *colorsP = colors;

        ppm_freecolorhist(chv);
    }
}



static void
ppmToPalettePcx(pixel **            const pixels,
                int                 const cols,
                int                 const rows,
                pixval              const maxval,
                unsigned int        const xPos,
                unsigned int        const yPos,
                struct PcxCmapEntry const pcxcmap[],
                colorhash_table     const cht,
                int                 const colors,
                bool                const packbits,
                unsigned int        const planes,
                bool                const use_8_bit) {

    /* convert image */
    if( colors <= 16 && !use_8_bit )
        ppmTo16ColorPcx(pixels, cols, rows, pcxcmap, colors, cht,
                        packbits, planes, xPos, yPos);
    else
        ppmTo256ColorPcx(pixels, cols, rows, pcxcmap, colors, cht,
                         xPos, yPos);
}



int
main(int argc, const char *argv[]) {

    struct CmdlineInfo cmdline;
    FILE * ifP;
    int rows, cols;
    pixval maxval;
    pixel **pixels;
    struct PcxCmapEntry * pcxcmap;
    colorhash_table cht;
    bool truecolor;
    int colors;

    pm_proginit(&argc, argv);

    parseCommandLine(argc, argv, &cmdline);

    ifP = pm_openr(cmdline.inputFilespec);
    pixels = ppm_readppm(ifP, &cols, &rows, &maxval);
    pm_close(ifP);

    if (cmdline.truecolor)
        truecolor = TRUE;
    else {
        if (cmdline.stdpalette) {
            truecolor = FALSE;
            generateStandardPalette(&pcxcmap, maxval, &cht, &colors);
        } else if (cmdline.palette) {
            truecolor = FALSE;
            readPaletteFromFile(&pcxcmap, cmdline.palette, maxval,
                                &cht, &colors);
        } else {
            bool tooManyColors;
            makePcxColormapFromImage(pixels, cols, rows, maxval,
                                     &pcxcmap, &cht, &colors,
                                     &tooManyColors);

            if (tooManyColors) {
                pm_message("too many colors - writing a 24bit PCX file");
                pm_message("if you want a non-24bit file, "
                           " a 'pnmquant %d'", MAXCOLORS);
                truecolor = TRUE;
            } else
                truecolor = FALSE;
        }
    }

    if (truecolor)
        ppmToTruecolorPcx(pixels, cols, rows, maxval,
                          cmdline.xpos, cmdline.ypos);
    else {
        ppmToPalettePcx(pixels, cols, rows, maxval,
                        cmdline.xpos, cmdline.ypos,
                        pcxcmap, cht, colors, cmdline.packed,
                        cmdline.planes, cmdline.use8Bit);

        ppm_freecolorhash(cht);
        free(pcxcmap);
    }
    return 0;
}