about summary refs log tree commit diff
path: root/converter/other/exif.c
blob: b2a7bd5de9499d095bffcd01d40571b585aff5eb (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
/*--------------------------------------------------------------------------
  This file contains subroutines for use by Jpegtopnm to handle the
  EXIF header.

  The code is adapted from the program Jhead by Matthaias Wandel
  December 1999 - August 2000, and contributed to the public domain.
  Bryan Henderson adapted it to Netpbm in September 2001.  Bryan
  added more of Wandel's code, from Jhead 1.9 dated December 2002 in
  January 2003.

  Bryan fundamentally rewrote it in March 2023 because it wasn't properly
  dealing with the main image vs thumbnail IFDs.
--------------------------------------------------------------------------*/

/*
  N.B. "EXIF" refers to a whole image file format; some people think it is
  just the format of the camera model, orientation, etc. data within the
  image file.  EXIF is a subset of JFIF; an EXIF file is JFIF file
  containing an EXIF header in the form of a JFIF APP1 marker.

  An EXIF header is generated by some digital cameras and contains information
  about the circumstances of the creation of the image (camera settings,
  etc.).

  The EXIF header uses the TIFF format, only it contains only tag values and
  no actual image.

  Note that the image format called EXIF is simply JFIF with an EXIF header,
  i.e. a subformat of JFIF.

  See the EXIF specs at http://exif.org (2001.09.01).

  The basic format of the EXIF header is a sequence of IFDs (directories).  I
  believe the first IFD is always for the main image and the 2nd IFD is for a
  thumbnail image and is not present if there is no thumbnail image in the
  file.

  A directory is a sequence of tag/value pairs.

  Each IFD can contain SubIFD, as the value of an EXIF Offset or Interop
  Offset tag.

*/


#include "pm_config.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <limits.h>
#include <ctype.h>
#include <assert.h>

#if MSVCRT
    #include <sys/utime.h>
#else
    #include <utime.h>
    #include <sys/types.h>
    #include <unistd.h>
    #include <errno.h>
#endif

#include "pm_c_util.h"
#include "pm.h"
#include "mallocvar.h"
#include "nstring.h"

#include "exif.h"



enum Orientation {
    ORIENT_NORMAL,
    ORIENT_FLIP_HORIZ,   /* left right reversed mirror */
    ORIENT_ROTATE_180,   /* upside down */
    ORIENT_FLIP_VERT,    /* upside down mirror */
    ORIENT_TRANSPOSE,    /* Flipped about top-left <--> bottom-right axis*/
    ORIENT_ROTATE_90,    /* rotate 90 cw to right it */
    ORIENT_TRANSVERSE,   /* flipped about top-right <--> bottom-left axis */
    ORIENT_ROTATE_270    /* rotate 270 to right it */
};

typedef struct {
    unsigned short tag;
    const char * desc;
} TagTableEntry;



/* Describes format descriptor */
static int const bytesPerFormat[] = {0,1,1,2,4,8,1,1,2,4,8,4,8};
#define NUM_FORMATS 12

#define FMT_BYTE       1
#define FMT_STRING     2
#define FMT_USHORT     3
#define FMT_ULONG      4
#define FMT_URATIONAL  5
#define FMT_SBYTE      6
#define FMT_UNDEFINED  7
#define FMT_SSHORT     8
#define FMT_SLONG      9
#define FMT_SRATIONAL 10
#define FMT_SINGLE    11
#define FMT_DOUBLE    12

/* Describes tag values */

#define TAG_EXIF_OFFSET       0x8769
#define TAG_INTEROP_OFFSET    0xa005

#define TAG_MAKE              0x010F
#define TAG_MODEL             0x0110

#define TAG_ORIENTATION       0x0112

#define TAG_XRESOLUTION       0x011A
#define TAG_YRESOLUTION       0x011B

#define TAG_EXPOSURETIME      0x829A
#define TAG_FNUMBER           0x829D

#define TAG_SHUTTERSPEED      0x9201
#define TAG_APERTURE          0x9202
#define TAG_MAXAPERTURE       0x9205
#define TAG_FOCALLENGTH       0x920A

#define TAG_DATETIME_ORIGINAL 0x9003
#define TAG_USERCOMMENT       0x9286

#define TAG_SUBJECT_DISTANCE  0x9206
#define TAG_FLASH             0x9209

#define TAG_FOCALPLANEXRES    0xa20E
#define TAG_FOCALPLANEUNITS   0xa210
#define TAG_EXIF_IMAGEWIDTH   0xA002
#define TAG_EXIF_IMAGELENGTH  0xA003

/* the following is added 05-jan-2001 vcs */
#define TAG_EXPOSURE_BIAS     0x9204
#define TAG_WHITEBALANCE      0x9208
#define TAG_METERING_MODE     0x9207
#define TAG_EXPOSURE_PROGRAM  0x8822
#define TAG_ISO_EQUIVALENT    0x8827
#define TAG_COMPRESSION_LEVEL 0x9102

#define TAG_THUMBNAIL_OFFSET  0x0201
#define TAG_THUMBNAIL_LENGTH  0x0202

static TagTableEntry const tagTable[] = {
  {   0x100,   "ImageWidth"},
  {   0x101,   "ImageLength"},
  {   0x102,   "BitsPerSample"},
  {   0x103,   "Compression"},
  {   0x106,   "PhotometricInterpretation"},
  {   0x10A,   "FillOrder"},
  {   0x10D,   "DocumentName"},
  {   0x10E,   "ImageDescription"},
  {   0x10F,   "Make"},
  {   0x110,   "Model"},
  {   0x111,   "StripOffsets"},
  {   0x112,   "Orientation"},
  {   0x115,   "SamplesPerPixel"},
  {   0x116,   "RowsPerStrip"},
  {   0x117,   "StripByteCounts"},
  {   0x11A,   "XResolution"},
  {   0x11B,   "YResolution"},
  {   0x11C,   "PlanarConfiguration"},
  {   0x128,   "ResolutionUnit"},
  {   0x12D,   "TransferFunction"},
  {   0x131,   "Software"},
  {   0x132,   "DateTime"},
  {   0x13B,   "Artist"},
  {   0x13E,   "WhitePoint"},
  {   0x13F,   "PrimaryChromaticities"},
  {   0x156,   "TransferRange"},
  {   0x200,   "JPEGProc"},
  {   0x201,   "ThumbnailOffset"},
  {   0x202,   "ThumbnailLength"},
  {   0x211,   "YCbCrCoefficients"},
  {   0x212,   "YCbCrSubSampling"},
  {   0x213,   "YCbCrPositioning"},
  {   0x214,   "ReferenceBlackWhite"},
  {   0x828D,  "CFARepeatPatternDim"},
  {   0x828E,  "CFAPattern"},
  {   0x828F,  "BatteryLevel"},
  {   0x8298,  "Copyright"},
  {   0x829A,  "ExposureTime"},
  {   0x829D,  "FNumber"},
  {   0x83BB,  "IPTC/NAA"},
  {   0x8769,  "ExifOffset"},
  {   0x8773,  "InterColorProfile"},
  {   0x8822,  "ExposureProgram"},
  {   0x8824,  "SpectralSensitivity"},
  {   0x8825,  "GPSInfo"},
  {   0x8827,  "ISOSpeedRatings"},
  {   0x8828,  "OECF"},
  {   0x9000,  "ExifVersion"},
  {   0x9003,  "DateTimeOriginal"},
  {   0x9004,  "DateTimeDigitized"},
  {   0x9101,  "ComponentsConfiguration"},
  {   0x9102,  "CompressedBitsPerPixel"},
  {   0x9201,  "ShutterSpeedValue"},
  {   0x9202,  "ApertureValue"},
  {   0x9203,  "BrightnessValue"},
  {   0x9204,  "ExposureBiasValue"},
  {   0x9205,  "MaxApertureValue"},
  {   0x9206,  "SubjectDistance"},
  {   0x9207,  "MeteringMode"},
  {   0x9208,  "LightSource"},
  {   0x9209,  "Flash"},
  {   0x920A,  "FocalLength"},
  {   0x927C,  "MakerNote"},
  {   0x9286,  "UserComment"},
  {   0x9290,  "SubSecTime"},
  {   0x9291,  "SubSecTimeOriginal"},
  {   0x9292,  "SubSecTimeDigitized"},
  {   0xA000,  "FlashPixVersion"},
  {   0xA001,  "ColorSpace"},
  {   0xA002,  "ExifImageWidth"},
  {   0xA003,  "ExifImageLength"},
  {   0xA005,  "InteroperabilityOffset"},
  {   0xA20B,  "FlashEnergy"},                 /* 0x920B in TIFF/EP */
  {   0xA20C,  "SpatialFrequencyResponse"},  /* 0x920C    -  - */
  {   0xA20E,  "FocalPlaneXResolution"},     /* 0x920E    -  - */
  {   0xA20F,  "FocalPlaneYResolution"},      /* 0x920F    -  - */
  {   0xA210,  "FocalPlaneResolutionUnit"},  /* 0x9210    -  - */
  {   0xA214,  "SubjectLocation"},             /* 0x9214    -  - */
  {   0xA215,  "ExposureIndex"},            /* 0x9215    -  - */
  {   0xA217,  "SensingMethod"},            /* 0x9217    -  - */
  {   0xA300,  "FileSource"},
  {   0xA301,  "SceneType"},
  {      0, NULL}
} ;



typedef enum { ORDER_NORMAL, ORDER_MOTOROLA } ByteOrder;



static uint16_t
get16u(const void * const data,
       ByteOrder    const byteOrder) {
/*--------------------------------------------------------------------------
   Convert a 16 bit unsigned value from file's native byte order
--------------------------------------------------------------------------*/
    if (byteOrder == ORDER_MOTOROLA) {
        return (((const unsigned char *)data)[0] << 8) |
            ((const unsigned char *)data)[1];
    } else {
        return (((const unsigned char *)data)[1] << 8) |
            ((const unsigned char *)data)[0];
    }
}



static int32_t
get32s(const void * const data,
       ByteOrder    const byteOrder) {
/*--------------------------------------------------------------------------
   Convert a 32 bit signed value from file's native byte order
--------------------------------------------------------------------------*/
    if (byteOrder == ORDER_MOTOROLA) {
        return
            (((const char *)data)[0] << 24) |
            (((const unsigned char *)data)[1] << 16) |
            (((const unsigned char *)data)[2] << 8 ) |
            (((const unsigned char *)data)[3] << 0 );
    } else {
        return
            (((const char *)data)[3] << 24) |
            (((const unsigned char *)data)[2] << 16) |
            (((const unsigned char *)data)[1] << 8 ) |
            (((const unsigned char *)data)[0] << 0 );
    }
}



static uint32_t
get32u(const void * const data,
       ByteOrder    const byteOrder) {
/*--------------------------------------------------------------------------
   Convert a 32 bit unsigned value from file's native byte order
--------------------------------------------------------------------------*/
    return (uint32_t)get32s(data, byteOrder) & 0xffffffff;
}



static const char *
numberTraceValue(const void * const valueP,
                 int          const format,
                 unsigned int const byteCt,
                 ByteOrder    const byteOrder) {
/*--------------------------------------------------------------------------
   Format for display a number represented in any of the numeric formats
--------------------------------------------------------------------------*/
    const char * retval;

    switch(format) {
    case FMT_SBYTE:
    case FMT_BYTE:
        pm_asprintf(&retval, "%02x", *(unsigned char *)valueP);
        break;
    case FMT_USHORT:
        pm_asprintf(&retval, "%d",get16u(valueP, byteOrder));
        break;
    case FMT_ULONG:
    case FMT_SLONG:
        pm_asprintf(&retval, "%d",get32s(valueP, byteOrder));
        break;
    case FMT_SSHORT:
        pm_asprintf(&retval, "%hd",(signed short)get16u(valueP, byteOrder));
        break;
    case FMT_URATIONAL:
    case FMT_SRATIONAL:
        pm_asprintf(&retval, "%d/%d",
                    get32s(valueP, byteOrder),
                    get32s(4+(char *)valueP,
                           byteOrder));
        break;
    case FMT_SINGLE:
        pm_asprintf(&retval, "%f",(double)*(float *)valueP);
        break;
    case FMT_DOUBLE:
        pm_asprintf(&retval, "%f",*(double *)valueP);
        break;
    default: {
        char * hex;

        MALLOCARRAY(hex, byteCt*2 + 1);
        if (!hex)
            retval = pm_strsol;
        else {
            unsigned int i;
            for (i = 0; i < byteCt && i < 16; ++i) {
                sprintf(&hex[i*2], "%02x",
                        ((const unsigned char *)valueP)[i]);
            }
            pm_asprintf(&retval, "Unknown format %d: %s", format, hex);
        }
    }
    }
    return retval;
}



static double
numericValue(const void * const valuePtr,
             int          const format,
             ByteOrder    const byteOrder) {
/*--------------------------------------------------------------------------
   Evaluate number, be it int, rational, or float from directory.
--------------------------------------------------------------------------*/
    double value;

    switch(format) {
    case FMT_SBYTE:
        value = *(signed char *)valuePtr;
        break;
    case FMT_BYTE:
        value = *(unsigned char *)valuePtr;
        break;
    case FMT_USHORT:
        value = get16u(valuePtr, byteOrder);
        break;
    case FMT_ULONG:
        value = get32u(valuePtr, byteOrder);
        break;
    case FMT_URATIONAL:
    case FMT_SRATIONAL: {
        int num, den;
        num = get32s(valuePtr, byteOrder);
        den = get32s(4+(char *)valuePtr, byteOrder);
        value = den == 0 ? 0 : (double)(num/den);
    } break;
    case FMT_SSHORT:
        value = (signed short)get16u(valuePtr, byteOrder);
        break;
    case FMT_SLONG:
        value = get32s(valuePtr, byteOrder);
        break;

    /* Not sure if this is correct (never seen float used in Exif format) */
    case FMT_SINGLE:
        value = (double)*(float *)valuePtr;
        break;
    case FMT_DOUBLE:
        value = *(double *)valuePtr;
        break;
    }
    return value;
}



static const char *
stringTraceValue(const unsigned char * const value,
                 unsigned int          const valueSz) {

    const char * retval;
    char * buffer;

    MALLOCARRAY(buffer, valueSz + 1);
    if (!buffer)
        retval = pm_strsol;
    else {
        unsigned int i;
        bool noPrint;
            /* We're in a sequence of unprintable characters.  We put one
               '?' in the value for the whole sequence.
            */
        unsigned int outCursor;

        outCursor = 0;  /* initial value */

        for (i = 0, noPrint = false; i < valueSz; ++i) {
            if (ISPRINT(value[i])) {
                buffer[outCursor++] = value[i];
                noPrint = false;
            } else {
                if (!noPrint) {
                    buffer[outCursor++] = '?';
                    noPrint = true;
                }
            }
        }
        buffer[outCursor++] = '\0';

        retval = buffer;
    }
    return retval;
}



static void
traceTag(int                   const tag,
         int                   const format,
         const unsigned char * const value,
         unsigned int          const valueSz,
         ByteOrder             const byteOrder) {

    const char * tagNm;
    const char * tagValue;
    unsigned int i;

    for (i = 0, tagNm = NULL; tagTable[i].tag; ++i) {
        if (tagTable[i].tag == tag)
            tagNm = pm_strdup(tagTable[i].desc);
    }

    if (!tagNm)
        pm_asprintf(&tagNm, "Unknown Tag %04x", tag);

    /* Show tag value. */
    switch (format) {

    case FMT_UNDEFINED:
        /* Undefined is typically an ascii string. */
    case FMT_STRING: {
        tagValue = stringTraceValue(value, valueSz);
    } break;

    default:
        /* Handle arrays of numbers later (will there ever be?)*/
        tagValue = numberTraceValue(value, format, valueSz, byteOrder);
    }
    pm_message("%s = \"%s\"", tagNm, tagValue);

    pm_strfree(tagValue);
    pm_strfree(tagNm);
}



static void
initializeIfd(exif_ifd * const ifdP) {

    ifdP->cameraMake        = NULL;
    ifdP->cameraModel       = NULL;
    ifdP->dateTime          = NULL;
    ifdP->xResolutionP      = NULL;
    ifdP->yResolutionP      = NULL;
    ifdP->orientationP      = NULL;
    ifdP->isColorP          = NULL;
    ifdP->flashP            = NULL;
    ifdP->focalLengthP      = NULL;
    ifdP->exposureTimeP     = NULL;
    ifdP->shutterSpeedP     = NULL;
    ifdP->apertureFNumberP  = NULL;
    ifdP->distanceP         = NULL;
    ifdP->exposureBiasP     = NULL;
    ifdP->whiteBalanceP     = NULL;
    ifdP->meteringModeP     = NULL;
    ifdP->exposureProgramP  = NULL;
    ifdP->isoEquivalentP    = NULL;
    ifdP->compressionLevelP = NULL;
    ifdP->comments          = NULL;
    ifdP->thumbnailOffsetP  = NULL;
    ifdP->thumbnailLengthP  = NULL;
    ifdP->exifImageLengthP  = NULL;
    ifdP->exifImageWidthP   = NULL;
    ifdP->focalPlaneXResP   = NULL;
    ifdP->focalPlaneUnitsP  = NULL;
    ifdP->thumbnail         = NULL;
}



static void
freeIfPresent(const void * const arg) {

    if (arg)
        free((void *)arg);
}



static void
strfreeIfPresent(const char * const arg) {

    if (arg)
        pm_strfree(arg);
}



static void
terminateIfd(exif_ifd * const ifdP) {

    strfreeIfPresent(ifdP->cameraMake  );
    strfreeIfPresent(ifdP->cameraModel );
    strfreeIfPresent(ifdP->dateTime    );
    strfreeIfPresent(ifdP->comments    );
    freeIfPresent(ifdP->xResolutionP      );
    freeIfPresent(ifdP->yResolutionP      );
    freeIfPresent(ifdP->orientationP      );
    freeIfPresent(ifdP->isColorP          );
    freeIfPresent(ifdP->flashP            );
    freeIfPresent(ifdP->focalLengthP      );
    freeIfPresent(ifdP->exposureTimeP     );
    freeIfPresent(ifdP->shutterSpeedP     );
    freeIfPresent(ifdP->apertureFNumberP  );
    freeIfPresent(ifdP->distanceP         );
    freeIfPresent(ifdP->exposureBiasP     );
    freeIfPresent(ifdP->whiteBalanceP     );
    freeIfPresent(ifdP->meteringModeP     );
    freeIfPresent(ifdP->exposureProgramP  );
    freeIfPresent(ifdP->isoEquivalentP    );
    freeIfPresent(ifdP->compressionLevelP );
    freeIfPresent(ifdP->thumbnailOffsetP  );
    freeIfPresent(ifdP->thumbnailLengthP  );
    freeIfPresent(ifdP->exifImageLengthP  );
    freeIfPresent(ifdP->exifImageWidthP   );
    freeIfPresent(ifdP->focalPlaneXResP   );
    freeIfPresent(ifdP->focalPlaneUnitsP  );
}



static const char *
commentValue(const unsigned char * const valuePtr,
             unsigned int          const valueSz) {

    /* Olympus has this padded with trailing spaces.  We stop the copy
       where those start.
    */
    const char * const value = (const char *)valuePtr;

    const char * retval;
    char * buffer;  /* malloc'ed */
    unsigned int cursor;
    unsigned int end;

    for (end = valueSz; end > 0 && value[end] == ' '; --end);

    /* Skip "ASCII" if it is there */
    if (end >= 5 && memeq(value, "ASCII", 5))
        cursor = 5;
    else
        cursor = 0;

    /* Skip consecutive blanks and NULs */

    for (;
         cursor < valueSz &&
             (value[cursor] == '\0' || value[cursor] == ' ');
         ++cursor);

    /* Copy the rest as the comment */

    MALLOCARRAY(buffer, end - cursor + 1);
    if (!buffer)
        retval = pm_strsol;
    else {
        unsigned int outCursor;
        for (outCursor = 0; cursor < end; ++cursor)
            buffer[outCursor++] = value[cursor];

        buffer[outCursor++] = '\0';

        retval = buffer;
    }
    return retval;
}



/* Forward declaration for recursion */

static void
processIfd(const unsigned char *  const exifData,
           unsigned int           const exifLength,
           const unsigned char *  const ifdData,
           ByteOrder              const byteOrder,
           bool                   const wantTagTrace,
           exif_ifd *             const ifdP,
           const unsigned char ** const nextIfdPP,
           const char **          const errorP);


static void
processDirEntry(const unsigned char *  const dirEntry,
                const unsigned char *  const exifData,
                unsigned int           const exifLength,
                ByteOrder              const byteOrder,
                bool                   const wantTagTrace,
                exif_ifd *             const ifdP,
                const char **          const errorP) {

    int const tag        = get16u(&dirEntry[0], byteOrder);
    int const format     = get16u(&dirEntry[2], byteOrder);
    int const components = get32u(&dirEntry[4], byteOrder);

    const unsigned char * valuePtr;
        /* This actually can point to a variety of things; it must be cast to
           other types when used.  But we use it as a byte-by-byte cursor, so
           we declare it as a pointer to a generic byte here.
        */
    unsigned int valueSz;

    *errorP = NULL;  /* initial assumption */

    if ((format-1) >= NUM_FORMATS) {
        /* (-1) catches illegal zero case as unsigned underflows
           to positive large.
        */
        pm_message("Illegal number format %d for tag %04x", format, tag);
        return;
    }

    valueSz = components * bytesPerFormat[format];

    if (valueSz > 4) {
        unsigned const offsetVal = get32u(&dirEntry[8], byteOrder);
        /* If its bigger than 4 bytes, the dir entry contains an offset.*/
        if (offsetVal + valueSz > exifLength) {
            /* Bogus pointer offset and / or bytecount value */
            pm_message("Illegal pointer offset value in EXIF "
                       "for tag %04x.  "
                       "Offset %d bytes %d ExifLen %d\n",
                       tag, offsetVal, valueSz, exifLength);
            return;
        }
        valuePtr = &exifData[offsetVal];
    } else {
        /* 4 bytes or less and value is in the dir entry itself */
        valuePtr = &dirEntry[8];
    }

    if (wantTagTrace)
        traceTag(tag, format, valuePtr, valueSz, byteOrder);
    /* TODO: Need to deal with nonterminated strings in tag value */
    /* TODO: Deal with repeated tag */
    /* Extract useful components of tag */
    switch (tag) {
    case TAG_MAKE:
        ifdP->cameraMake = pm_strdup((const char*)valuePtr);
        break;

    case TAG_MODEL:
        ifdP->cameraModel = pm_strdup((const char*)valuePtr);
        break;

    case TAG_XRESOLUTION:
        MALLOCVAR_NOFAIL(ifdP->xResolutionP);
        *ifdP->xResolutionP = numericValue(valuePtr, format, byteOrder);
        break;

    case TAG_YRESOLUTION:
        MALLOCVAR_NOFAIL(ifdP->yResolutionP);
        *ifdP->yResolutionP = numericValue(valuePtr, format, byteOrder);
        break;

    case TAG_DATETIME_ORIGINAL:
        ifdP->dateTime = pm_strdup((const char*)valuePtr);
        break;

    case TAG_USERCOMMENT:
        ifdP->comments = commentValue(valuePtr, valueSz);
        break;

    case TAG_FNUMBER:
        /* Simplest way of expressing aperture, so I trust it the most.
           (replace any existing value, as it will be based on a less useful
           tag that came earlier in the IFD).
        */
        if (ifdP->apertureFNumberP)
            free(ifdP->apertureFNumberP);

        MALLOCVAR_NOFAIL(ifdP->apertureFNumberP);
        *ifdP->apertureFNumberP =
            (float)numericValue(valuePtr, format, byteOrder);
        break;

    case TAG_APERTURE:
    case TAG_MAXAPERTURE:
        /* If we already have aperture information, it probably came from an
           FNUMBER tag and is superior, so we leave it alone
        */
        if (!ifdP->apertureFNumberP) {
            MALLOCVAR_NOFAIL(ifdP->apertureFNumberP);
            *ifdP->apertureFNumberP = (float)
                exp(numericValue(valuePtr, format, byteOrder)
                    * log(2) * 0.5);
        }
        break;

    case TAG_FOCALLENGTH:
        /* Nice digital cameras actually save the focal length
           as a function of how farthey are zoomed in.
        */

        MALLOCVAR_NOFAIL(ifdP->focalLengthP);
        *ifdP->focalLengthP =
            (float)numericValue(valuePtr, format, byteOrder);
        break;

    case TAG_SUBJECT_DISTANCE:
        /* Inidcates the distacne the autofocus camera is focused to.
           Tends to be less accurate as distance increases.
        */
        MALLOCVAR_NOFAIL(ifdP->distanceP);
        *ifdP->distanceP =
            (float)numericValue(valuePtr, format, byteOrder);
        break;

    case TAG_EXPOSURETIME:
        MALLOCVAR_NOFAIL(ifdP->exposureTimeP);
        *ifdP->exposureTimeP =
            (float)numericValue(valuePtr, format, byteOrder);
        break;

    case TAG_SHUTTERSPEED:
        MALLOCVAR_NOFAIL(ifdP->shutterSpeedP);
        *ifdP->shutterSpeedP =
            1 << (unsigned int)numericValue(valuePtr, format, byteOrder);
        break;

    case TAG_FLASH: {
        unsigned int const tagValue =
            (unsigned int)numericValue(valuePtr, format, byteOrder);

        MALLOCVAR_NOFAIL(ifdP->flashP);

        *ifdP->flashP = ((tagValue & 0x7) != 0);

    } break;

    case TAG_ORIENTATION: {
        unsigned int const tagValue =
            (unsigned int)numericValue(valuePtr, format, byteOrder);

        if (tagValue < 1 || tagValue > 8)
            pm_asprintf(errorP, "Unrecognized orientation value %d",
                        tagValue);
        else {
            MALLOCVAR_NOFAIL(ifdP->orientationP);

            switch (tagValue) {
            case 1: *ifdP->orientationP = ORIENT_NORMAL;     break;
            case 2: *ifdP->orientationP = ORIENT_FLIP_HORIZ; break;
            case 3: *ifdP->orientationP = ORIENT_ROTATE_180; break;
            case 4: *ifdP->orientationP = ORIENT_FLIP_VERT;  break;
            case 5: *ifdP->orientationP = ORIENT_TRANSPOSE;  break;
            case 6: *ifdP->orientationP = ORIENT_ROTATE_90;  break;
            case 7: *ifdP->orientationP = ORIENT_TRANSVERSE; break;
            case 8: *ifdP->orientationP = ORIENT_ROTATE_270; break;
            default:
                assert(false);
            }
        }
        } break;

    case TAG_EXIF_IMAGELENGTH:
        MALLOCVAR_NOFAIL(ifdP->exifImageLengthP);
        *ifdP->exifImageLengthP =
            (unsigned int)numericValue(valuePtr, format, byteOrder);
        break;

    case TAG_EXIF_IMAGEWIDTH:
        MALLOCVAR_NOFAIL(ifdP->exifImageWidthP);
        *ifdP->exifImageWidthP =
            (unsigned int)numericValue(valuePtr, format, byteOrder);
        break;

    case TAG_FOCALPLANEXRES:
        MALLOCVAR_NOFAIL(ifdP->focalPlaneXResP);
        *ifdP->focalPlaneXResP = numericValue(valuePtr, format, byteOrder);
        break;

    case TAG_FOCALPLANEUNITS: {
        int const tagValue = (int)numericValue(valuePtr, format, byteOrder);

        if (tagValue < 1 || tagValue > 5) {
            pm_asprintf(errorP, "Unrecognized FOCALPLANEUNITS value %d.  "
                        "We know only 1, 2, 3, 4, and 5",
                        tagValue);
        } else {
            MALLOCVAR_NOFAIL(ifdP->focalPlaneUnitsP);

            switch (tagValue) {
            case 1: *ifdP->focalPlaneUnitsP = 25.4;  break; /* 1 inch */
            case 2: *ifdP->focalPlaneUnitsP = 100.0; break; /* 1 meter */
            case 3: *ifdP->focalPlaneUnitsP = 10.0;  break;  /* 1 centimeter*/
            case 4: *ifdP->focalPlaneUnitsP = 1.0;   break;  /* 1 millimeter*/
            case 5: *ifdP->focalPlaneUnitsP = .001;  break;  /* 1 micrometer*/
            }
            /* According to the information I was using, 2 means meters.  But
               looking at the Cannon powershot's files, inches is the only
               sensible value.
            */
        }
    } break;

        /* Remaining cases contributed by: Volker C. Schoech
           (schoech@gmx.de)
        */

    case TAG_EXPOSURE_BIAS:
        MALLOCVAR_NOFAIL(ifdP->exposureBiasP);
        *ifdP->exposureBiasP =
            (float) numericValue(valuePtr, format, byteOrder);
        break;

    case TAG_WHITEBALANCE:
        MALLOCVAR_NOFAIL(ifdP->whiteBalanceP);
        *ifdP->whiteBalanceP = (int)numericValue(valuePtr, format, byteOrder);
        break;

    case TAG_METERING_MODE:
        MALLOCVAR_NOFAIL(ifdP->meteringModeP);
        *ifdP->meteringModeP = (int)numericValue(valuePtr, format, byteOrder);
        break;

    case TAG_EXPOSURE_PROGRAM:
        MALLOCVAR_NOFAIL(ifdP->exposureProgramP);
        *ifdP->exposureProgramP =
            (int)numericValue(valuePtr, format, byteOrder);
        break;

    case TAG_ISO_EQUIVALENT: {
        int const tagValue = (int)numericValue(valuePtr, format, byteOrder);

        MALLOCVAR_NOFAIL(ifdP->isoEquivalentP);
        if (tagValue < 50)
            *ifdP->isoEquivalentP = tagValue * 200;
        else
            *ifdP->isoEquivalentP = tagValue;
    } break;

    case TAG_COMPRESSION_LEVEL:
        MALLOCVAR_NOFAIL(ifdP->compressionLevelP);
        *ifdP->compressionLevelP =
            (int)numericValue(valuePtr, format, byteOrder);
        break;

    case TAG_THUMBNAIL_OFFSET:
        MALLOCVAR_NOFAIL(ifdP->thumbnailOffsetP);
        *ifdP->thumbnailOffsetP = (unsigned int)
            numericValue(valuePtr, format, byteOrder);
        break;

    case TAG_THUMBNAIL_LENGTH:
        MALLOCVAR_NOFAIL(ifdP->thumbnailLengthP);
        *ifdP->thumbnailLengthP = (unsigned int)
            numericValue(valuePtr, format, byteOrder);
        break;

    case TAG_EXIF_OFFSET:
    case TAG_INTEROP_OFFSET: {
        unsigned int const subIfdOffset = get32u(valuePtr, byteOrder);
        if (subIfdOffset + 4 > exifLength)
            pm_message("Invalid exif or interop offset "
                       "directory link.  Offset is %u, "
                       "but Exif data is only %u bytes.",
                       subIfdOffset, exifLength);
        else {
            /* Process the chain of IFDs starting at 'subIfdOffset'.
               Merge whatever tags are in them into *ifdP
            */
            const unsigned char * nextIfdP;

            for (nextIfdP = exifData + subIfdOffset; nextIfdP;) {
                const char * error;

                if (wantTagTrace)
                    pm_message("Processing subIFD");

                processIfd(exifData, exifLength, exifData + subIfdOffset,
                           byteOrder, wantTagTrace,
                           ifdP, &nextIfdP, &error);

                if (error) {
                    pm_asprintf(errorP, "Failed to process "
                                "ExifOffset/InteropOffset tag.  %s", error);
                    pm_strfree(error);
                }
            }
        }
    } break;
    }
}



static void
locateNextIfd(const unsigned char *  const exifData,
              unsigned int           const exifLength,
              ByteOrder              const byteOrder,
              const unsigned char *  const nextIfdLinkPtr,
              const unsigned char ** const nextIfdPP,
              const char **          const errorP) {

    if (nextIfdLinkPtr + 4 > exifData + exifLength)
        pm_asprintf(errorP, "EXIF header ends before next-IFD link");
    else {
        if (nextIfdLinkPtr + 4 <= exifData + exifLength) {
            unsigned int const nextIfdLink =
                get32u(nextIfdLinkPtr, byteOrder);
                /* Offset in EXIF header of next IFD, or zero if none */

            if (nextIfdLink) {
                if (nextIfdLink + 4 >= exifLength) {
                    pm_asprintf(errorP, "Next IFD link is %u, "
                                "but EXIF header is only %u bytes long",
                                nextIfdLink, exifLength);
                } else
                    *nextIfdPP = exifData + nextIfdLink;
            } else
                *nextIfdPP = NULL;
        }
    }
}



static void
processIfd(const unsigned char *  const exifData,
           unsigned int           const exifLength,
           const unsigned char *  const ifdData,
           ByteOrder              const byteOrder,
           bool                   const wantTagTrace,
           exif_ifd *             const ifdP,
           const unsigned char ** const nextIfdPP,
           const char **          const errorP) {
/*--------------------------------------------------------------------------
   Process one EXIF IFD (Image File Directory).

   The text of the IFD is at 'ifdData'.

   The text of the EXIF header of which the IFD is part is the 'exifLength'
   bytes at 'exifData'.

   Return the contents of the directory (tags) as *ifdP.

   Return as *nextIfdPP a pointer into the EXIF header at 'exifData'
   to the next IFD in the chain, or NULL if this is the last IFD.
--------------------------------------------------------------------------*/
    unsigned int const numDirEntries = get16u(&ifdData[0], byteOrder);

    unsigned int de;

    *errorP = NULL;  /* initial value */

    #define DIR_ENTRY_ADDR(Start, Entry) (Start + 2 + 12*(Entry))

    if (wantTagTrace)
        pm_message("Processing IFD at %p with %u entries",
                   ifdData, numDirEntries);

    for (de = 0; de < numDirEntries && !*errorP; ++de) {
        const char * error;
        processDirEntry(DIR_ENTRY_ADDR(ifdData, de), exifData, exifLength,
                        byteOrder, wantTagTrace, ifdP,
                        &error);

        if (error) {
            pm_asprintf(errorP, "Failed to process tag %u.  %s",
                        de, error);
            pm_strfree(error);
        }
    }

    locateNextIfd(exifData, exifLength, byteOrder,
                  DIR_ENTRY_ADDR(ifdData, numDirEntries),
                  nextIfdPP, errorP);

    if (ifdP->thumbnailOffsetP && ifdP->thumbnailLengthP) {
        if (*ifdP->thumbnailOffsetP + *ifdP->thumbnailLengthP <= exifLength) {
            /* The thumbnail pointer appears to be valid.  Store it. */
            ifdP->thumbnail     = exifData + *ifdP->thumbnailOffsetP;
            ifdP->thumbnailSize = *ifdP->thumbnailLengthP;
        }
    }
    if (wantTagTrace)
        pm_message("Done processing IFD at %p", ifdData);
}



void
exif_parse(const unsigned char * const exifData,
           unsigned int          const length,
           exif_ImageInfo *      const imageInfoP,
           bool                  const wantTagTrace,
           const char **         const errorP) {
/*--------------------------------------------------------------------------
  Interpret an EXIF APP1 marker

  'exifData' is the actual Exif data; it does not include the
  "Exif" identifier and length field that often prefix Exif data.

  'length' is the length of the Exif section.
--------------------------------------------------------------------------*/
    ByteOrder byteOrder;
    unsigned int firstOffset;

    *errorP = NULL;  /* initial assumption */

    if (wantTagTrace)
        pm_message("Exif header %u bytes long", length);

    if (memeq(exifData + 0, "II" , 2)) {
        if (wantTagTrace)
            pm_message("Exif header in Intel order");
        byteOrder = ORDER_NORMAL;
    } else {
        if (memeq(exifData + 0, "MM", 2)) {
            if (wantTagTrace)
                pm_message("Exif header in Motorola order");
            byteOrder = ORDER_MOTOROLA;
        } else {
            pm_asprintf(errorP, "Invalid alignment marker in Exif "
                        "data.  First two bytes are '%c%c' (0x%02x%02x) "
                        "instead of 'II' or 'MM'.",
                        exifData[0], exifData[1], exifData[0], exifData[1]);
        }
    }
    if (!*errorP) {
        unsigned short const start = get16u(exifData + 2, byteOrder);
        /* Check the next value for correctness. */
        if (start != 0x002a) {
            pm_asprintf(errorP, "Invalid Exif header start.  "
                        "two bytes after the alignment marker "
                        "should be 0x002a, but is 0x%04x",
                        start);
        }
    }
    if (!*errorP) {
        const char * error;
        const unsigned char * nextIfdP;

        firstOffset = get32u(exifData + 4, byteOrder);
        if (firstOffset < 8 || firstOffset > 16) {
            /* I used to ensure this was set to 8 (website I used
               indicated it's 8) but PENTAX Optio 230 has it set
               differently, and uses it as offset. (Sept 11 2002)
            */
            pm_message("Suspicious offset of first IFD value in Exif header");
        }

        initializeIfd(&imageInfoP->mainImage);
        initializeIfd(&imageInfoP->thumbnailImage);

        if (wantTagTrace)
            pm_message("Processing main image IFD (IFD0)");

        processIfd(exifData, length, exifData + firstOffset, byteOrder,
                   wantTagTrace,
                   &imageInfoP->mainImage, &nextIfdP, &error);

        if (error) {
            pm_asprintf(errorP, "Failed to process main image IFD.  %s",
                        error);
            pm_strfree(error);
        }

        if (nextIfdP) {
            const char * error;

            if (wantTagTrace)
                pm_message("Processing thumbnail IFD (IFD1)");

            processIfd(exifData, length, nextIfdP, byteOrder,
                       wantTagTrace,
                       &imageInfoP->thumbnailImage, &nextIfdP, &error);

            if (error) {
                pm_asprintf(errorP,
                            "Failed to process thumbnail image IFD.  %s",
                            error);
                pm_strfree(error);
            } else {
                if (nextIfdP) {
                    pm_message("Ignoring third IFD in EXIF header because "
                               "We understand only two -- one for the main "
                               "image and one for the thumbnail");
                }
            }
        }
        if (!*errorP) {
            /* Compute the CCD width, in millimeters. */
            if (imageInfoP->mainImage.focalPlaneXResP &&
                imageInfoP->mainImage.focalPlaneUnitsP &&
                imageInfoP->mainImage.exifImageWidthP &&
                imageInfoP->mainImage.exifImageLengthP) {

                unsigned int const maxDim =
                    MAX(*imageInfoP->mainImage.exifImageWidthP,
                        *imageInfoP->mainImage.exifImageLengthP);

                MALLOCVAR_NOFAIL(imageInfoP->ccdWidthP);
                *imageInfoP->ccdWidthP =
                    (float)(maxDim *
                            *imageInfoP->mainImage.focalPlaneUnitsP /
                            *imageInfoP->mainImage.focalPlaneXResP);
            } else
                imageInfoP->ccdWidthP = NULL;
        }
    }
}



static void
showIfd(const exif_ifd * const ifdP) {

    if (ifdP->cameraMake)
        pm_message("Camera make  : %s", ifdP->cameraMake);

    if (ifdP->cameraModel)
        pm_message("Camera model : %s", ifdP->cameraModel);

    if (ifdP->dateTime)
        pm_message("Date/Time    : %s", ifdP->dateTime);

    if (ifdP->xResolutionP && ifdP->yResolutionP)
        pm_message("Resolution   : %f x %f",
                   *ifdP->xResolutionP, *ifdP->yResolutionP);

    if (ifdP->orientationP) {
        /* Note that orientation is usually understood to be the orientation
           of the camera, not of the image.  The top, bottom, left, and right
           sides of an image are defined in the JFIF format.

           But values such as "flip horizontal" make no sense for that.
        */

        const char * orientDisp;

        switch (*ifdP->orientationP) {
        case ORIENT_NORMAL:     orientDisp = "Normal";          break;
        case ORIENT_FLIP_HORIZ: orientDisp = "Flip horizontal"; break;
        case ORIENT_ROTATE_180: orientDisp = "Rotate 180";      break;
        case ORIENT_FLIP_VERT:  orientDisp = "Flip vertical";   break;
        case ORIENT_TRANSPOSE:  orientDisp = "Transpose";       break;
        case ORIENT_ROTATE_90:  orientDisp = "Rotate 90";       break;
        case ORIENT_TRANSVERSE: orientDisp = "Transverse";      break;
        case ORIENT_ROTATE_270: orientDisp = "Rotate 270";      break;
        }

        pm_message("Orientation  : %s", orientDisp);
    }

    if (ifdP->isColorP)
        pm_message("Color/bw     : %s",
                   *ifdP->isColorP ? "Color" : "Black and white");

    if (ifdP->flashP)
        pm_message("Flash used   : %s",
                   *ifdP->flashP ? "Yes" :"No");

    if (ifdP->exposureTimeP) {
        const char * timeDisp;
        const char * recipDisp;

        if (*ifdP->exposureTimeP < 0.010) {
            pm_asprintf(&timeDisp, "%6.4f s", *ifdP->exposureTimeP);
        } else {
            pm_asprintf(&timeDisp, "%5.3f s", *ifdP->exposureTimeP);
        }
        /* We've seen the EXPOSURETIME tag be present but contain zero.
           I don't know why.
        */
        if (*ifdP->exposureTimeP <= 0.5 && *ifdP->exposureTimeP > 0) {
            pm_asprintf(&recipDisp, " (1/%d)",
                        (int)(0.5 + 1 / *ifdP->exposureTimeP));
        } else
            recipDisp = pm_strdup("");

        pm_message("Exposure time: %s %s", timeDisp, recipDisp);

        pm_strfree(recipDisp);
        pm_strfree(timeDisp);
    }
    if (ifdP->shutterSpeedP)
        pm_message("Shutter speed: 1/%u", *ifdP->shutterSpeedP);

    if (ifdP->apertureFNumberP) {
        pm_message("Aperture     : f/%3.1f", *ifdP->apertureFNumberP);
    }
    if (ifdP->distanceP) {
        if (*ifdP->distanceP < 0)
            pm_message("Focus dist.  : Infinite");
        else
            pm_message("Focus dist.  :%5.2fm", *ifdP->distanceP);
    }

    if (ifdP->isoEquivalentP)
        pm_message("ISO equiv.   : %2d", *ifdP->isoEquivalentP);

    if (ifdP->exposureBiasP)
        pm_message("Exposure bias: %4.2f", *ifdP->exposureBiasP);

    if (ifdP->whiteBalanceP) {
        const char * whiteBalanceDisp;

        switch(*ifdP->whiteBalanceP) {
        case 1:  whiteBalanceDisp = "sunny";         break;
        case 2:  whiteBalanceDisp = "fluorescent";   break;
        case 3:  whiteBalanceDisp = "incandescent";  break;
        default: whiteBalanceDisp = "cloudy";        break;
        }
        pm_message("Whitebalance : %s", whiteBalanceDisp);
    }
    if (ifdP->meteringModeP) {
        const char * meteringModeDisp;

        switch(*ifdP->meteringModeP) {
        case 2:  meteringModeDisp = "center weight";  break;
        case 3:  meteringModeDisp = "spot";           break;
        case 5:  meteringModeDisp = "matrix";         break;
        default: meteringModeDisp = "?";              break;
        }
        pm_message("Metering Mode: %s", meteringModeDisp);
    }
    if (ifdP->exposureProgramP) {
        const char * exposureDisp;

        switch(*ifdP->exposureProgramP) {
        case 2:  exposureDisp = "program (auto)";                break;
        case 3:  exposureDisp = "aperture priority (semi-auto)"; break;
        case 4:  exposureDisp = "shutter priority (semi-auto)";  break;
        default: exposureDisp = "?";                              break;
        }
        pm_message("Exposure     : %s", exposureDisp);
    }
    if (ifdP->compressionLevelP) {
        const char * jpegQualityDisp;

        switch(*ifdP->compressionLevelP) {
        case 1:  jpegQualityDisp = "basic";  break;
        case 2:  jpegQualityDisp = "normal"; break;
        case 4:  jpegQualityDisp = "fine";   break;
        default: jpegQualityDisp = "?";      break;
       }
        pm_message("Jpeg Quality  : %s", jpegQualityDisp);
    }

    if (ifdP->comments) {
        char * buffer;

        MALLOCARRAY(buffer, strlen(ifdP->comments) + 1);

        if (!buffer)
            pm_message("Out of memory allocating a buffer for %u "
                       "characters of comments",
                       (unsigned)strlen(ifdP->comments));
        else {
            unsigned int i;
            unsigned int outCursor;

            strcpy(buffer, "Comment:  ");  /* Permanently in buffer */

            outCursor = 10;  /* initial value */

            for (i = 0; ifdP->comments[i]; ++i) {
                char const c = ifdP->comments[i];
                if (c == '\n') {
                    buffer[outCursor++] = '\0';
                    pm_message("%s", buffer);
                    outCursor = 10;
                } else
                    buffer[outCursor++] = c;
            }
            if (outCursor > 10)
                pm_message("%s", buffer);

            free(buffer);
        }
    }
}



void
exif_showImageInfo(const exif_ImageInfo * const imageInfoP) {
/*--------------------------------------------------------------------------
   Show the collected image info, displaying camera F-stop and shutter
   speed in a consistent and legible fashion.
--------------------------------------------------------------------------*/
    showIfd(&imageInfoP->mainImage);

    if (imageInfoP->mainImage.focalLengthP) {
        const char * mm35equiv;

        if (imageInfoP->ccdWidthP) {
            pm_asprintf(&mm35equiv, "  (35mm equivalent: %dmm)",
                        (int) (*imageInfoP->mainImage.focalLengthP /
                               *imageInfoP->ccdWidthP * 36 + 0.5));
        } else
            mm35equiv = pm_strdup("");

        pm_message("Focal length : %4.1fmm %s",
                   *imageInfoP->mainImage.focalLengthP, mm35equiv);

        pm_strfree(mm35equiv);
    }

    if (imageInfoP->ccdWidthP)
        pm_message("CCD width    : %2.4fmm", *imageInfoP->ccdWidthP);
}



void
exif_terminateImageInfo(exif_ImageInfo * const imageInfoP) {

    terminateIfd(&imageInfoP->mainImage);
    terminateIfd(&imageInfoP->thumbnailImage);
}