/*--------------------------------------------------------------------------
  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.

  An EXIF header is a JFIF APP1 marker.  It 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).

--------------------------------------------------------------------------*/
#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>

#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 "nstring.h"

#include "exif.h"

static const unsigned char * DirWithThumbnailPtrs;
static double FocalplaneXRes;
bool HaveXRes;
static double FocalplaneUnits;
static int ExifImageWidth;

typedef struct {
    unsigned short Tag;
    const char * Desc;
} TagTable;



/* 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 TagTable 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 { NORMAL, 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 == 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 == 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 void
printFormatNumber(FILE *       const fileP, 
                  const void * const ValuePtr, 
                  int          const Format,
                  int          const ByteCount,
                  ByteOrder    const byteOrder) {
/*--------------------------------------------------------------------------
   Display a number as one of its many formats
--------------------------------------------------------------------------*/
    switch(Format){
    case FMT_SBYTE:
    case FMT_BYTE:
        fprintf(fileP, "%02x\n", *(unsigned char *)ValuePtr);
        break;
    case FMT_USHORT:
        fprintf(fileP, "%d\n",get16u(ValuePtr, byteOrder));
        break;
    case FMT_ULONG:     
    case FMT_SLONG:
        fprintf(fileP, "%d\n",get32s(ValuePtr, byteOrder));
        break;
    case FMT_SSHORT:    
        fprintf(fileP, "%hd\n",(signed short)get16u(ValuePtr, byteOrder));
        break;
    case FMT_URATIONAL:
    case FMT_SRATIONAL: 
        fprintf(fileP, "%d/%d\n",get32s(ValuePtr, byteOrder),
                get32s(4+(char *)ValuePtr, byteOrder));
        break;
    case FMT_SINGLE:    
        fprintf(fileP, "%f\n",(double)*(float *)ValuePtr);
        break;
    case FMT_DOUBLE:
        fprintf(fileP, "%f\n",*(double *)ValuePtr);
        break;
    default: 
        fprintf(fileP, "Unknown format %d:", Format);
        {
            unsigned int a;
            for (a = 0; a < ByteCount && a < 16; ++a)
                printf("%02x", ((unsigned char *)ValuePtr)[a]);
        }
        fprintf(fileP, "\n");
    }
}



static double
convertAnyFormat(const void * const ValuePtr,
                 int          const Format,
                 ByteOrder    const byteOrder) {
/*--------------------------------------------------------------------------
   Evaluate number, be it int, rational, or float from directory.
--------------------------------------------------------------------------*/
    double Value;
    Value = 0;

    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 void
traceTag(int                   const tag,
         int                   const format,
         const unsigned char * const valuePtr,
         unsigned int          const byteCount,
         ByteOrder             const byteOrder) {
             
    /* Show tag name */
    unsigned int a;
    bool found;
    for (a = 0, found = false; !found; ++a){
        if (tagTable[a].Tag == 0){
            fprintf(stderr, "  Unknown Tag %04x Value = ", tag);
            found = true;
        }
        if (tagTable[a].Tag == tag){
            fprintf(stderr, "    %s = ",tagTable[a].Desc);
            found = true;
        }
    }

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

    case FMT_UNDEFINED:
        /* Undefined is typically an ascii string. */

    case FMT_STRING: {
        /* String arrays printed without function call
           (different from int arrays)
        */
        bool noPrint;
        printf("\"");
        for (a = 0, noPrint = false; a < byteCount; ++a){
            if (ISPRINT((valuePtr)[a])){
                fprintf(stderr, "%c", valuePtr[a]);
                noPrint = false;
            } else {
                /* Avoiding indicating too many unprintable characters of
                   proprietary bits of binary information this program may not
                   know how to parse.
                */
                if (!noPrint){
                    fprintf(stderr, "?");
                    noPrint = true;
                }
            }
        }
        fprintf(stderr, "\"\n");
    } break;

    default:
        /* Handle arrays of numbers later (will there ever be?)*/
        printFormatNumber(stderr, valuePtr, format, byteCount, byteOrder);
    }
}



/* Forward declaration for recursion */

static void 
processExifDir(const unsigned char *  const ExifData, 
               unsigned int           const ExifLength,
               unsigned int           const DirOffset,
               exif_ImageInfo *       const imageInfoP, 
               ByteOrder              const byteOrder,
               bool                   const wantTagTrace,
               const unsigned char ** const LastExifRefdP);


