about summary refs log tree commit diff
path: root/lib/libpm.c
blob: 115d301c0f939ad9692aba54bd5f0e54b011a4da (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
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
/**************************************************************************
                                  libpm.c
***************************************************************************
  This is the most fundamental Netpbm library.  It contains routines
  not specific to any particular Netpbm format.

  Some of the subroutines in this library are intended and documented
  for use by Netpbm users, but most of them are just used by other
  Netpbm library subroutines.

  Before May 2001, this function was served by the libpbm library
  (in addition to being the library for handling the PBM format).

**************************************************************************/
#define _SVID_SOURCE
    /* Make sure P_tmpdir is defined in GNU libc 2.0.7 (_XOPEN_SOURCE 500
       does it in other libc's).  pm_config.h defines TMPDIR as P_tmpdir
       in some environments.
    */
#define _XOPEN_SOURCE 500    /* Make sure ftello, fseeko are defined */
#define _LARGEFILE_SOURCE 1  /* Make sure ftello, fseeko are defined */
#define _LARGEFILE64_SOURCE 1 
#define _FILE_OFFSET_BITS 64
    /* This means ftello() is really ftello64() and returns a 64 bit file
       position.  Unless the C library doesn't have ftello64(), in which 
       case ftello() is still just ftello().

       Likewise for all the other C library file functions.

       And off_t and fpos_t are 64 bit types instead of 32.  Consequently,
       pm_filepos_t might be 64 bits instead of 32.
    */
#define _LARGE_FILES  
    /* This does for AIX what _FILE_OFFSET_BITS=64 does for GNU */
#define _LARGE_FILE_API
    /* This makes the the x64() functions available on AIX */

#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <setjmp.h>
#ifdef __DJGPP__
  #include <io.h>
#endif
#include <time.h>

#include "pm_c_util.h"
#include "version.h"
#include "compile.h"
#include "nstring.h"
#include "shhopt.h"
#include "mallocvar.h"
#include "pm.h"

/* The following are set by pm_init(), then used by subsequent calls to other
   pm_xxx() functions.
   */
static const char * pm_progname;
static bool pm_showmessages;  
    /* Programs should display informational messages (because the user didn't
       specify the --quiet option).
    */

int pm_plain_output;
    /* Boolean: programs should produce output in plain format */

static jmp_buf * pm_jmpbufP = NULL;
    /* A description of the point to which the program should hyperjump
       if a libnetpbm function encounters an error (libnetpbm functions
       don't normally return in that case).

       User sets this to something in his own extra-library context.
       Libnetpbm routines that have something that needs to be cleaned up
       preempt it.

       NULL, which is the default value, means when a libnetpbm function
       encounters an error, it causes the process to exit.
    */
static pm_usererrormsgfn * userErrorMsgFn = NULL;
    /* A function to call to issue an error message.

       NULL means use the library default: print to Standard Error
    */

static pm_usermessagefn * userMessageFn = NULL;
    /* A function to call to issue an error message.

       NULL means use the library default: print to Standard Error
    */



void
pm_setjmpbuf(jmp_buf * const jmpbufP) {
    pm_jmpbufP = jmpbufP;
}



void
pm_setjmpbufsave(jmp_buf *  const jmpbufP,
                 jmp_buf ** const oldJmpbufPP) {

    *oldJmpbufPP = pm_jmpbufP;
    pm_jmpbufP = jmpbufP;
}



void
pm_longjmp(void) {

    if (pm_jmpbufP)
        longjmp(*pm_jmpbufP, 1);
    else
        exit(1);
}



void
pm_setusererrormsgfn(pm_usererrormsgfn * fn) {

    userErrorMsgFn = fn;
}



void
pm_setusermessagefn(pm_usermessagefn * fn) {

    userMessageFn = fn;
}



void
pm_usage(const char usage[]) {
    pm_error("usage:  %s %s", pm_progname, usage);
}



void PM_GNU_PRINTF_ATTR(1,2)
pm_message(const char format[], ...) {

    va_list args;

    va_start(args, format);

    if (pm_showmessages) {
        const char * msg;
        vasprintfN(&msg, format, args);

        if (userMessageFn)
            userMessageFn(msg);
        else
            fprintf(stderr, "%s: %s\n", pm_progname, msg);

        strfree(msg);
    }
    va_end(args);
}



static void
errormsg(const char * const msg) {

    if (userErrorMsgFn)
        userErrorMsgFn(msg);
    else
        fprintf(stderr, "%s: %s\n", pm_progname, msg);
}



void PM_GNU_PRINTF_ATTR(1,2)
pm_errormsg(const char format[], ...) {

    va_list args;
    const char * msg;

    va_start(args, format);

    vasprintfN(&msg, format, args);
    
    errormsg(msg);

    strfree(msg);

    va_end(args);
}



void PM_GNU_PRINTF_ATTR(1,2)
pm_error(const char format[], ...) {
    va_list args;
    const char * msg;

    va_start(args, format);

    vasprintfN(&msg, format, args);
    
    errormsg(msg);

    strfree(msg);

    va_end(args);

    pm_longjmp();
}


/* Variable-sized arrays. */

char *
pm_allocrow(unsigned int const cols,
            unsigned int const size) {

    char * itrow;

    if (UINT_MAX / cols < size)
        pm_error("Arithmetic overflow multiplying %u by %u to get the "
                 "size of a row to allocate.", cols, size);

    itrow = malloc(cols * size);
    if (itrow == NULL)
        pm_error("out of memory allocating a row");

    return itrow;
}



void
pm_freerow(char * const itrow) {
    free(itrow);
}



static void
allocarrayNoHeap(unsigned char ** const rowIndex,
                 unsigned int     const cols,
                 unsigned int     const rows,
                 unsigned int     const size,
                 const char **    const errorP) {

    if (UINT_MAX / cols < size)
        asprintfN(errorP,
                  "Arithmetic overflow multiplying %u by %u to get the "
                  "size of a row to allocate.", cols, size);
    else {
        unsigned int rowsDone;

        rowsDone = 0;
        *errorP = NULL;

        while (rowsDone < rows && !*errorP) {
            unsigned char * const rowSpace = malloc(cols * size);
            if (rowSpace == NULL)
                asprintfN(errorP,
                          "Unable to allocate a %u-column by %u byte row",
                          cols, size);
            else
                rowIndex[rowsDone++] = rowSpace;
        }
        if (*errorP) {
            unsigned int row;
            for (row = 0; row < rowsDone; ++row)
                free(rowIndex[row]);
        }
    }
}



static unsigned char *
allocRowHeap(unsigned int const cols,
             unsigned int const rows,
             unsigned int const size) {

    unsigned char * retval;

    if (UINT_MAX / cols / rows < size)
        /* Too big even to request the memory ! */
        retval = NULL;
    else
        retval = malloc(rows * cols * size);

    return retval;
}



char **
pm_allocarray(int const cols,
              int const rows,
              int const size )  {
/*----------------------------------------------------------------------------
   Allocate an array of 'rows' rows of 'cols' columns each, with each
   element 'size' bytes.

   We use a special format where we tack on an extra element to the row
   index to indicate the format of the array.

   We have two ways of allocating the space: fragmented and
   unfragmented.  In both, the row index (plus the extra element) is
   in one block of memory.  In the fragmented format, each row is
   also in an independent memory block, and the extra row pointer is
   NULL.  In the unfragmented format, all the rows are in a single
   block of memory called the row heap and the extra row pointer is
   the address of that block.

   We use unfragmented format if possible, but if the allocation of the
   row heap fails, we fall back to fragmented.
-----------------------------------------------------------------------------*/
    unsigned char ** rowIndex;
    const char * error;

    MALLOCARRAY(rowIndex, rows + 1);
    if (rowIndex == NULL)
        asprintfN(&error,
                  "out of memory allocating row index (%u rows) for an array",
                  rows);
    else {
        unsigned char * rowheap;

        rowheap = allocRowHeap(cols, rows, size);

        if (rowheap) {
            /* It's unfragmented format */

            rowIndex[rows] = rowheap;  /* Declare it unfragmented format */

            if (rowheap) {
                unsigned int row;
                
                for (row = 0; row < rows; ++row)
                    rowIndex[row] = &(rowheap[row * cols * size]);
            }
            error = NULL;
        } else {
            /* We couldn't get the whole heap in one block, so try fragmented
               format.
            */
            rowIndex[rows] = NULL;   /* Declare it fragmented format */
            
            allocarrayNoHeap(rowIndex, cols, rows, size, &error);
        }
    }
    if (error) {
        pm_errormsg("Couldn't allocate %u-row array.  %s", rows, error);
        strfree(error);
        pm_longjmp();
    }
    return (char **)rowIndex;
}



void
pm_freearray(char ** const rowIndex, 
             int     const rows) {

    void * const rowheap = rowIndex[rows];

    if (rowheap != NULL)
        free(rowheap);
    else {
        unsigned int row;
        for (row = 0; row < rows; ++row)
            pm_freerow(rowIndex[row]);
    }
    free(rowIndex);
}



/* Case-insensitive keyword matcher. */

int
pm_keymatch(char *       const strarg, 
            const char * const keywordarg, 
            int          const minchars) {
    int len;
    const char *keyword;
    char *str;

    str = strarg;
    keyword = keywordarg;

    len = strlen( str );
    if ( len < minchars )
        return 0;
    while ( --len >= 0 )
        {
        register char c1, c2;

        c1 = *str++;
        c2 = *keyword++;
        if ( c2 == '\0' )
            return 0;
        if ( ISUPPER( c1 ) )
            c1 = tolower( c1 );
        if ( ISUPPER( c2 ) )
            c2 = tolower( c2 );
        if ( c1 != c2 )
            return 0;
        }
    return 1;
}


/* Log base two hacks. */

int
pm_maxvaltobits(int const maxval) {
    if ( maxval <= 1 )
        return 1;
    else if ( maxval <= 3 )
        return 2;
    else if ( maxval <= 7 )
        return 3;
    else if ( maxval <= 15 )
        return 4;
    else if ( maxval <= 31 )
        return 5;
    else if ( maxval <= 63 )
        return 6;
    else if ( maxval <= 127 )
        return 7;
    else if ( maxval <= 255 )
        return 8;
    else if ( maxval <= 511 )
        return 9;
    else if ( maxval <= 1023 )
        return 10;
    else if ( maxval <= 2047 )
        return 11;
    else if ( maxval <= 4095 )
        return 12;
    else if ( maxval <= 8191 )
        return 13;
    else if ( maxval <= 16383 )
        return 14;
    else if ( maxval <= 32767 )
        return 15;
    else if ( (long) maxval <= 65535L )
        return 16;
    else
        pm_error( "maxval of %d is too large!", maxval );
        return -1;  /* Should never come here */
}

int
pm_bitstomaxval(int const bits) {
    return ( 1 << bits ) - 1;
}


unsigned int PURE_FN_ATTR
pm_lcm(unsigned int const x, 
       unsigned int const y,
       unsigned int const z,
       unsigned int const limit) {
/*----------------------------------------------------------------------------
  Compute the least common multiple of 'x', 'y', and 'z'.  If it's bigger than
  'limit', though, just return 'limit'.
-----------------------------------------------------------------------------*/
    unsigned int biggest;
    unsigned int candidate;

    if (x == 0 || y == 0 || z == 0)
        pm_error("pm_lcm(): Least common multiple of zero taken.");

    biggest = MAX(x, MAX(y,z));

    candidate = biggest;
    while (((candidate % x) != 0 ||       /* not a multiple of x */
            (candidate % y) != 0 ||       /* not a multiple of y */
            (candidate % z) != 0 ) &&     /* not a multiple of z */
           candidate <= limit)
        candidate += biggest;

    if (candidate > limit) 
        candidate = limit;

    return candidate;
}


/* Initialization. */


#ifdef VMS
static const char *
vmsProgname(int * const argcP, char * argv[]) {   
    char **temp_argv = argv;
    int old_argc = *argcP;
    int i;
    const char * retval;
    
    getredirection( argcP, &temp_argv );
    if (*argcP > old_argc) {
        /* Number of command line arguments has increased */
        fprintf( stderr, "Sorry!! getredirection() for VMS has "
                 "changed the argument list!!!\n");
        fprintf( stderr, "This is intolerable at the present time, "
                 "so we must stop!!!\n");
        exit(1);
    }
    for (i=0; i<*argcP; i++)
        argv[i] = temp_argv[i];
    retval = strrchr( argv[0], '/');
    if ( retval == NULL ) retval = rindex( argv[0], ']');
    if ( retval == NULL ) retval = rindex( argv[0], '>');

    return retval;
}
#endif



void
pm_init(const char * const progname, unsigned int const flags) {
/*----------------------------------------------------------------------------
   Initialize static variables that Netpbm library routines use.

   Any user of Netpbm library routines is expected to call this at the
   beginning of this program, before any other Netpbm library routines.

   A program may call this via pm_proginit() instead, though.
-----------------------------------------------------------------------------*/
    pm_setMessage(FALSE, NULL);

    pm_progname = progname;

#ifdef O_BINARY
#ifdef HAVE_SETMODE
    /* Set the stdin and stdout mode to binary.  This means nothing on Unix,
       but matters on Windows.
       
       Note that stdin and stdout aren't necessarily image files.  In
       particular, stdout is sometimes text for human consumption,
       typically printed on the terminal.  Binary mode isn't really
       appropriate for that case.  We do this setting here without
       any knowledge of how stdin and stdout are being used because it is
       easy.  But we do make an exception for the case that we know the
       file is a terminal, to get a little closer to doing the right
       thing.  
    */
    if (!isatty(0)) setmode(0,O_BINARY);  /* Standard Input */
    if (!isatty(1)) setmode(1,O_BINARY);  /* Standard Output */
#endif /* HAVE_SETMODE */
#endif /* O_BINARY */
}



static void
showVersion(void) {
    pm_message( "Using libnetpbm from Netpbm Version: %s", NETPBM_VERSION );
#if defined(COMPILE_TIME) && defined(COMPILED_BY)
    pm_message( "Compiled %s by user \"%s\"",
                COMPILE_TIME, COMPILED_BY );
#endif
#ifdef BSD
    pm_message( "BSD defined" );
#endif /*BSD*/
#ifdef SYSV
#ifdef VMS
    pm_message( "VMS & SYSV defined" );
#else
    pm_message( "SYSV defined" );
#endif
#endif /*SYSV*/
#ifdef MSDOS
    pm_message( "MSDOS defined" );
#endif /*MSDOS*/
#ifdef AMIGA
    pm_message( "AMIGA defined" );
#endif /* AMIGA */
    {
        const char * rgbdef;
        pm_message( "RGB_ENV='%s'", RGBENV );
        rgbdef = getenv(RGBENV);
        if( rgbdef )
            pm_message( "RGBENV= '%s' (env vbl set to '%s')", 
                        RGBENV, rgbdef );
        else
            pm_message( "RGBENV= '%s' (env vbl is unset)", RGBENV);
    }
}



static void
showNetpbmHelp(const char progname[]) {
/*----------------------------------------------------------------------------
  Tell the user where to get help for this program, assuming it is a Netpbm
  program (a program that comes with the Netpbm package, as opposed to a 
  program that just uses the Netpbm libraries).

  Tell him to go to the URL listed in the Netpbm configuration file.
  The Netpbm configuration file is the file named by the NETPBM_CONF
  environment variable, or /etc/netpbm if there is no such environment
  variable.

  If the configuration file doesn't exist or can't be read, or doesn't
  contain a DOCURL value, tell him to go to a hardcoded source for
  documentation.
-----------------------------------------------------------------------------*/
    const char * netpbmConfigFileName;
    FILE * netpbmConfigFile;
    char * docurl;

    if (getenv("NETPBM_CONF"))
        netpbmConfigFileName = getenv("NETPBM_CONF");
    else 
        netpbmConfigFileName = "/etc/netpbm";
    
    netpbmConfigFile = fopen(netpbmConfigFileName, "r");
    if (netpbmConfigFile == NULL) {
        pm_message("Unable to open Netpbm configuration file '%s'.  "
                   "Errno = %d (%s).  "
                   "Use the NETPBM_CONF environment variable "
                   "to control the identity of the Netpbm configuration file.",
                   netpbmConfigFileName,errno, strerror(errno));
        docurl = NULL;
    } else {
        docurl = NULL;  /* default */
        while (!feof(netpbmConfigFile) && !ferror(netpbmConfigFile)) {
            char line[80+1];
            fgets(line, sizeof(line), netpbmConfigFile);
            if (line[0] != '#') {
                sscanf(line, "docurl=%s", docurl);
            }
        }
        if (docurl == NULL)
            pm_message("No 'docurl=' line in Netpbm configuration file '%s'.",
                       netpbmConfigFileName);
    }
    if (docurl == NULL)
        pm_message("We have no reliable indication of where the Netpbm "
                   "documentation is, but try "
                   "http://netpbm.sourceforge.net or email "
                   "Bryan Henderson (bryanh@giraffe-data.com) for help.");
    else
        pm_message("This program is part of the Netpbm package.  Find "
                   "documentation for it at %s/%s\n", docurl, progname);
}



void
pm_proginit(int * const argcP, char * argv[]) {
/*----------------------------------------------------------------------------
   Do various initialization things that all programs in the Netpbm package,
   and programs that emulate such programs, should do.

   This includes processing global options.

   This includes calling pm_init() to initialize the Netpbm libraries.
-----------------------------------------------------------------------------*/
    int argn, i;
    const char * progname;
    bool showmessages;
    bool show_version;
        /* We're supposed to just show the version information, then exit the
           program.
        */
    bool show_help;
        /* We're supposed to just tell user where to get help, then exit the
           program.
        */
    
    /* Extract program name. */
#ifdef VMS
    progname = vmsProgname(argcP, argv);
#else
    progname = strrchr( argv[0], '/');
#endif
    if (progname == NULL)
        progname = argv[0];
    else
        ++progname;

    pm_init(progname, 0);

    /* Check for any global args. */
    showmessages = TRUE;
    show_version = FALSE;
    show_help = FALSE;
    pm_plain_output = FALSE;
    for (argn = 1; argn < *argcP; ++argn) {
        if (pm_keymatch(argv[argn], "-quiet", 6) ||
            pm_keymatch(argv[argn], "--quiet", 7)) 
            showmessages = FALSE;
        else if (pm_keymatch(argv[argn], "-version", 8) ||
                   pm_keymatch(argv[argn], "--version", 9)) 
            show_version = TRUE;
        else if (pm_keymatch(argv[argn], "-help", 5) ||
                 pm_keymatch(argv[argn], "--help", 6) ||
                 pm_keymatch(argv[argn], "-?", 2)) 
            show_help = TRUE;
        else if (pm_keymatch(argv[argn], "-plain", 6) ||
                 pm_keymatch(argv[argn], "--plain", 7))
            pm_plain_output = TRUE;
        else
            continue;
        for (i = argn + 1; i <= *argcP; ++i)
            argv[i - 1] = argv[i];
        --(*argcP);
    }

    pm_setMessage((unsigned int) showmessages, NULL);

    if (show_version) {
        showVersion();
        exit( 0 );
    } else if (show_help) {
        pm_error("Use 'man %s' for help.", progname);
        /* If we can figure out a way to distinguish Netpbm programs from 
           other programs using the Netpbm libraries, we can do better here.
        */
        if (0)
            showNetpbmHelp(progname);
        exit(0);
    }
}


void
pm_setMessage(int const newState, int * const oldStateP) {
    
    if (oldStateP)
        *oldStateP = pm_showmessages;

    pm_showmessages = !!newState;
}


char *
pm_arg0toprogname(const char arg0[]) {
/*----------------------------------------------------------------------------
   Given a value for argv[0] (a command name or file name passed to a 
   program in the standard C calling sequence), return the name of the
   Netpbm program to which is refers.

   In the most ordinary case, this is simply the argument itself.

   But if the argument contains a slash, it is the part of the argument 
   after the last slash, and if there is a .exe on it (as there is for
   DJGPP), that is removed.

   The return value is in static storage within.  It is null-terminated,
   but truncated at 64 characters.
-----------------------------------------------------------------------------*/
    static char retval[64+1];
    char *slash_pos;

    /* Chop any directories off the left end */
    slash_pos = strrchr(arg0, '/');

    if (slash_pos == NULL) {
        strncpy(retval, arg0, sizeof(retval));
        retval[sizeof(retval)-1] = '\0';
    } else {
        strncpy(retval, slash_pos +1, sizeof(retval));
        retval[sizeof(retval)-1] = '\0';
    }

    /* Chop any .exe off the right end */
    if (strlen(retval) >= 4 && strcmp(retval+strlen(retval)-4, ".exe") == 0)
        retval[strlen(retval)-4] = 0;

    return(retval);
}



unsigned int
pm_randseed(void) {

    return time(NULL) ^ getpid();

}



/* File open/close that handles "-" as stdin/stdout and checks errors. */

FILE*
pm_openr(const char * const name) {
    FILE* f;

    if (strcmp(name, "-") == 0)
        f = stdin;
    else {
#ifndef VMS
        f = fopen(name, "rb");
#else
        f = fopen(name, "r", "ctx=stm");
#endif
        if (f == NULL) 
            pm_error("Unable to open file '%s' for reading.  "
                     "fopen() returns errno %d (%s)", 
                     name, errno, strerror(errno));
    }
    return f;
}



FILE*
pm_openw(const char * const name) {
    FILE* f;

    if (strcmp(name, "-") == 0)
        f = stdout;
    else {
#ifndef VMS
        f = fopen(name, "wb");
#else
        f = fopen(name, "w", "mbc=32", "mbf=2");  /* set buffer factors */
#endif
        if (f == NULL) 
            pm_error("Unable to open file '%s' for writing.  "
                     "fopen() returns errno %d (%s)", 
                     name, errno, strerror(errno));
    }
    return f;
}



static const char *
tmpDir(void) {
/*----------------------------------------------------------------------------
   Return the name of the directory in which we should create temporary
   files.

   The name is a constant in static storage.
-----------------------------------------------------------------------------*/
    const char * tmpdir;
        /* running approximation of the result */

    tmpdir = getenv("TMPDIR");   /* Unix convention */

    if (!tmpdir || strlen(tmpdir) == 0)
        tmpdir = getenv("TMP");  /* Windows convention */

    if (!tmpdir || strlen(tmpdir) == 0)
        tmpdir = getenv("TEMP"); /* Windows convention */

    if (!tmpdir || strlen(tmpdir) == 0)
        tmpdir = TMPDIR;

    return tmpdir;
}



static int
mkstempx(char * const filenameBuffer) {
/*----------------------------------------------------------------------------
  This is meant to be equivalent to POSIX mkstemp().

  On some old systems, mktemp() is a security hazard that allows a hacker
  to read or write our temporary file or cause us to read or write some
  unintended file.  On other systems, mkstemp() does not exist.

  A Windows/mingw environment is one which doesn't have mkstemp()
  (2006.06.15).

  We assume that if a system doesn't have mkstemp() that its mktemp()
  is safe, or that the total situation is such that the problems of
  mktemp() are not a problem for the user.
-----------------------------------------------------------------------------*/
    int retval;
    int fd;
    unsigned int attempts;
    bool gotFile;
    bool error;

    for (attempts = 0, gotFile = FALSE, error = FALSE;
         !gotFile && !error && attempts < 100;
         ++attempts) {

        char * rc;
        rc = mktemp(filenameBuffer);

        if (rc == NULL)
            error = TRUE;
        else {
            int rc;

            rc = open(filenameBuffer, O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);

            if (rc == 0) {
                fd = rc;
                gotFile = TRUE;
            } else {
                if (errno == EEXIST) {
                    /* We'll just have to keep trying */
                } else 
                    error = TRUE;
            }
        }
    }    
    if (gotFile)
        retval = fd;
    else
        retval = -1;

    return retval;
}



static int
mkstemp2(char * const filenameBuffer) {

#if HAVE_MKSTEMP
    if (0)
        mkstempx(NULL);  /* defeat compiler unused function warning */
    return mkstemp(filenameBuffer);
#else
    return mkstempx(filenameBuffer);
#endif
}



static void
makeTmpfileWithTemplate(const char *  const filenameTemplate,
                        FILE **       const filePP,
                        const char ** const filenameP,
                        const char ** const errorP) {
    
    char * filenameBuffer;  /* malloc'ed */

    filenameBuffer = strdup(filenameTemplate);

    if (filenameBuffer == NULL)
        asprintfN(errorP, "Unable to allocate storage for temporary "
                  "file name");
    else {
        int rc;
        
        rc = mkstemp2(filenameBuffer);
        
        if (rc < 0)
            asprintfN(errorP,
                      "Unable to create temporary file according to name "
                      "pattern '%s'.  mkstemp() failed with errno %d (%s)",
                      filenameTemplate, errno, strerror(errno));
        else {
            int const fd = rc;
            
            FILE * fileP;
            fileP = fdopen(fd, "w+b");
            
            if (fileP == NULL)
                asprintfN(errorP, "Unable to create temporary file.  "
                          "fdopen() failed with errno %d (%s)",
                          errno, strerror(errno));
            else {
                *errorP = NULL;
                *filePP = fileP;
                *filenameP = filenameBuffer;
            }
            if (*errorP) {
                unlink(filenameBuffer);
                close(fd);
            }
        }
        if (*errorP)
            strfree(filenameBuffer);
    }
}



void
pm_make_tmpfile(FILE **       const filePP,
                const char ** const filenameP) {

    const char * filenameTemplate;
    unsigned int fnamelen;
    const char * tmpdir;
    const char * dirseparator;
    const char * error;

    fnamelen = strlen(pm_progname) + 10; /* "/" + "_XXXXXX\0" */

    tmpdir = tmpDir();

    if (tmpdir[strlen(tmpdir) - 1] == '/')
        dirseparator = "";
    else
        dirseparator = "/";
    
    asprintfN(&filenameTemplate, "%s%s%s%s", 
              tmpdir, dirseparator, pm_progname, "_XXXXXX");

    if (filenameTemplate == NULL)
        asprintfN(&error,
                  "Unable to allocate storage for temporary file name");
    else {
        makeTmpfileWithTemplate(filenameTemplate, filePP, filenameP, &error);

        strfree(filenameTemplate);
    }
    if (error) {
        pm_errormsg("%s", error);
        strfree(error);
        pm_longjmp();
    }
}



FILE * 
pm_tmpfile(void) {

    FILE * fileP;
    const char * tmpfile;

    pm_make_tmpfile(&fileP, &tmpfile);

    unlink(tmpfile);

    strfree(tmpfile);

    return fileP;
}



FILE *
pm_openr_seekable(const char name[]) {
/*----------------------------------------------------------------------------
  Open the file named by name[] such that it is seekable (i.e. it can be
  rewound and read in multiple passes with fseek()).

  If the file is actually seekable, this reduces to the same as
  pm_openr().  If not, we copy the named file to a temporary file
  and return that file's stream descriptor.

  We use a file that the operating system recognizes as temporary, so
  it picks the filename and deletes the file when Caller closes it.
-----------------------------------------------------------------------------*/
    int stat_rc;
    int seekable;  /* logical: file is seekable */
    struct stat statbuf;
    FILE * original_file;
    FILE * seekable_file;

    original_file = pm_openr((char *) name);

    /* I would use fseek() to determine if the file is seekable and 
       be a little more general than checking the type of file, but I
       don't have reliable information on how to do that.  I have seen
       streams be partially seekable -- you can, for example seek to
       0 if the file is positioned at 0 but you can't actually back up
       to 0.  I have seen documentation that says the errno for an
       unseekable stream is EBADF and in practice seen ESPIPE.

       On the other hand, regular files are always seekable and even if
       some other file is, it doesn't hurt much to assume it isn't.
    */

    stat_rc = fstat(fileno(original_file), &statbuf);
    if (stat_rc == 0 && S_ISREG(statbuf.st_mode))
        seekable = TRUE;
    else 
        seekable = FALSE;

    if (seekable) {
        seekable_file = original_file;
    } else {
        seekable_file = pm_tmpfile();
        
        /* Copy the input into the temporary seekable file */
        while (!feof(original_file) && !ferror(original_file) 
               && !ferror(seekable_file)) {
            char buffer[4096];
            int bytes_read;
            bytes_read = fread(buffer, 1, sizeof(buffer), original_file);
            fwrite(buffer, 1, bytes_read, seekable_file);
        }
        if (ferror(original_file))
            pm_error("Error reading input file into temporary file.  "
                     "Errno = %s (%d)", strerror(errno), errno);
        if (ferror(seekable_file))
            pm_error("Error writing input into temporary file.  "
                     "Errno = %s (%d)", strerror(errno), errno);
        pm_close(original_file);
        {
            int seek_rc;
            seek_rc = fseek(seekable_file, 0, SEEK_SET);
            if (seek_rc != 0)
                pm_error("fseek() failed to rewind temporary file.  "
                         "Errno = %s (%d)", strerror(errno), errno);
        }
    }
    return seekable_file;
}



void
pm_close(FILE * const f) {
    fflush(f);
    if (ferror(f))
        pm_message("A file read or write error occurred at some point");
    if (f != stdin)
        if (fclose(f) != 0)
            pm_error("close of file failed with errno %d (%s)",
                     errno, strerror(errno));
}



/* The pnmtopng package uses pm_closer() and pm_closew() instead of 
   pm_close(), apparently because the 1999 Pbmplus package has them.
   I don't know what the difference is supposed to be.
*/

void
pm_closer(FILE * const f) {
    pm_close(f);
}



void
pm_closew(FILE * const f) {
    pm_close(f);
}



/* Endian I/O.

   Before Netpbm 10.27 (March 2005), these would return failure on EOF
   or I/O failure.  For backward compatibility, they still have the return
   code, but it is always zero and the routines abort the program in case
   of EOF or I/O failure.  A program that wants to handle failure differently
   must use lower level (C library) interfaces.  But that level of detail
   is uncharacteristic of a Netpbm program; the ease of programming that
   comes with not checking a return code is more Netpbm.

   It is also for historical reasons that these return signed values,
   when clearly unsigned would make more sense.
*/



static void
abortWithReadError(FILE * const ifP) {

    if (feof(ifP))
        pm_error("Unexpected end of input file");
    else
        pm_error("Error (not EOF) reading file.");
}



void
pm_readchar(FILE * const ifP,
            char * const cP) {
    
    int c;

    c = getc(ifP);
    if (c == EOF)
        abortWithReadError(ifP);

    *cP = c;
}



void
pm_writechar(FILE * const ofP,
             char   const c) {

    putc(c, ofP);
}



int
pm_readbigshort(FILE *  const ifP, 
                short * const sP) {
    int c;

    unsigned short s;

    c = getc(ifP);
    if (c == EOF)
        abortWithReadError(ifP);
    s = (c & 0xff) << 8;
    c = getc(ifP);
    if (c == EOF)
        abortWithReadError(ifP);
    s |= c & 0xff;

    *sP = s;

    return 0;
}



int
pm_writebigshort(FILE * const ofP, 
                 short  const s) {

    putc((s >> 8) & 0xff, ofP);
    putc(s & 0xff, ofP);

    return 0;
}



int
pm_readbiglong(FILE * const ifP, 
               long * const lP) {

    int c;
    unsigned long l;

    c = getc(ifP);
    if (c == EOF)
        abortWithReadError(ifP);
    l = c << 24;
    c = getc(ifP);
    if (c == EOF)
        abortWithReadError(ifP);
    l |= c << 16;
    c = getc(ifP);
    if (c == EOF)
        abortWithReadError(ifP);
    l |= c << 8;
    c = getc(ifP);
    if (c == EOF)
        abortWithReadError(ifP);
    l |= c;

    *lP = l;

    return 0;
}



int
pm_writebiglong(FILE * const ofP, 
                long   const l) {

    putc((l >> 24) & 0xff, ofP);
    putc((l >> 16) & 0xff, ofP);
    putc((l >>  8) & 0xff, ofP);
    putc((l >>  0) & 0xff, ofP);

    return 0;
}



int
pm_readlittleshort(FILE *  const ifP, 
                   short * const sP) {
    int c;
    unsigned short s;

    c = getc(ifP);
    if (c == EOF)
        abortWithReadError(ifP);
    s = c & 0xff;

    c = getc(ifP);
    if (c == EOF)
        abortWithReadError(ifP);
    s |= (c & 0xff) << 8;

    *sP = s;

    return 0;
}



int
pm_writelittleshort(FILE * const ofP, 
                    short  const s) {

    putc((s >> 0) & 0xff, ofP);
    putc((s >> 8) & 0xff, ofP);

    return 0;
}



int
pm_readlittlelong(FILE * const ifP, 
                  long * const lP) {
    int c;
    unsigned long l;

    c = getc(ifP);
    if (c == EOF)
        abortWithReadError(ifP);
    l = c;
    c = getc(ifP);
    if (c == EOF)
        abortWithReadError(ifP);
    l |= c << 8;
    c = getc(ifP);
    if (c == EOF)
        abortWithReadError(ifP);
    l |= c << 16;
    c = getc(ifP);
    if (c == EOF)
        abortWithReadError(ifP);
    l |= c << 24;

    *lP = l;

    return 0;
}



int
pm_writelittlelong(FILE * const ofP, 
                   long   const l) {

    putc((l >>  0) & 0xff, ofP);
    putc((l >>  8) & 0xff, ofP);
    putc((l >> 16) & 0xff, ofP);
    putc((l >> 24) & 0xff, ofP);

    return 0;
}



int 
pm_readmagicnumber(FILE * const ifP) {

    int ich1, ich2;

    ich1 = getc(ifP);
    ich2 = getc(ifP);
    if (ich1 == EOF || ich2 == EOF)
        pm_error( "Error reading magic number from Netpbm image stream.  "
                  "Most often, this "
                  "means your input file is empty." );

    return ich1 * 256 + ich2;
}



/* Read a file of unknown size to a buffer. Return the number of bytes
   read. Allocate more memory as we need it. The calling routine has
   to free() the buffer.

   Oliver Trepte, oliver@fysik4.kth.se, 930613 */

#define PM_BUF_SIZE 16384      /* First try this size of the buffer, then
                                  double this until we reach PM_MAX_BUF_INC */
#define PM_MAX_BUF_INC 65536   /* Don't allocate more memory in larger blocks
                                  than this. */

char *
pm_read_unknown_size(FILE * const file, 
                     long * const nread) {
    long nalloc;
    char * buf;
    bool eof;

    *nread = 0;
    nalloc = PM_BUF_SIZE;
    MALLOCARRAY(buf, nalloc);

    eof = FALSE;  /* initial value */

    while(!eof) {
        int val;

        if (*nread >= nalloc) { /* We need a larger buffer */
            if (nalloc > PM_MAX_BUF_INC)
                nalloc += PM_MAX_BUF_INC;
            else
                nalloc += nalloc;
            REALLOCARRAY_NOFAIL(buf, nalloc);
        }

        val = getc(file);
        if (val == EOF)
            eof = TRUE;
        else 
            buf[(*nread)++] = val;
    }
    return buf;
}



union cheat {
    uint32n l;
    short s;
    unsigned char c[4];
};



short
pm_bs_short(short const s) {
    union cheat u;
    unsigned char t;

    u.s = s;
    t = u.c[0];
    u.c[0] = u.c[1];
    u.c[1] = t;
    return u.s;
}



long
pm_bs_long(long const l) {
    union cheat u;
    unsigned char t;

    u.l = l;
    t = u.c[0];
    u.c[0] = u.c[3];
    u.c[3] = t;
    t = u.c[1];
    u.c[1] = u.c[2];
    u.c[2] = t;
    return u.l;
}



void
pm_tell2(FILE *       const fileP, 
         void *       const fileposP,
         unsigned int const fileposSize) {
/*----------------------------------------------------------------------------
   Return the current file position as *filePosP, which is a buffer
   'fileposSize' bytes long.  Abort the program if error, including if
   *fileP isn't a file that has a position.
-----------------------------------------------------------------------------*/
    /* Note: FTELLO() is either ftello() or ftell(), depending on the
       capabilities of the underlying C library.  It is defined in
       pm_config.h.  ftello(), in turn, may be either ftell() or
       ftello64(), as implemented by the C library.
    */
    pm_filepos const filepos = FTELLO(fileP);
    if (filepos < 0)
        pm_error("ftello() to get current file position failed.  "
                 "Errno = %s (%d)\n", strerror(errno), errno);

    if (fileposSize == sizeof(pm_filepos)) {
        pm_filepos * const fileposP_filepos = fileposP;
        *fileposP_filepos = filepos;
    } else if (fileposSize == sizeof(long)) {
        if (sizeof(pm_filepos) > sizeof(long) &&
            filepos >= (pm_filepos) 1 << (sizeof(long)*8))
            pm_error("File size is too large to represent in the %u bytes "
                     "that were provided to pm_tell2()", fileposSize);
        else {
            long * const fileposP_long = fileposP;
            *fileposP_long = (long)filepos;
        }
    } else
        pm_error("File position size passed to pm_tell() is invalid: %u.  "
                 "Valid sizes are %u and %u", 
                 fileposSize, (unsigned int)sizeof(pm_filepos),
                 (unsigned int) sizeof(long));
}



unsigned int
pm_tell(FILE * const fileP) {
    
    long filepos;

    pm_tell2(fileP, &filepos, sizeof(filepos));

    return filepos;
}



void
pm_seek2(FILE *             const fileP, 
         const pm_filepos * const fileposP,
         unsigned int       const fileposSize) {
/*----------------------------------------------------------------------------
   Position file *fileP to position *fileposP.  Abort if error, including
   if *fileP isn't a seekable file.
-----------------------------------------------------------------------------*/
    if (fileposSize == sizeof(pm_filepos)) 
        /* Note: FSEEKO() is either fseeko() or fseek(), depending on the
           capabilities of the underlying C library.  It is defined in
           pm_config.h.  fseeko(), in turn, may be either fseek() or
           fseeko64(), as implemented by the C library.
        */
        FSEEKO(fileP, *fileposP, SEEK_SET);
    else if (fileposSize == sizeof(long)) {
        long const fileposLong = *(long *)fileposP;
        fseek(fileP, fileposLong, SEEK_SET);
    } else
        pm_error("File position size passed to pm_seek() is invalid: %u.  "
                 "Valid sizes are %u and %u", 
                 fileposSize, (unsigned int)sizeof(pm_filepos),
                 (unsigned int) sizeof(long));
}



void
pm_seek(FILE * const fileP, unsigned long filepos) {
/*----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/

    pm_filepos fileposBuff;

    fileposBuff = filepos;

    pm_seek2(fileP, &fileposBuff, sizeof(fileposBuff));
}



void
pm_nextimage(FILE * const file, int * const eofP) {
/*----------------------------------------------------------------------------
   Position the file 'file' to the next image in the stream, assuming it is
   now positioned just after the current image.  I.e. read off any white
   space at the end of the current image's raster.  Note that the raw formats
   don't permit such white space, but this routine tolerates it anyway, 
   because the plain formats do permit white space after the raster.

   Iff there is no next image, return *eofP == TRUE.

   Note that in practice, we will not normally see white space here in
   a plain PPM or plain PGM stream because the routine to read a
   sample from the image reads one character of white space after the
   sample in order to know where the sample ends.  There is not
   normally more than one character of white space (a newline) after
   the last sample in the raster.  But plain PBM is another story.  No white
   space is required between samples of a plain PBM image.  But the raster
   normally ends with a newline nonetheless.  Since the sample reading code
   will not have read that newline, it is there for us to read now.
-----------------------------------------------------------------------------*/
    bool eof;
    bool nonWhitespaceFound;

    eof = FALSE;
    nonWhitespaceFound = FALSE;

    while (!eof && !nonWhitespaceFound) {
        int c;
        c = getc(file);
        if (c == EOF) {
            if (feof(file)) 
                eof = TRUE;
            else
                pm_error("File error on getc() to position to image");
        } else {
            if (!isspace(c)) {
                int rc;

                nonWhitespaceFound = TRUE;

                /* Have to put the non-whitespace character back in
                   the stream -- it's part of the next image.  
                */
                rc = ungetc(c, file);
                if (rc == EOF) 
                    pm_error("File error doing ungetc() "
                             "to position to image.");
            }
        }
    }
    *eofP = eof;
}



void
pm_check(FILE *               const file, 
         enum pm_check_type   const check_type, 
         pm_filepos           const need_raster_size,
         enum pm_check_code * const retval_p) {
/*----------------------------------------------------------------------------
   This is not defined for use outside of libnetpbm.
-----------------------------------------------------------------------------*/
    struct stat statbuf;
    pm_filepos curpos;  /* Current position of file; -1 if none */
    int rc;

#ifdef LARGEFILEDEBUG
    pm_message("pm_filepos received by pm_check() is %u bytes.",
               sizeof(pm_filepos));
#endif
    /* Note: FTELLO() is either ftello() or ftell(), depending on the
       capabilities of the underlying C library.  It is defined in
       pm_config.h.  ftello(), in turn, may be either ftell() or
       ftello64(), as implemented by the C library.
    */
    curpos = FTELLO(file);
    if (curpos >= 0) {
        /* This type of file has a current position */
            
        rc = fstat(fileno(file), &statbuf);
        if (rc != 0) 
            pm_error("fstat() failed to get size of file, though ftello() "
                     "successfully identified\n"
                     "the current position.  Errno=%s (%d)",
                     strerror(errno), errno);
        else if (!S_ISREG(statbuf.st_mode)) {
            /* Not a regular file; we can't know its size */
            if (retval_p) *retval_p = PM_CHECK_UNCHECKABLE;
        } else {
            pm_filepos const have_raster_size = statbuf.st_size - curpos;
            
            if (have_raster_size < need_raster_size)
                pm_error("File has invalid format.  The raster should "
                         "contain %u bytes, but\n"
                         "the file ends after only %u bytes.",
                         (unsigned int) need_raster_size, 
                         (unsigned int) have_raster_size);
            else if (have_raster_size > need_raster_size) {
                if (retval_p) *retval_p = PM_CHECK_TOO_LONG;
            } else {
                if (retval_p) *retval_p = PM_CHECK_OK;
            }
        }
    } else
        if (retval_p) *retval_p = PM_CHECK_UNCHECKABLE;
}



void
pm_drain(FILE *         const fileP,
         unsigned int   const limit,
         unsigned int * const bytesReadP) {
/*----------------------------------------------------------------------------
  Read bytes from *fileP until EOF and return as *bytesReadP how many there
  were.

  But don't read any more than 'limit'.

  This is a good thing to call after reading an input file to be sure you
  didn't leave some input behind, which could mean you didn't properly
  interpret the file.
-----------------------------------------------------------------------------*/
    unsigned int bytesRead;
    bool eof;

    for (bytesRead = 0, eof = false; !eof && bytesRead < 4096;) {

        int rc;

        rc = fgetc(fileP);

        eof = (rc == EOF);
        if (!eof)
            ++bytesRead;
    }
    *bytesReadP = bytesRead;
}