about summary refs log tree commit diff
path: root/editor/pamundice.c
blob: 5c5043564c2da7382f067f3fd1caa8d4a7d333d0 (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
/*****************************************************************************
                                  pamundice
******************************************************************************
  Assemble a grid of images into one.

  By Bryan Henderson, San Jose CA 2001.01.31

  Contributed to the public domain.

******************************************************************************/

#include <assert.h>
#include <string.h>

#include "pam.h"
#include "shhopt.h"
#include "nstring.h"
#include "mallocvar.h"

#define MAXFILENAMELEN 80
    /* Maximum number of characters we accept in filenames */

struct cmdlineInfo {
    /* All the information the user supplied in the command line,
       in a form easy for the program to use.
    */
    const char * inputFilePattern;
        /* null-terminated string, max MAXFILENAMELEN-10 characters */
    unsigned int across;
    unsigned int down;
    unsigned int hoverlap; 
    unsigned int voverlap; 
    unsigned int verbose;
};



static void
parseCommandLine(int argc, 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 optParseOptions3 on how to parse our options.
         */
    optStruct3 opt;
    
    unsigned int acrossSpec, downSpec;
    unsigned int hoverlapSpec, voverlapSpec;
    unsigned int option_def_index;

    MALLOCARRAY_NOFAIL(option_def, 100);

    option_def_index = 0;   /* incremented by OPTENT3 */
    OPTENT3(0, "across",      OPT_UINT,    &cmdlineP->across,
            &acrossSpec,                      0);
    OPTENT3(0, "down",        OPT_UINT,    &cmdlineP->down,
            &downSpec,                        0);
    OPTENT3(0, "hoverlap",    OPT_UINT,    &cmdlineP->hoverlap,
            &hoverlapSpec,                    0);
    OPTENT3(0, "voverlap",    OPT_UINT,    &cmdlineP->voverlap,
            &voverlapSpec,                    0);
    OPTENT3(0, "verbose",     OPT_FLAG,    NULL,
            &cmdlineP->verbose,               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 */

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

    if (!acrossSpec)
        cmdlineP->across = 1;
    
    if (!downSpec)
        cmdlineP->down = 1;

    if (!hoverlapSpec)
        cmdlineP->hoverlap = 0;

    if (!voverlapSpec)
        cmdlineP->voverlap = 0;

    if (argc-1 < 1)
        pm_error("You must specify one argument: the input file name "
                 "pattern (e.g. 'myimage%%2a%%2d.pnm')");
    else {
        cmdlineP->inputFilePattern = argv[1];

        if (argc-1 > 1)
            pm_error("Progam takes at most one parameter: input file name.  "
                     "You specified %u", argc-1);
    }
}



/*------------------ string buffer -----------------------------------*/
struct buffer {
    char * string;
    unsigned int allocSize;
    unsigned int length;
};


static void
buffer_init(struct buffer * const bufferP) {

    bufferP->length = 0;
    bufferP->allocSize = 1024;
    MALLOCARRAY(bufferP->string, bufferP->allocSize);

    if (bufferP->string == NULL)
        pm_error("Out of memory allocating buffer to compute file name");
}



static void
buffer_term(struct buffer * const bufferP) {
    
    free(bufferP->string);
}



static void
buffer_addChar(struct buffer * const bufferP,
               char            const newChar) {

    if (bufferP->length + 1 + 1 > bufferP->allocSize)
        pm_error("Ridiculously long input file name.");
    else {
        bufferP->string[bufferP->length++] = newChar;
        bufferP->string[bufferP->length] = '\0';
    }
}



static void
buffer_addString(struct buffer * const bufferP,
                 const char *    const newString) {

    if (bufferP->length + 1 + strlen(newString) > bufferP->allocSize)
        pm_error("Ridiculously long input file name.");
    else {
        strcat(&bufferP->string[bufferP->length], newString);
        bufferP->length += strlen(newString);
    }
}
/*------------------ end of string buffer ----------------------------*/



/*------------------ computeInputFileName ----------------------------*/
static unsigned int
digitValue(char const digitChar) {

    return digitChar - '0';
}



static void
getPrecision(const char *   const pattern,
             unsigned int   const startInCursor,
             unsigned int * const precisionP,
             unsigned int * const newInCursorP) {

    unsigned int precision;
    unsigned int inCursor;

    inCursor = startInCursor;  /* Start right after the '%' */

    precision = 0;
                
    while (isdigit(pattern[inCursor])) {
        precision = 10 * precision + digitValue(pattern[inCursor]);
        ++inCursor;
    }

    if (precision == 0)
        pm_error("Zero (or no) precision in substitution "
                 "specification in file name pattern '%s'.  "
                 "A proper substitution specification is like "
                 "'%%3a'.", pattern);

    *precisionP = precision;
    *newInCursorP = inCursor;
}



static void
doSubstitution(const char *    const pattern,
               unsigned int    const startInCursor,
               unsigned int    const rank,
               unsigned int    const file,
               struct buffer * const bufferP,
               unsigned int *  const newInCursorP) {

    unsigned int inCursor;

    inCursor = startInCursor;  /* Start right after the '%' */

    if (pattern[inCursor] == '%') {
        buffer_addChar(bufferP, '%');
        ++inCursor;
    } else {
        unsigned int precision;
        
        getPrecision(pattern, inCursor, &precision, &inCursor);

        if (pattern[inCursor] == '\0')
            pm_error("No format character follows '%%' in input "
                     "file name pattern '%s'.  A proper substitution "
                     "specification is like '%%3a'", pattern);
        else {
            const char * substString;
            const char * desc;

            switch (pattern[inCursor]) {
            case 'a':
                asprintfN(&substString, "%0*u", precision, file);
                asprintfN(&desc, "file (across)");
                break;
            case 'd':
                asprintfN(&substString, "%0*u", precision, rank);
                asprintfN(&desc, "rank (down)");
                break;
            default:
                pm_error("Unknown format specifier '%c' in input file "
                         "pattern '%s'.  Recognized format specifier s are "
                         "'%%a' (across) and '%%d (down)'",
                         pattern[inCursor], pattern);
            }
            if (strlen(substString) > precision)
                pm_error("%s number %u is wider than "
                         "the %u characters specified in the "
                         "input file pattern",
                         desc, strlen(substString), precision);
            else
                buffer_addString(bufferP, substString);
            
            strfree(desc);
            strfree(substString);

            ++inCursor;
        }
    }
    *newInCursorP = inCursor;
}



static void
computeInputFileName(const char *  const pattern,
                     unsigned int  const rank,
                     unsigned int  const file,
                     const char ** const fileNameP) {

    struct buffer buffer;
    unsigned int inCursor, outCursor;

    buffer_init(&buffer);

    inCursor = 0;
    outCursor = 0;

    while (pattern[inCursor] != '\0') {
        if (pattern[inCursor] == '%') {
            ++inCursor;

            doSubstitution(pattern, inCursor, rank, file, &buffer, &inCursor);

        } else
            buffer_addChar(&buffer, pattern[inCursor++]);
    }

    asprintfN(fileNameP, "%s", buffer.string);

    buffer_term(&buffer);
}
/*------------------ end of computeInputFileName ------------------------*/



static void
getCommonInfo(const char *   const inputFilePattern,
              int *          const formatP,
              unsigned int * const depthP,
              sample *       const maxvalP,
              char *         const tupleType) {
/*----------------------------------------------------------------------------
   Get from the top left input image all the information which is common
   among all input images and the output image.  I.e. everything except
   width and height.
-----------------------------------------------------------------------------*/
    const char * fileName;
        /* Name of top left input image */
    FILE * ifP;
        /* Top left input image stream */
    struct pam inpam00;
        /* Description of top left input image */

    computeInputFileName(inputFilePattern, 0, 0, &fileName);

    ifP = pm_openr(fileName);

    pnm_readpaminit(ifP, &inpam00, PAM_STRUCT_SIZE(tuple_type));

    *formatP = inpam00.format;
    *depthP  = inpam00.depth;
    *maxvalP = inpam00.maxval;
    strcpy(tupleType, inpam00.tuple_type);

    pm_close(ifP);

    strfree(fileName);
}



static FILE *
openInputImage(const char * const inputFilePattern,
               unsigned int const rank,
               unsigned int const file) {

    FILE * retval;
    const char * fileName;
        
    computeInputFileName(inputFilePattern, rank, file, &fileName);

    retval = pm_openr(fileName);
    
    strfree(fileName);

    return retval;
}

               

static void
getImageInfo(const char * const inputFilePattern,
             unsigned int const rank,
             unsigned int const file,
             struct pam * const pamP) {

    FILE * ifP;

    ifP = openInputImage(inputFilePattern, rank, file);

    pnm_readpaminit(ifP, pamP, PAM_STRUCT_SIZE(tuple_type));

    pm_close(ifP);
    pamP->file = NULL;  /* for robustness */
}



static void
getOutputWidth(const char * const inputFilePattern,
               unsigned int const nFile,
               unsigned int const hoverlap,
               int *        const widthP) {
/*----------------------------------------------------------------------------
   Get the output width by adding up the widths of all 'nFile' images of
   the top rank, and allowing for overlap of 'hoverlap' pixels.
-----------------------------------------------------------------------------*/
    unsigned int totalWidth;
    unsigned int file;

    for (file = 0, totalWidth = 0; file < nFile; ++file) {
        struct pam inpam;

        getImageInfo(inputFilePattern, 0, file, &inpam);

        if (inpam.width < hoverlap)
            pm_error("Rank 0, file %u image has width %u, "
                     "which is less than the horizontal overlap of %u pixels",
                     file, inpam.width, hoverlap);
        else {
            totalWidth += inpam.width;

            if (file < nFile-1)
                totalWidth -= hoverlap;
        }
    }
    *widthP = totalWidth;
}



static void
getOutputHeight(const char *  const inputFilePattern,
                unsigned int  const nRank,
                unsigned int  const voverlap,
                int *         const heightP) {
/*----------------------------------------------------------------------------
   Get the output height by adding up the widths of all 'nRank' images of
   the left file, and allowing for overlap of 'voverlap' pixels.
-----------------------------------------------------------------------------*/
    unsigned int totalHeight;
    unsigned int rank;

    for (rank = 0, totalHeight = 0; rank < nRank; ++rank) {
        struct pam inpam;

        getImageInfo(inputFilePattern, rank, 0, &inpam);

        if (inpam.height < voverlap)
            pm_error("Rank %u, file 0 image has height %u, "
                     "which is less than the vertical overlap of %u pixels",
                     rank, inpam.height, voverlap);
        
        totalHeight += inpam.height;
        
        if (rank < nRank-1)
            totalHeight -= voverlap;
    }
    *heightP = totalHeight;
}



static void
initOutpam(const char * const inputFilePattern,
           unsigned int const nFile,
           unsigned int const nRank,
           unsigned int const hoverlap,
           unsigned int const voverlap,
           FILE *       const ofP,
           bool         const verbose,
           struct pam * const outpamP) {
/*----------------------------------------------------------------------------
   Figure out the attributes of the output image and return them as
   *outpamP.

   Do this by examining the top rank and left file of the input images,
   which are in files named by 'inputFilePattern', 'nFile', and 'nRank'.

   In computing dimensions, assume 'hoverlap' pixels of horizontal
   overlap and 'voverlap' pixels of vertical overlap.

   We overlook any inconsistencies among the images.  E.g. if two images
   have different depths, we just return one of them.  If two images in
   the top rank have different heights, we use just one of them.

   Therefore, Caller must check all the input images to make sure they are
   consistent with the information we return.
-----------------------------------------------------------------------------*/
    assert(nFile >= 1);
    assert(nRank >= 1);

    outpamP->size        = sizeof(*outpamP);
    outpamP->len         = PAM_STRUCT_SIZE(tuple_type);
    outpamP->file        = ofP;
    outpamP->plainformat = 0;
    
    getCommonInfo(inputFilePattern, &outpamP->format, &outpamP->depth,
                  &outpamP->maxval, outpamP->tuple_type);

    getOutputWidth(inputFilePattern, nFile, hoverlap, &outpamP->width);

    getOutputHeight(inputFilePattern, nRank, voverlap, &outpamP->height);

    if (verbose) {
        pm_message("Output width = %u pixels", outpamP->width);
        pm_message("Output height = %u pixels", outpamP->height);
    }
}



static void
openInStreams(struct pam         inpam[],
              unsigned int const rank,
              unsigned int const fileCount,
              char         const inputFilePattern[]) {
/*----------------------------------------------------------------------------
   Open the input files for a single horizontal slice (there's one file
   for each vertical slice) and read the Netpbm headers from them.  Return
   the pam structures to describe each.
-----------------------------------------------------------------------------*/
    unsigned int file;

    for (file = 0; file < fileCount; ++file) {
        FILE * const ifP = openInputImage(inputFilePattern, rank, file);

        pnm_readpaminit(ifP, &inpam[file], PAM_STRUCT_SIZE(tuple_type));
    }        
}



static void
closeInFiles(struct pam         pam[],
             unsigned int const fileCount) {

    unsigned int file;
    
    for (file = 0; file < fileCount; ++file)
        pm_close(pam[file].file);
}



static void
assembleRow(tuple              outputRow[], 
            struct pam         inpam[], 
            unsigned int const fileCount,
            unsigned int const hOverlap) {
/*----------------------------------------------------------------------------
   Assemble the row outputRow[] from the 'fileCount' input files
   described out inpam[].

   'hOverlap', which is meaningful only when fileCount is greater than 1,
   is the amount by which files overlap each other.  We assume every
   input image is at least that wide.

   We assume that outputRow[] is allocated wide enough to contain the
   entire assembly.
-----------------------------------------------------------------------------*/
    tuple * inputRow;
    unsigned int file;

    for (file = 0, inputRow = &outputRow[0]; 
         file < fileCount; 
         ++file) {

        unsigned int const overlap = file == fileCount - 1 ? 0 : hOverlap;

        assert(hOverlap <= inpam[file].width);

        pnm_readpamrow(&inpam[file], inputRow);

        inputRow += inpam[file].width - overlap;
    }
}



static void
allocInpam(unsigned int  const rankCount,
           struct pam ** const inpamArrayP) {

    struct pam * inpamArray;

    MALLOCARRAY(inpamArray, rankCount);

    if (inpamArray == NULL)
        pm_error("Unable to allocate array for %u input pam structures.",
                 rankCount);

    *inpamArrayP = inpamArray;
}



static void
verifyRankFileAttributes(struct pam *       const inpam,
                         unsigned int       const nFile,
                         const struct pam * const outpamP,
                         unsigned int       const hoverlap,
                         unsigned int       const rank) {
/*----------------------------------------------------------------------------
   Verify that the 'nFile' images that make up a rank, which are described
   by inpam[], are consistent with the properties of the assembled image
   *outpamP.

   I.e. verify that each image has the depth, maxval, format, and tuple
   type of *outpamP and their total width is the width given by
   *outpamP.

   Also verify that every image has the same height.

   Abort the program if verification fails.
-----------------------------------------------------------------------------*/
    unsigned int file;
    unsigned int totalWidth;

    for (file = 0, totalWidth = 0; file < nFile; ++file) {
        struct pam * const inpamP = &inpam[file];

        if (inpamP->depth != outpamP->depth)
            pm_error("Rank %u, File %u image has depth %u, "
                     "which differs from others (%u)",
                     rank, file, inpamP->depth, outpamP->depth);
        else if (inpamP->maxval != outpamP->maxval)
            pm_error("Rank %u, File %u image has maxval %lu, "
                     "which differs from others (%lu)",
                     rank, file, inpamP->maxval, outpamP->maxval);
        else if (inpamP->format != outpamP->format)
            pm_error("Rank %u, File %u image has format 0x%x, "
                     "which differs from others (0x%x)",
                     rank, file, inpamP->format, outpamP->format);
        else if (!streq(inpamP->tuple_type, outpamP->tuple_type))
            pm_error("Rank %u, File %u image has tuple type '%s', "
                     "which differs from others ('%s')",
                     rank, file, inpamP->tuple_type, outpamP->tuple_type);

        else if (inpamP->height != inpam[0].height)
            pm_error("Rank %u, File %u image has height %u, "
                     "which differs from that of File 0 in the same rank (%u)",
                     rank, file, inpamP->height, inpam[0].height);
        else {
            totalWidth += inpamP->width;
        
            if (file < nFile-1)
                totalWidth -= hoverlap;
        }
    }

    if (totalWidth != outpamP->width)
        pm_error("Rank %u has a total width (%u) different from that of "
                 "other ranks (%u)", rank, totalWidth, outpamP->width);
}



static void
assembleTiles(struct pam * const outpamP,
              const char * const inputFilePattern,
              unsigned int const nFile,
              unsigned int const nRank,
              unsigned int const hoverlap,
              unsigned int const voverlap,
              struct pam         inpam[],
              tuple *      const tuplerow) {

    unsigned int rank;
        /* Number of the current rank (horizontal slice).  Ranks are numbered
           sequentially starting at 0.
        */
    
    for (rank = 0; rank < nRank; ++rank) {
        unsigned int row;
        unsigned int rankHeight;

        openInStreams(inpam, rank, nFile, inputFilePattern);

        verifyRankFileAttributes(inpam, nFile, outpamP, hoverlap, rank);

        rankHeight = inpam[0].height - (rank == nRank-1 ? 0 : voverlap);

        for (row = 0; row < rankHeight; ++row) {
            assembleRow(tuplerow, inpam, nFile, hoverlap);

            pnm_writepamrow(outpamP, tuplerow);
        }
        closeInFiles(inpam, nFile);
    }
}



int
main(int argc, char ** argv) {

    struct cmdlineInfo cmdline;
    struct pam outpam;
    struct pam * inpam;
        /* malloc'ed.  inpam[x] is the pam structure that controls the
           current rank of file x. 
        */
    tuple * tuplerow;

    pnm_init(&argc, argv);
    
    parseCommandLine(argc, argv, &cmdline);
        
    allocInpam(cmdline.across, &inpam);

    initOutpam(cmdline.inputFilePattern, cmdline.across, cmdline.down,
               cmdline.hoverlap, cmdline.voverlap, stdout, cmdline.verbose,
               &outpam);
    
    tuplerow = pnm_allocpamrow(&outpam);

    pnm_writepaminit(&outpam);

    assembleTiles(&outpam,
                  cmdline.inputFilePattern, cmdline.across, cmdline.down,
                  cmdline.hoverlap, cmdline.voverlap, inpam, tuplerow);

    pnm_freepamrow(tuplerow);

    free(inpam);

    return 0;
}