/*--------------------------------------------------------------------------
  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",
                       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);
}