static void
processDirEntry(const unsigned char *  const dirEntry,
                const unsigned char *  const exifData,
                unsigned int           const exifLength,
                ByteOrder              const byteOrder,
                bool                   const wantTagTrace,
                exif_ImageInfo *       const imageInfoP, 
                unsigned int *         const thumbnailOffsetP,
                unsigned int *         const thumbnailSizeP,
                bool *                 const haveThumbnailP,
                const unsigned char ** const lastExifRefdP) {

    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 byteCount;

    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;
    }
        
    byteCount = components * bytesPerFormat[format];

    if (byteCount > 4){
        unsigned const offsetVal = get32u(&dirEntry[8], byteOrder);
        /* If its bigger than 4 bytes, the dir entry contains an offset.*/
        if (offsetVal + byteCount > 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, byteCount, exifLength);
            return;
        }
        valuePtr = &exifData[offsetVal];
    } else {
        /* 4 bytes or less and value is in the dir entry itself */
        valuePtr = &dirEntry[8];
    }

    if (*lastExifRefdP < valuePtr + byteCount){
        /* Keep track of last byte in the exif header that was actually
           referenced.  That way, we know where the discardable thumbnail data
           begins.
        */
        *lastExifRefdP = valuePtr + byteCount;
    }

    if (wantTagTrace)
        traceTag(tag, format, valuePtr, byteCount, byteOrder);

    *haveThumbnailP = (tag == TAG_THUMBNAIL_OFFSET);

    /* Extract useful components of tag */
    switch (tag){

    case TAG_MAKE:
        STRSCPY(imageInfoP->CameraMake, (const char*)valuePtr);
        break;

    case TAG_MODEL:
        STRSCPY(imageInfoP->CameraModel, (const char*)valuePtr);
        break;

    case TAG_XRESOLUTION:
        imageInfoP->XResolution = 
            convertAnyFormat(valuePtr, format, byteOrder);
        break;

    case TAG_YRESOLUTION:
        imageInfoP->YResolution = 
            convertAnyFormat(valuePtr, format, byteOrder);
        break;

    case TAG_DATETIME_ORIGINAL:
        STRSCPY(imageInfoP->DateTime, (const char*)valuePtr);
        imageInfoP->DatePointer = (const char*)valuePtr;
        break;

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

        unsigned int cursor;
        unsigned int outCursor;
        unsigned int end;

        for (end = byteCount; 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 < byteCount && 
                 (value[cursor] == '\0' || value[cursor] == ' ');
             ++cursor);

        /* Copy the rest as the comment */

        for (outCursor = 0;
             cursor < end && outCursor < MAX_COMMENT-1;
             ++cursor)
            imageInfoP->Comments[outCursor++] = value[cursor];

        imageInfoP->Comments[outCursor++] = '\0';
    } break;

    case TAG_FNUMBER:
        /* Simplest way of expressing aperture, so I trust it the most.
           (overwrite previously computd value if there is one)
        */
        imageInfoP->ApertureFNumber = 
            (float)convertAnyFormat(valuePtr, format, byteOrder);
        break;

    case TAG_APERTURE:
    case TAG_MAXAPERTURE:
        /* More relevant info always comes earlier, so only use this field if
           we don't have appropriate aperture information yet.
        */
        if (imageInfoP->ApertureFNumber == 0){
            imageInfoP->ApertureFNumber = (float)
                exp(convertAnyFormat(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. 
        */

        imageInfoP->FocalLength = 
            (float)convertAnyFormat(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.
        */
        imageInfoP->Distance = 
            (float)convertAnyFormat(valuePtr, format, byteOrder);
        break;

    case TAG_EXPOSURETIME:
        /* Simplest way of expressing exposure time, so I
           trust it most.  (overwrite previously computd value
           if there is one) 
        */
        imageInfoP->ExposureTime = 
            (float)convertAnyFormat(valuePtr, format, byteOrder);
        break;

    case TAG_SHUTTERSPEED:
        /* More complicated way of expressing exposure time,
           so only use this value if we don't already have it
           from somewhere else.  
        */
        if (imageInfoP->ExposureTime == 0){
            imageInfoP->ExposureTime = (float)
                (1/exp(convertAnyFormat(valuePtr, format, byteOrder)
                       * log(2)));
        }
        break;

    case TAG_FLASH:
        if ((int)convertAnyFormat(valuePtr, format, byteOrder) & 0x7){
            imageInfoP->FlashUsed = TRUE;
        }else{
            imageInfoP->FlashUsed = FALSE;
        }
        break;

    case TAG_ORIENTATION:
        imageInfoP->Orientation = 
            (int)convertAnyFormat(valuePtr, format, byteOrder);
        if (imageInfoP->Orientation < 1 || 
            imageInfoP->Orientation > 8){
            pm_message("Undefined rotation value %d",
                       imageInfoP->Orientation);
            imageInfoP->Orientation = 0;
        }
        break;

    case TAG_EXIF_IMAGELENGTH:
    case TAG_EXIF_IMAGEWIDTH:
        /* Use largest of height and width to deal with images
           that have been rotated to portrait format.  
        */
        ExifImageWidth =
            MIN(ExifImageWidth,
                (int)convertAnyFormat(valuePtr, format, byteOrder));
        break;

    case TAG_FOCALPLANEXRES:
        HaveXRes = TRUE;
        FocalplaneXRes = convertAnyFormat(valuePtr, format, byteOrder);
        break;

    case TAG_FOCALPLANEUNITS:
        switch((int)convertAnyFormat(valuePtr, format, byteOrder)){
        case 1: FocalplaneUnits = 25.4; break; /* 1 inch */
        case 2: 
            /* According to the information I was using, 2
               means meters.  But looking at the Cannon
               powershot's files, inches is the only
               sensible value.  
            */
            FocalplaneUnits = 25.4;
            break;

        case 3: FocalplaneUnits = 10;   break;  /* 1 centimeter*/
        case 4: FocalplaneUnits = 1;    break;  /* 1 millimeter*/
        case 5: FocalplaneUnits = .001; break;  /* 1 micrometer*/
        }
        break;

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

    case TAG_EXPOSURE_BIAS:
        imageInfoP->ExposureBias = 
            (float) convertAnyFormat(valuePtr, format, byteOrder);
        break;

    case TAG_WHITEBALANCE:
        imageInfoP->Whitebalance = 
            (int)convertAnyFormat(valuePtr, format, byteOrder);
        break;

    case TAG_METERING_MODE:
        imageInfoP->MeteringMode = 
            (int)convertAnyFormat(valuePtr, format, byteOrder);
        break;

    case TAG_EXPOSURE_PROGRAM:
        imageInfoP->ExposureProgram = 
            (int)convertAnyFormat(valuePtr, format, byteOrder);
        break;

    case TAG_ISO_EQUIVALENT:
        imageInfoP->ISOequivalent = 
            (int)convertAnyFormat(valuePtr, format, byteOrder);
        if ( imageInfoP->ISOequivalent < 50 ) 
            imageInfoP->ISOequivalent *= 200;
        break;

    case TAG_COMPRESSION_LEVEL:
        imageInfoP->CompressionLevel = 
            (int)convertAnyFormat(valuePtr, format, byteOrder);
        break;

    case TAG_THUMBNAIL_OFFSET:
        *thumbnailOffsetP = (unsigned int)
            convertAnyFormat(valuePtr, format, byteOrder);
        break;

    case TAG_THUMBNAIL_LENGTH:
        *thumbnailSizeP = (unsigned int)
            convertAnyFormat(valuePtr, format, byteOrder);
        break;

    case TAG_EXIF_OFFSET:
    case TAG_INTEROP_OFFSET: {
        unsigned int const subdirOffset = get32u(valuePtr, byteOrder);
        if (subdirOffset >= exifLength)
            pm_message("Illegal exif or interop offset "
                       "directory link.  Offset is %u, "
                       "but Exif data is only %u bytes.",
                       subdirOffset, exifLength);
        else
            processExifDir(exifData, exifLength, subdirOffset, 
                           imageInfoP, byteOrder, wantTagTrace,
                           lastExifRefdP);
    } break;
    }
}



static void 
processExifDir(const unsigned char *  const exifData, 
               unsigned int           const exifLength,
               unsigned int           const dirOffset,
               exif_ImageInfo *       const imageInfoP, 
               ByteOrder              const byteOrder,
               bool                   const wantTagTrace,
               const unsigned char ** const lastExifRefdP) {
/*--------------------------------------------------------------------------
   Process one of the nested EXIF directories.
--------------------------------------------------------------------------*/
    const unsigned char * const dirStart = exifData + dirOffset;
    unsigned int const numDirEntries = get16u(&dirStart[0], byteOrder);
    unsigned int de;
    bool haveThumbnail;
    unsigned int thumbnailOffset;
    unsigned int thumbnailSize;

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

    {
        const unsigned char * const dirEnd =
            DIR_ENTRY_ADDR(dirStart, numDirEntries);
        if (dirEnd + 4 > (exifData + exifLength)){
            if (dirEnd + 2 == exifData + exifLength || 
                dirEnd == exifData + exifLength){
                /* Version 1.3 of jhead would truncate a bit too much.
                   This also caught later on as well.
                */
            }else{
                /* Note: Files that had thumbnails trimmed with jhead
                   1.3 or earlier might trigger this.
                */
                pm_message("Illegal directory entry size");
                return;
            }
        }
        *lastExifRefdP = MAX(*lastExifRefdP, dirEnd);
    }

    if (wantTagTrace)
        pm_message("Directory with %d entries", numDirEntries);

    haveThumbnail   = false;  /* initial value */
    thumbnailOffset = 0;      /* initial value */
    thumbnailSize   = 0;      /* initial value */

    for (de = 0; de < numDirEntries; ++de)
        processDirEntry(DIR_ENTRY_ADDR(dirStart, de), exifData, exifLength,
                        byteOrder, wantTagTrace, imageInfoP,
                        &thumbnailOffset, &thumbnailSize, &haveThumbnail,
                        lastExifRefdP);

    if (haveThumbnail)
        DirWithThumbnailPtrs = dirStart;

    {
        /* In addition to linking to subdirectories via exif tags,
           there's also a potential link to another directory at the end
           of each directory.  This has got to be the result of a
           committee!  
        */
        if (DIR_ENTRY_ADDR(dirStart, numDirEntries) + 4 <= 
            exifData + exifLength){
            unsigned int const subdirOffset =
                get32u(dirStart + 2 + 12*numDirEntries, byteOrder);
            if (subdirOffset){
                const unsigned char * const subdirStart =
                    exifData + subdirOffset;
                if (subdirStart > exifData + exifLength){
                    if (subdirStart < exifData + exifLength + 20){
                        /* Jhead 1.3 or earlier would crop the whole directory!
                           As Jhead produces this form of format incorrectness,
                           I'll just let it pass silently.
                        */
                        if (wantTagTrace) 
                            printf("Thumbnail removed with "
                                   "Jhead 1.3 or earlier\n");
                    }else{
                        pm_message("Illegal subdirectory link");
                    }
                }else{
                    if (subdirOffset <= exifLength)
                        processExifDir(exifData, exifLength, subdirOffset,
                                       imageInfoP, byteOrder, wantTagTrace,
                                       lastExifRefdP);
                }
            }
        }else{
            /* The exif header ends before the last next directory pointer. */
        }
    }

    if (thumbnailSize && thumbnailOffset){
        if (thumbnailSize + thumbnailOffset <= exifLength){
            /* The thumbnail pointer appears to be valid.  Store it. */
            imageInfoP->ThumbnailPointer = exifData + thumbnailOffset;
            imageInfoP->ThumbnailSize = thumbnailSize;

            if (wantTagTrace){
                fprintf(stderr, "Thumbnail size: %u bytes\n", thumbnailSize);
            }
        }
    }
}



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;
    int FirstOffset;
    const unsigned char * lastExifRefd;

    *errorP = NULL;  /* initial assumption */

    if (wantTagTrace)
        fprintf(stderr, "Exif header %d bytes long\n",length);

    if (MEMEQ(exifData + 0, "II" , 2)) {
        if (wantTagTrace) 
            fprintf(stderr, "Exif header in Intel order\n");
        byteOrder = NORMAL;
    } else {
        if (MEMEQ(exifData + 0, "MM", 2)) {
            if (wantTagTrace) 
                fprintf(stderr, "Exif header in Motorola order\n");
            byteOrder = 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) {
        FirstOffset = get32u(exifData + 4, byteOrder);
        if (FirstOffset < 8 || FirstOffset > 16){
            /* I used to ensure this was set to 8 (website I used
               indicated its 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");
        }
        
        imageInfoP->Comments[0] = '\0';  /* Initial value - null string */
        
        HaveXRes = FALSE;  /* Initial assumption */
        FocalplaneUnits = 0;
        ExifImageWidth = 0;
        
        lastExifRefd = exifData;
        DirWithThumbnailPtrs = NULL;
        
        processExifDir(exifData, length, FirstOffset, 
                       imageInfoP, byteOrder, wantTagTrace, &lastExifRefd);
        
        /* Compute the CCD width, in millimeters. */
        if (HaveXRes){
            imageInfoP->HaveCCDWidth = 1;
            imageInfoP->CCDWidth = 
                    (float)(ExifImageWidth * FocalplaneUnits / FocalplaneXRes);
        } else
            imageInfoP->HaveCCDWidth = 0;
            
        if (wantTagTrace){
            fprintf(stderr, 
                    "Non-settings part of Exif header: %lu bytes\n",
                    (unsigned long)(exifData + length - lastExifRefd));
        }
    }
}



void 
exif_showImageInfo(const exif_ImageInfo * const imageInfoP,
                   FILE *                 const fileP) {
/*--------------------------------------------------------------------------
   Show the collected image info, displaying camera F-stop and shutter
   speed in a consistent and legible fashion.
--------------------------------------------------------------------------*/
    if (imageInfoP->CameraMake[0]) {
        fprintf(fileP, "Camera make  : %s\n", imageInfoP->CameraMake);
        fprintf(fileP, "Camera model : %s\n", imageInfoP->CameraModel);
    }
    if (imageInfoP->DateTime[0])
        fprintf(fileP, "Date/Time    : %s\n", imageInfoP->DateTime);

    fprintf(fileP, "Resolution   : %f x %f\n",
            imageInfoP->XResolution, imageInfoP->YResolution);

    if (imageInfoP->Orientation > 1) {

        /* Only print orientation if one was supplied, and if its not
           1 (normal orientation)

           1 - The 0th row is at the visual top of the image
               and the 0th column is the visual left-hand side.
           2 - The 0th row is at the visual top of the image
               and the 0th column is the visual right-hand side.
           3 - The 0th row is at the visual bottom of the image
               and the 0th column is the visual right-hand side.
           4 - The 0th row is at the visual bottom of the image
               and the 0th column is the visual left-hand side.
           5 - The 0th row is the visual left-hand side of of the image
               and the 0th column is the visual top.
           6 - The 0th row is the visual right-hand side of of the image
               and the 0th column is the visual top.
           7 - The 0th row is the visual right-hand side of of the image
               and the 0th column is the visual bottom.
           8 - The 0th row is the visual left-hand side of of the image
               and the 0th column is the visual bottom.

           Note: The descriptions here are the same as the name of the
           command line option to pass to jpegtran to right the image
        */
        static const char * OrientTab[9] = {
            "Undefined",
            "Normal",           /* 1 */
            "flip horizontal",  /* left right reversed mirror */
            "rotate 180",       /* 3 */
            "flip vertical",    /* upside down mirror */
            "transpose",    /* Flipped about top-left <--> bottom-right axis.*/
            "rotate 90",        /* rotate 90 cw to right it. */
            "transverse",   /* flipped about top-right <--> bottom-left axis */
            "rotate 270",       /* rotate 270 to right it. */
        };

        fprintf(fileP, "Orientation  : %s\n", 
                OrientTab[imageInfoP->Orientation]);
    }

    if (imageInfoP->IsColor == 0)
        fprintf(fileP, "Color/bw     : Black and white\n");

    if (imageInfoP->FlashUsed >= 0)
        fprintf(fileP, "Flash used   : %s\n",
                imageInfoP->FlashUsed ? "Yes" :"No");

    if (imageInfoP->FocalLength) {
        fprintf(fileP, "Focal length : %4.1fmm",
                (double)imageInfoP->FocalLength);
        if (imageInfoP->HaveCCDWidth){
            fprintf(fileP, "  (35mm equivalent: %dmm)",
                    (int)
                    (imageInfoP->FocalLength/imageInfoP->CCDWidth*36 + 0.5));
        }
        fprintf(fileP, "\n");
    }

    if (imageInfoP->HaveCCDWidth)
        fprintf(fileP, "CCD width    : %2.4fmm\n",
                (double)imageInfoP->CCDWidth);

    if (imageInfoP->ExposureTime) {
        if (imageInfoP->ExposureTime < 0.010){
            fprintf(fileP, 
                    "Exposure time: %6.4f s ",
                    (double)imageInfoP->ExposureTime);
        }else{
            fprintf(fileP, 
                    "Exposure time: %5.3f s ",
                    (double)imageInfoP->ExposureTime);
        }
        if (imageInfoP->ExposureTime <= 0.5){
            fprintf(fileP, " (1/%d)",(int)(0.5 + 1/imageInfoP->ExposureTime));
        }
        fprintf(fileP, "\n");
    }
    if (imageInfoP->ApertureFNumber){
        fprintf(fileP, "Aperture     : f/%3.1f\n",
                (double)imageInfoP->ApertureFNumber);
    }
    if (imageInfoP->Distance){
        if (imageInfoP->Distance < 0){
            fprintf(fileP, "Focus dist.  : Infinite\n");
        }else{
            fprintf(fileP, "Focus dist.  :%5.2fm\n",
                    (double)imageInfoP->Distance);
        }
    }

    if (imageInfoP->ISOequivalent){ /* 05-jan-2001 vcs */
        fprintf(fileP, "ISO equiv.   : %2d\n",(int)imageInfoP->ISOequivalent);
    }
    if (imageInfoP->ExposureBias){ /* 05-jan-2001 vcs */
        fprintf(fileP, "Exposure bias:%4.2f\n",
                (double)imageInfoP->ExposureBias);
    }
        
    if (imageInfoP->Whitebalance){ /* 05-jan-2001 vcs */
        switch(imageInfoP->Whitebalance) {
        case 1:
            fprintf(fileP, "Whitebalance : sunny\n");
            break;
        case 2:
            fprintf(fileP, "Whitebalance : fluorescent\n");
            break;
        case 3:
            fprintf(fileP, "Whitebalance : incandescent\n");
            break;
        default:
            fprintf(fileP, "Whitebalance : cloudy\n");
        }
    }
    if (imageInfoP->MeteringMode){ /* 05-jan-2001 vcs */
        switch(imageInfoP->MeteringMode) {
        case 2:
            fprintf(fileP, "Metering Mode: center weight\n");
            break;
        case 3:
            fprintf(fileP, "Metering Mode: spot\n");
            break;
        case 5:
            fprintf(fileP, "Metering Mode: matrix\n");
            break;
        }
    }
    if (imageInfoP->ExposureProgram){ /* 05-jan-2001 vcs */
        switch(imageInfoP->ExposureProgram) {
        case 2:
            fprintf(fileP, "Exposure     : program (auto)\n");
            break;
        case 3:
            fprintf(fileP, "Exposure     : aperture priority (semi-auto)\n");
            break;
        case 4:
            fprintf(fileP, "Exposure     : shutter priority (semi-auto)\n");
            break;
        }
    }
    if (imageInfoP->CompressionLevel){ /* 05-jan-2001 vcs */
        switch(imageInfoP->CompressionLevel) {
        case 1:
            fprintf(fileP, "Jpeg Quality  : basic\n");
            break;
        case 2:
            fprintf(fileP, "Jpeg Quality  : normal\n");
            break;
        case 4:
            fprintf(fileP, "Jpeg Quality  : fine\n");
            break;
       }
    }

    /* Print the comment. Print 'Comment:' for each new line of comment. */
    if (imageInfoP->Comments[0]) {
        unsigned int a;

        fprintf(fileP, "Comment      : ");

        for (a = 0; a < MAX_COMMENT && imageInfoP->Comments[a]; ++a) {
            char const c = imageInfoP->Comments[a];
            if (c == '\n'){
                /* Do not start a new line if the string ends with a cr */
                if (imageInfoP->Comments[a+1] != '\0')
                    fprintf(fileP, "\nComment      : ");
                else
                    fprintf(fileP, "\n");
            } else
                putc(c, fileP);
        }
        fprintf(fileP, "\n");
    }

    fprintf(fileP, "\n");
}


