home *** CD-ROM | disk | FTP | other *** search
/ Crawly Crypt Collection 1 / crawlyvol1.bin / program / grfx_snd / tifflib / source / tif_dir.c < prev    next >
C/C++ Source or Header  |  1993-01-17  |  68KB  |  1,674 lines

  1. #pragma warn -use
  2. static char     *sccsid = "@(#)TIFF/tif_dir.c 1.64, Copyright (c) Sam Leffler, Dieter Linde, "__DATE__;
  3. #pragma warn .use
  4. /*
  5.  * Copyright (c) 1988, 1990 by Sam Leffler, Oct 8 1990
  6.  * All rights reserved.
  7.  *
  8.  * This file is provided for unrestricted use provided that this legend is included on all tape media and as a part of the
  9.  * software program in whole or part.  Users may copy, modify or distribute this file at will.
  10.  *
  11.  * TIFF Library.
  12.  *
  13.  * Directory Support Routines.
  14.  *
  15.  * NB: Beware of the varargs declarations for routines in this file.  The names and types of variables has been
  16.  *     carefully chosen to make things work with compilers that are busted in one way or another (e.g. SGI/MIPS).
  17.  */
  18. #include <stdlib.h>
  19. #include "tiffio.h"
  20.  
  21. #ifndef TRUE
  22. #define TRUE       1
  23. #define FALSE      0
  24. #endif
  25.  
  26. #define howmany(x, y)    (((x) + ((y) - 1)) / (y))
  27. #define roundup(x, y)      ((((x) + ((y) - 1)) / (y)) * (y))
  28.  
  29. #define FieldSet(fields, f)            (fields[f / 32] & (1L << (f & 0x1F)))
  30. #define ResetFieldBit(fields, f)        (fields[f / 32] &= ~(1L << (f & 0x1F)))
  31.  
  32. #define TIFFExtractData(tif, type, v)     ((tif)->tif_header.tiff_magic == TIFF_BIGENDIAN ? ((v) >> (tif)->tif_typeshift[type]) & (tif)->tif_typemask[type] : (v) & (tif)->tif_typemask[type])
  33. #define TIFFInsertData(tif, type, v)     ((tif)->tif_header.tiff_magic == TIFF_BIGENDIAN ? ((v) & (tif)->tif_typemask[type]) << (tif)->tif_typeshift[type] : (v) & (tif)->tif_typemask[type])
  34.  
  35. typedef struct {
  36.         u_short        field_tag;              /* field's tag */
  37.         short       field_count;            /* write count (-1 for unknown) */
  38.         TIFFDataType     field_type;            /* type of associated data */
  39.         u_short     field_bit;              /* bit in fieldsset bit vector */
  40.         u_short     field_oktochange;       /* if true, can change while writing */
  41.         char        *field_name;        /* ASCII name */
  42. } TIFFFieldInfo;
  43.  
  44. /*
  45.  * NB: This array is assumed to be sorted by tag.
  46.  */
  47. static TIFFFieldInfo    FieldInfo[] = {
  48.         { TIFFTAG_SUBFILETYPE,           1, TIFF_LONG,     FIELD_SUBFILETYPE,           TRUE,  "SubfileType" },
  49.  
  50. #ifdef    SUBFILE_COMPAT
  51.         { TIFFTAG_SUBFILETYPE,           1, TIFF_SHORT,    FIELD_SUBFILETYPE,           FALSE, "SubfileType" },
  52. #endif    /* SUBFILE_COMPAT */
  53.  
  54.         { TIFFTAG_OSUBFILETYPE,           1, TIFF_SHORT,    FIELD_SUBFILETYPE,        FALSE, "OldSubfileType" },
  55.         { TIFFTAG_IMAGEWIDTH,             1, TIFF_SHORT,    FIELD_IMAGEDIMENSIONS,    FALSE, "ImageWidth" },
  56.         { TIFFTAG_IMAGEWIDTH,             1, TIFF_LONG,     FIELD_IMAGEDIMENSIONS,    FALSE, "ImageWidth" },
  57.         { TIFFTAG_IMAGELENGTH,            1, TIFF_SHORT,    FIELD_IMAGEDIMENSIONS,    TRUE,  "ImageLength" },
  58.         { TIFFTAG_IMAGELENGTH,            1, TIFF_LONG,     FIELD_IMAGEDIMENSIONS,    TRUE,  "ImageLength" },
  59.         { TIFFTAG_BITSPERSAMPLE,         -1, TIFF_SHORT,    FIELD_BITSPERSAMPLE,      FALSE, "BitsPerSample" },
  60.        { TIFFTAG_COMPRESSION,            1, TIFF_SHORT,    FIELD_COMPRESSION,        FALSE, "Compression" },
  61.         { TIFFTAG_PHOTOMETRIC,            1, TIFF_SHORT,    FIELD_PHOTOMETRIC,        TRUE,  "PhotometricInterpretation" },
  62.         { TIFFTAG_THRESHHOLDING,          1, TIFF_SHORT,    FIELD_THRESHHOLDING,      TRUE,  "Threshholding" },
  63.         { TIFFTAG_CELLWIDTH,              1, TIFF_SHORT,    (u_short)-1,                TRUE,  "CellWidth" },
  64.         { TIFFTAG_CELLLENGTH,             1, TIFF_SHORT,    (u_short)-1,              TRUE,  "CellLength" },
  65.         { TIFFTAG_FILLORDER,              1, TIFF_SHORT,    FIELD_FILLORDER,          FALSE, "FillOrder" },
  66.         { TIFFTAG_DOCUMENTNAME,          -1, TIFF_ASCII,    FIELD_DOCUMENTNAME,       TRUE,  "DocumentName" },
  67.        { TIFFTAG_IMAGEDESCRIPTION,      -1, TIFF_ASCII,    FIELD_IMAGEDESCRIPTION,   TRUE,  "ImageDescription" },
  68.         { TIFFTAG_MAKE,                  -1, TIFF_ASCII,    FIELD_MAKE,                TRUE,  "Make" },
  69.         { TIFFTAG_MODEL,                 -1, TIFF_ASCII,    FIELD_MODEL,                TRUE,  "Model" },
  70.         { TIFFTAG_STRIPOFFSETS,          -1, TIFF_LONG,     FIELD_STRIPOFFSETS,       FALSE, "StripOffsets" },
  71.         { TIFFTAG_STRIPOFFSETS,          -1, TIFF_SHORT,    FIELD_STRIPOFFSETS,       FALSE, "StripOffsets" },
  72.         { TIFFTAG_ORIENTATION,            1, TIFF_SHORT,    FIELD_ORIENTATION,        TRUE,  "Orientation" },
  73.         { TIFFTAG_SAMPLESPERPIXEL,        1, TIFF_SHORT,    FIELD_SAMPLESPERPIXEL,    FALSE, "SamplesPerPixel" },
  74.         { TIFFTAG_ROWSPERSTRIP,           1, TIFF_LONG,     FIELD_ROWSPERSTRIP,       FALSE, "RowsPerStrip" },
  75.         { TIFFTAG_ROWSPERSTRIP,           1, TIFF_SHORT,    FIELD_ROWSPERSTRIP,       FALSE, "RowsPerStrip" },
  76.         { TIFFTAG_STRIPBYTECOUNTS,       -1, TIFF_LONG,     FIELD_STRIPBYTECOUNTS,    FALSE, "StripByteCounts" },
  77.         { TIFFTAG_STRIPBYTECOUNTS,       -1, TIFF_SHORT,    FIELD_STRIPBYTECOUNTS,    FALSE, "StripByteCounts" },
  78.         { TIFFTAG_MINSAMPLEVALUE,        -1, TIFF_SHORT,    FIELD_MINSAMPLEVALUE,     TRUE,  "MinSampleValue" },
  79.         { TIFFTAG_MAXSAMPLEVALUE,        -1, TIFF_SHORT,    FIELD_MAXSAMPLEVALUE,     TRUE,  "MaxSampleValue" },
  80.         { TIFFTAG_XRESOLUTION,            1, TIFF_RATIONAL, FIELD_RESOLUTION,         TRUE,  "XResolution" },
  81.         { TIFFTAG_YRESOLUTION,            1, TIFF_RATIONAL, FIELD_RESOLUTION,         TRUE,  "YResolution" },
  82.         { TIFFTAG_PLANARCONFIG,           1, TIFF_SHORT,    FIELD_PLANARCONFIG,       FALSE, "PlanarConfiguration" },
  83.         { TIFFTAG_PAGENAME,              -1, TIFF_ASCII,    FIELD_PAGENAME,           TRUE,  "PageName" },
  84.         { TIFFTAG_XPOSITION,              1, TIFF_RATIONAL, FIELD_POSITION,           TRUE,  "XPosition" },
  85.         { TIFFTAG_YPOSITION,              1, TIFF_RATIONAL, FIELD_POSITION,           TRUE,  "YPosition" },
  86.         { TIFFTAG_FREEOFFSETS,           -1, TIFF_LONG,     (u_short)-1,                FALSE, "FreeOffsets" },
  87.         { TIFFTAG_FREEBYTECOUNTS,        -1, TIFF_LONG,     (u_short)-1,                FALSE, "FreeByteCounts" },
  88.         { TIFFTAG_GRAYRESPONSEUNIT,       1, TIFF_SHORT,    FIELD_GRAYRESPONSEUNIT,   TRUE,  "GrayResponseUnit" },
  89.         { TIFFTAG_GRAYRESPONSECURVE,     -1, TIFF_SHORT,    FIELD_GRAYRESPONSECURVE,  TRUE,  "GrayResponseCurve" },
  90.         { TIFFTAG_GROUP3OPTIONS,          1, TIFF_LONG,     FIELD_GROUP3OPTIONS,      FALSE, "Group3Options" },
  91.         { TIFFTAG_GROUP4OPTIONS,          1, TIFF_LONG,     FIELD_GROUP4OPTIONS,      FALSE, "Group4Options" },
  92.         { TIFFTAG_RESOLUTIONUNIT,         1, TIFF_SHORT,    FIELD_RESOLUTIONUNIT,     TRUE,  "ResolutionUnit" },
  93.         { TIFFTAG_PAGENUMBER,             2, TIFF_SHORT,    FIELD_PAGENUMBER,         TRUE,  "PageNumber" },
  94.         { TIFFTAG_COLORRESPONSEUNIT,      1, TIFF_SHORT,    FIELD_COLORRESPONSEUNIT,  TRUE,  "ColorResponseUnit" },
  95.         { TIFFTAG_COLORRESPONSECURVE,      -1, TIFF_SHORT,    FIELD_COLORRESPONSECURVE, TRUE,  "ColorResponseCurve" },
  96.         { TIFFTAG_SOFTWARE,              -1, TIFF_ASCII,    FIELD_SOFTWARE,           TRUE,  "Software" },
  97.         { TIFFTAG_DATETIME,              -1, TIFF_ASCII,    FIELD_DATETIME,           TRUE,  "DateTime" },
  98.         { TIFFTAG_ARTIST,                -1, TIFF_ASCII,    FIELD_ARTIST,                TRUE,  "Artist" },
  99.         { TIFFTAG_HOSTCOMPUTER,          -1, TIFF_ASCII,    FIELD_HOSTCOMPUTER,       TRUE,  "HostComputer" },
  100.         { TIFFTAG_PREDICTOR,               1, TIFF_SHORT,    FIELD_PREDICTOR,          FALSE, "Predictor" },
  101.         { TIFFTAG_WHITEPOINT,             2, TIFF_RATIONAL, (u_short)-1,                TRUE,  "WhitePoint" },
  102.         { TIFFTAG_PRIMARYCHROMATICITIES,  6, TIFF_RATIONAL, (u_short)-1,                TRUE,  "PrimaryChromaticities" },
  103.         { TIFFTAG_COLORMAP,               1, TIFF_SHORT,    FIELD_COLORMAP,           TRUE,  "ColorMap" },
  104.         { TIFFTAG_BADFAXLINES,            1, TIFF_LONG,     FIELD_BADFAXLINES,        TRUE,  "BadFaxLines" },
  105.         { TIFFTAG_BADFAXLINES,            1, TIFF_SHORT,    FIELD_BADFAXLINES,        TRUE,  "BadFaxLines" },
  106.         { TIFFTAG_CLEANFAXDATA,           1, TIFF_SHORT,    FIELD_CLEANFAXDATA,       TRUE,  "CleanFaxData" },
  107.         { TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG,     FIELD_BADFAXRUN,          TRUE,  "ConsecutiveBadFaxLines" },
  108.         { TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_SHORT,    FIELD_BADFAXRUN,          TRUE,  "ConsecutiveBadFaxLines" },
  109. /*** begin nonstandard tags ***/
  110.         { TIFFTAG_MATTEING,               1, TIFF_SHORT,    FIELD_MATTEING,           FALSE, "Matteing" },
  111. };
  112.  
  113. #define    NFIELDINFO    (sizeof(FieldInfo) / sizeof(FieldInfo[0]))
  114.  
  115. #define    IGNORE      0                  /* tag placeholder used below */
  116.  
  117. static int    datawidth[] = {
  118.         1,      /* nothing */
  119.         1,      /* TIFF_BYTE */
  120.         1,      /* TIFF_ASCII */
  121.         2,      /* TIFF_SHORT */
  122.         4,      /* TIFF_LONG */
  123.         8,    /* TIFF_RATIONAL */
  124. };
  125.  
  126. /****************************************************************************
  127.  *
  128.  */
  129. static void
  130. TIFFUnpackShorts(
  131.     TIFF        *tif,
  132.         u_short        v[],
  133.            TIFFDirEntry    *dir
  134.            )
  135. {
  136.         if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) {
  137.                 v[0] = dir->tdir_offset >> 16;
  138.                 v[1] = dir->tdir_offset & 0xffff;
  139.         } 
  140.         else {
  141.                 v[0] = dir->tdir_offset & 0xffff;
  142.                 v[1] = dir->tdir_offset >> 16;
  143.         }
  144. }
  145.  
  146. /****************************************************************************
  147.  *
  148.  */
  149. static TIFFFieldInfo *
  150. FindFieldInfo(
  151.     u_short     tag, 
  152.     TIFFDataType    dt
  153.     )
  154. {
  155.         register TIFFFieldInfo    *fip;
  156.  
  157.         /*** NB: if table gets big, can use sorted search (e.g. binary search) ***/
  158.         for (fip = FieldInfo; fip < &FieldInfo[NFIELDINFO]; fip++)
  159.                 if (fip->field_tag == tag && (dt == (TIFFDataType)0 || fip->field_type == dt))
  160.                         return(fip);
  161.         return(NULL);
  162. }
  163.  
  164. /****************************************************************************
  165.  *
  166.  */
  167. static TIFFFieldInfo *
  168. FieldWithTag(
  169.     u_short    tag
  170.     )
  171. {
  172.         TIFFFieldInfo *fip = FindFieldInfo(tag, (TIFFDataType)0);
  173.         if (fip)
  174.                 return(fip);
  175.         TIFFError("FieldWithTag", "internal error, unknown tag %u", tag);
  176.         exit(-1);
  177.         /*** NOTREACHED ***/
  178.         return(NULL);
  179. }
  180.  
  181. /****************************************************************************
  182.  * Fetch a contiguous directory item.
  183.  */
  184. static int
  185. TIFFFetchData(
  186.     TIFF        *tif,
  187.            TIFFDirEntry    *dir,
  188.            char            *cp
  189.            )
  190. {
  191.            int     w, cc;
  192.  
  193.         w = datawidth[dir->tdir_type];
  194.         cc = (int)dir->tdir_count * w;
  195.         if (SeekOK(tif->tif_fd, dir->tdir_offset) && ReadOK(tif->tif_fd, cp, cc)) {
  196.                    if (tif->tif_flags & TIFF_SWAB) {
  197.                            switch (dir->tdir_type) {
  198.                             case TIFF_SHORT:
  199.                                     TIFFSwabArrayOfShort((u_short *)cp, (int)dir->tdir_count);
  200.                                     break;
  201.                             case TIFF_LONG:
  202.                                     TIFFSwabArrayOfLong((u_long *)cp, (int)dir->tdir_count);
  203.                                     break;
  204.                             case TIFF_RATIONAL:
  205.                                     TIFFSwabArrayOfLong((u_long *)cp, (int)(dir->tdir_count * 2));
  206.                                     break;
  207.                            }
  208.                    }
  209.                 return(cc);
  210.         }
  211.         TIFFError("TIFFFetchData", "error fetching data for field '%s'", FieldWithTag(dir->tdir_tag)->field_name);
  212.         return(0);
  213. }
  214.  
  215. /****************************************************************************
  216.  * Fetch an ASCII item from the file.
  217.  */
  218. static int
  219. TIFFFetchString(
  220.     TIFF              *tif,
  221.         TIFFDirEntry     *dir,
  222.         char             *cp
  223.         )
  224. {
  225.         if (dir->tdir_count <= 4) {
  226.                 u_long     l = dir->tdir_offset;
  227.  
  228.                 if (tif->tif_flags & TIFF_SWAB)
  229.                         TIFFSwabLong(&l);
  230.                 bcopy(&l, cp, dir->tdir_count);
  231.                 return(1);
  232.         }
  233.         return(TIFFFetchData(tif, dir, cp));
  234. }
  235.  
  236. /****************************************************************************
  237.  * Fetch a rational item from the file at offset off.  We return the value
  238.  * as floating point number.
  239.  */
  240. static double
  241. TIFFFetchRational(
  242.     TIFF                *tif,
  243.         TIFFDirEntry     *dir
  244.         )
  245. {
  246.            long     l[2];
  247.  
  248.         if (!TIFFFetchData(tif, dir, (char *)l))
  249.                 return(1.0);
  250.         if (l[1] == 0) {
  251.                    TIFFError("TIFFFetchRational", "rational with zero denominator", FieldWithTag(dir->tdir_tag)->field_name);
  252.                 return(1.0);
  253.         }
  254.         return((double)l[0] / (double)l[1]);
  255. }
  256.  
  257. /****************************************************************************
  258.  *
  259.  */
  260. static int
  261. TIFFFetchPerSampleShorts(
  262.     TIFF               *tif,
  263.         TIFFDirEntry     *dir,
  264.         long               *pl
  265.         )
  266. {
  267.            u_short    v[4];
  268.         int     i;
  269.  
  270.         switch ((int)dir->tdir_count) {
  271.             case 1:
  272.                     *pl = TIFFExtractData(tif, dir->tdir_type, dir->tdir_offset);
  273.                     return(1);    /* XXX should check samplesperpixel */
  274.             case 2:
  275.                     TIFFUnpackShorts(tif, v, dir);
  276.                     break;
  277.             default:
  278.                     if (!TIFFFetchData(tif, dir, (char *)v))
  279.                             return(0);
  280.                     break;
  281.         }
  282.         if (tif->tif_dir.td_samplesperpixel != dir->tdir_count) {
  283.                 TIFFError("TIFFFetchPerSampleShorts", "incorrect count %ld for field '%s'", dir->tdir_count, FieldWithTag(dir->tdir_tag)->field_name);
  284.                 return(0);
  285.         }
  286.         for (i = 1; i < dir->tdir_count; i++)
  287.                 if (v[i] != v[0]) {
  288.                         TIFFError("TIFFFetchPerSampleShorts", "can't handle different per-sample values for field '%s'", FieldWithTag(dir->tdir_tag)->field_name);
  289.                            return(0);
  290.                 }
  291.         *pl = v[0];
  292.         return(1);
  293. }
  294.  
  295. /****************************************************************************
  296.  *
  297.  */
  298. static int
  299. TIFFFetchStripThing(
  300.     TIFF          *tif,
  301.         TIFFDirEntry     *dir,
  302.         long          nstrips,
  303.         u_long          **lpp
  304.         )
  305. {
  306.     static char    *module = "TIFFFetchStripThing";
  307.            register u_long    *lp;
  308.         int         status;
  309.  
  310.         if (nstrips != dir->tdir_count) {
  311.                 TIFFError(module, "count mismatch for field '%s'; expecting %ld, got %ld", FieldWithTag(dir->tdir_tag)->field_name, nstrips, dir->tdir_count);
  312.                 return(0);
  313.         }
  314.  
  315.         /*
  316.          * Allocate space for strip information.
  317.          */
  318.         if (*lpp == NULL && (*lpp = (u_long *)malloc(nstrips * sizeof(u_long))) == NULL) {
  319.                    TIFFError(module, "out of memory allocating space for '%s' array", FieldWithTag(dir->tdir_tag)->field_name);
  320.                 return(0);
  321.         }
  322.         lp = *lpp;
  323.         status = 1;
  324.         if (dir->tdir_type == (int)TIFF_SHORT) {
  325.  
  326.     /*
  327.          * Handle short->long expansion.
  328.          */
  329.                    if (dir->tdir_count > 2) {
  330.                            char     *dp = malloc(dir->tdir_count * datawidth[(int)TIFF_SHORT]);
  331.  
  332.                         if (dp == NULL) {
  333.                                    TIFFError(module, "out of memory fetching field '%s'", FieldWithTag(dir->tdir_tag)->field_name);
  334.                                 return(0);
  335.                         }
  336.                         if ((status = TIFFFetchData(tif, dir, dp)) != 0) {
  337.                                    register u_short    *wp = (u_short *)dp;
  338.  
  339.                                 while (nstrips-- > 0)
  340.                                         *lp++ = *wp++;
  341.                         }
  342.                         free(dp);
  343.                 } 
  344.                 else {
  345.  
  346.     /*
  347.          * Extract data from offset field.
  348.          */
  349.                         if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) {
  350.                                 *lp++ = (dir->tdir_offset >> 16);
  351.                                 *lp = dir->tdir_offset & 0xffff;
  352.                         } 
  353.                         else {
  354.                                 *lp++ = (dir->tdir_offset & 0xffff);
  355.                                 *lp = dir->tdir_offset >> 16;
  356.                         }
  357.                 }
  358.         } 
  359.         else {
  360.                 if (dir->tdir_count > 1)
  361.                         status = TIFFFetchData(tif, dir, (char *)lp);
  362.                 else
  363.                         *lp = dir->tdir_offset;
  364.         }
  365.         return(status);
  366. }
  367.  
  368. /****************************************************************************
  369.  *
  370.  */
  371. static void
  372. MissingRequired(
  373.     TIFF     *tif, 
  374.     char     *tagname
  375.     )
  376. {
  377.         TIFFError("TIFFLib", "TIFF directory for file \"%s\" is missing required '%s' field", tif->tif_name, tagname);
  378. }
  379.  
  380. /****************************************************************************
  381.  *
  382.  */
  383. static void
  384. setString(
  385.     char    **cpp, 
  386.     char     *cp
  387.     )
  388. {
  389.         if (*cpp) {
  390.                 free(*cpp);
  391.                 *cpp = 0;
  392.         }
  393.         if (cp) {
  394.                 size_t    len = strlen(cp) + 1;
  395.  
  396.                 if ((*cpp = malloc(len)) != NULL)
  397.                         bcopy(cp, *cpp, len);
  398.         }
  399. }
  400.  
  401. /****************************************************************************
  402.  *
  403.  */
  404. static void
  405. setCurve(
  406.     u_short    **wpp, 
  407.     u_short    *wp, 
  408.     long    nw
  409.     )
  410. {
  411.         if (*wpp) {
  412.                 free(*wpp);
  413.                 *wpp = 0;
  414.         }
  415.         nw *= sizeof(u_short);
  416.         if (wp && ((*wpp = (u_short *)malloc(nw)) != NULL))
  417.                 bcopy(wp, *wpp, nw);
  418. }
  419.  
  420. /****************************************************************************
  421.  * Record the value of a field in the internal directory structure.  The
  422.  * field will be written to the file when/if the directory structure is
  423.  * updated.
  424.  */
  425. int
  426. TIFFSetField(
  427.     TIFF     *tif,
  428.     u_short    tag,
  429.     ...
  430.     )
  431. {
  432.         static char    *module = "TIFFSetField";
  433.         TIFFDirectory     *td = &tif->tif_dir;
  434.         va_list     ap;
  435.         long         v;
  436.         int         field = -1;
  437.         int        status = 1;
  438.  
  439.         if (tag != TIFFTAG_IMAGELENGTH && (tif->tif_flags & TIFF_BEENWRITING)) {
  440.                 TIFFFieldInfo     *fip = FindFieldInfo(tag, (TIFFDataType)0);
  441.  
  442.     /*
  443.          * Consult info table to see if tag can be changed after we've started writing.  We only allow changes
  444.          * to those tags that don't/shouldn't affect the compression and/or format of the data.
  445.          */
  446.                 if (fip && !fip->field_oktochange) {
  447.                         TIFFError(module, "can't modify tag '%s'", fip->field_name);
  448.                         return(0);
  449.                 }
  450.         }
  451.         va_start(ap, tag);
  452.         switch (tag) {
  453.             case TIFFTAG_SUBFILETYPE:
  454.                     td->td_subfiletype = va_arg(ap, int);
  455.                     field = FIELD_SUBFILETYPE;
  456.                     break;
  457.             case TIFFTAG_IMAGEWIDTH:
  458.                     td->td_imagewidth = va_arg(ap, int);
  459.                     field = FIELD_IMAGEDIMENSIONS;
  460.                     break;
  461.             case TIFFTAG_IMAGELENGTH:
  462.                     td->td_imagelength = va_arg(ap, int);
  463.                     field = FIELD_IMAGEDIMENSIONS;
  464.                     break;
  465.             case TIFFTAG_BITSPERSAMPLE:
  466.                     td->td_bitspersample = va_arg(ap, int);
  467.                     field = FIELD_BITSPERSAMPLE;
  468.                     break;
  469.             case TIFFTAG_COMPRESSION:
  470.                     v = va_arg(ap, int) & 0xffff;
  471.  
  472.     /*
  473.          * If we're changing the compression scheme, the notify the previous module so that it
  474.          * can cleanup any state it's setup.
  475.          */
  476.                     if (TIFFFieldSet(tif, FIELD_COMPRESSION)) {
  477.                             if (td->td_compression == v)
  478.                                     break;
  479.                             if (tif->tif_cleanup)
  480.                                     (*tif->tif_cleanup)(tif);
  481.                     }
  482.  
  483.     /*
  484.          * Setup new compression routine state.
  485.          */
  486.                     if ((status = TIFFSetCompressionScheme(tif, v)) != 0) {
  487.                             td->td_compression = v;
  488.                             field = FIELD_COMPRESSION;
  489.                     }
  490.                     break;
  491.             case TIFFTAG_PHOTOMETRIC:
  492.                     td->td_photometric = va_arg(ap, int);
  493.                     field = FIELD_PHOTOMETRIC;
  494.                     break;
  495.             case TIFFTAG_THRESHHOLDING:
  496.                     td->td_threshholding = va_arg(ap, int);
  497.                     field = FIELD_THRESHHOLDING;
  498.                     break;
  499.             case TIFFTAG_FILLORDER:
  500.                     td->td_fillorder = va_arg(ap, int);
  501.                     field = FIELD_FILLORDER;
  502.                     break;
  503.             case TIFFTAG_DOCUMENTNAME:
  504.                     setString(&td->td_documentname, va_arg(ap, char *));
  505.                     field = FIELD_DOCUMENTNAME;
  506.                     break;
  507.             case TIFFTAG_ARTIST:
  508.                     setString(&td->td_artist, va_arg(ap, char *));
  509.                     field = FIELD_ARTIST;
  510.                     break;
  511.             case TIFFTAG_DATETIME:
  512.                     setString(&td->td_datetime, va_arg(ap, char *));
  513.                     field = FIELD_DATETIME;
  514.                     break;
  515.             case TIFFTAG_HOSTCOMPUTER:
  516.                     setString(&td->td_hostcomputer, va_arg(ap, char *));
  517.                     field = FIELD_HOSTCOMPUTER;
  518.                     break;
  519.             case TIFFTAG_IMAGEDESCRIPTION:
  520.                     setString(&td->td_imagedescription, va_arg(ap, char *));
  521.                     field = FIELD_IMAGEDESCRIPTION;
  522.                     break;
  523.             case TIFFTAG_MAKE:
  524.                     setString(&td->td_make, va_arg(ap, char *));
  525.                     field = FIELD_MAKE;
  526.                     break;
  527.             case TIFFTAG_MODEL:
  528.                     setString(&td->td_model, va_arg(ap, char *));
  529.                     field = FIELD_MODEL;
  530.                     break;
  531.             case TIFFTAG_SOFTWARE:
  532.                     setString(&td->td_software, va_arg(ap, char *));
  533.                     field = FIELD_SOFTWARE;
  534.                     break;
  535.             case TIFFTAG_ORIENTATION:
  536.                     td->td_orientation = va_arg(ap, int);
  537.                     field = FIELD_ORIENTATION;
  538.                     break;
  539.             case TIFFTAG_SAMPLESPERPIXEL:
  540.                     v = va_arg(ap, int);
  541.                     if (v == 0)
  542.                             goto badvalue;
  543.                     if (v > 4) {
  544.                             TIFFError(module, "can't handle %ld-channel data", v);
  545.                             goto bad;
  546.                     }
  547.                     td->td_samplesperpixel = v;
  548.                     field = FIELD_SAMPLESPERPIXEL;
  549.                     break;
  550.             case TIFFTAG_ROWSPERSTRIP:
  551.                     v = va_arg(ap, long);
  552.                     if (v == 0)
  553.                             goto badvalue;
  554.                     td->td_rowsperstrip = v;
  555.                     field = FIELD_ROWSPERSTRIP;
  556.                     break;
  557.             case TIFFTAG_MINSAMPLEVALUE:
  558.                     td->td_minsamplevalue = va_arg(ap, int) & 0xffff;
  559.                     field = FIELD_MINSAMPLEVALUE;
  560.                     break;
  561.             case TIFFTAG_MAXSAMPLEVALUE:
  562.                     td->td_maxsamplevalue = va_arg(ap, int) & 0xffff;
  563.                     field = FIELD_MAXSAMPLEVALUE;
  564.                     break;
  565.             case TIFFTAG_XRESOLUTION:
  566.                     td->td_xresolution = va_arg(ap, dblparam_t);
  567.                     field = FIELD_RESOLUTION;
  568.                     break;
  569.             case TIFFTAG_YRESOLUTION:
  570.                     td->td_yresolution = va_arg(ap, dblparam_t);
  571.                     field = FIELD_RESOLUTION;
  572.                     break;
  573.             case TIFFTAG_PLANARCONFIG:
  574.                     v = va_arg(ap, int);
  575.                     td->td_planarconfig = v;
  576.                     field = FIELD_PLANARCONFIG;
  577.                     break;
  578.             case TIFFTAG_PAGENAME:
  579.                     setString(&td->td_pagename, va_arg(ap, char *));
  580.                     field = FIELD_PAGENAME;
  581.                     break;
  582.             case TIFFTAG_XPOSITION:
  583.                     td->td_xposition = va_arg(ap, dblparam_t);
  584.                     field = FIELD_POSITION;
  585.                     break;
  586.             case TIFFTAG_YPOSITION:
  587.                     td->td_yposition = va_arg(ap, dblparam_t);
  588.                     field = FIELD_POSITION;
  589.                     break;
  590.             case TIFFTAG_GRAYRESPONSEUNIT:
  591.                     td->td_grayresponseunit = va_arg(ap, int);
  592.                     field = FIELD_GRAYRESPONSEUNIT;
  593.                     break;
  594.             case TIFFTAG_GRAYRESPONSECURVE:
  595.                     setCurve(&td->td_grayresponsecurve, va_arg(ap, u_short *), 1L << td->td_bitspersample);
  596.                     field = FIELD_GRAYRESPONSECURVE;
  597.                     break;
  598.             case TIFFTAG_GROUP3OPTIONS:
  599.                     td->td_group3options = va_arg(ap, long);
  600.                     field = FIELD_GROUP3OPTIONS;
  601.                     break;
  602.             case TIFFTAG_GROUP4OPTIONS:
  603.                     td->td_group4options = va_arg(ap, long);
  604.                     field = FIELD_GROUP4OPTIONS;
  605.                     break;
  606.             case TIFFTAG_RESOLUTIONUNIT:
  607.                     td->td_resolutionunit = va_arg(ap, int);
  608.                     field = FIELD_RESOLUTIONUNIT;
  609.                     break;
  610.             case TIFFTAG_PAGENUMBER:
  611.                     td->td_pagenumber[0] = va_arg(ap, int);
  612.                     td->td_pagenumber[1] = va_arg(ap, int);
  613.                     field = FIELD_PAGENUMBER;
  614.                     break;
  615.             case TIFFTAG_COLORRESPONSEUNIT:
  616.                     td->td_colorresponseunit = va_arg(ap, int);
  617.                     field = FIELD_COLORRESPONSEUNIT;
  618.                     break;
  619.             case TIFFTAG_COLORRESPONSECURVE:
  620.                     v = 1L << td->td_bitspersample;
  621.                     setCurve(&td->td_redresponsecurve, va_arg(ap, u_short *), v);
  622.                     setCurve(&td->td_greenresponsecurve, va_arg(ap, u_short *), v);
  623.                     setCurve(&td->td_blueresponsecurve, va_arg(ap, u_short *), v);
  624.                     field = FIELD_COLORRESPONSECURVE;
  625.                     break;
  626.             case TIFFTAG_COLORMAP:
  627.                     v = 1L << td->td_bitspersample;
  628.                     setCurve(&td->td_redcolormap, va_arg(ap, u_short *), v);
  629.                     setCurve(&td->td_greencolormap, va_arg(ap, u_short *), v);
  630.                     setCurve(&td->td_bluecolormap, va_arg(ap, u_short *), v);
  631.                     field = FIELD_COLORMAP;
  632.                     break;
  633.             case TIFFTAG_PREDICTOR:
  634.                     td->td_predictor = va_arg(ap, int);
  635.                     field = FIELD_PREDICTOR;
  636.                     break;
  637.             case TIFFTAG_MATTEING:
  638.                     td->td_matteing = va_arg(ap, int);
  639.                     field = FIELD_MATTEING;
  640.                     break;
  641.             case TIFFTAG_BADFAXLINES:
  642.                     td->td_badfaxlines = va_arg(ap, long);
  643.                     field = FIELD_BADFAXLINES;
  644.                     break;
  645.             case TIFFTAG_CLEANFAXDATA:
  646.                     td->td_cleanfaxdata = va_arg(ap, int);
  647.                     field = FIELD_CLEANFAXDATA;
  648.                     break;
  649.             case TIFFTAG_CONSECUTIVEBADFAXLINES:
  650.                     td->td_badfaxrun = va_arg(ap, int);
  651.                     field = FIELD_BADFAXRUN;
  652.                     break;
  653.         }
  654.         if (field >= 0) {
  655.                 TIFFSetFieldBit(tif, field);
  656.                 tif->tif_flags |= TIFF_DIRTYDIRECT;
  657.         }
  658.         va_end(ap);
  659.         return(status);
  660. badvalue:
  661.         TIFFError(module, "bad value %ld for '%s'", v, FieldWithTag(tag)->field_name);
  662. bad:
  663.         va_end(ap);
  664.         return(0);
  665. }
  666.  
  667. /****************************************************************************
  668.  * Setup a default directory structure.
  669.  */
  670. int
  671. TIFFDefaultDirectory(
  672.     TIFF     *tif
  673.     )
  674. {
  675.         register TIFFDirectory    *td = &tif->tif_dir;
  676.  
  677.         bzero(td, sizeof(*td));
  678.         td->td_fillorder = FILLORDER_MSB2LSB;
  679.         td->td_bitspersample = 1;
  680.         td->td_threshholding = THRESHHOLD_BILEVEL;
  681.         td->td_orientation = ORIENTATION_TOPLEFT;
  682.         td->td_samplesperpixel = 1;
  683.         td->td_predictor = 1;
  684.         td->td_rowsperstrip = 0xffffffffL;
  685.         td->td_grayresponseunit = GRAYRESPONSEUNIT_100S;
  686.         td->td_resolutionunit = RESUNIT_INCH;
  687.         td->td_colorresponseunit = COLORRESPONSEUNIT_100S;
  688.         TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
  689.  
  690.         /*
  691.          * NB: The directory is marked dirty as a result of setting up the default compression scheme.  However, this really
  692.          * isn't correct -- we want TIFF_DIRTYDIRECT to be set only if the user does something.  We could just do the setup
  693.          * by hand, but it seems better to use the normal mechanism (i.e. TIFFSetField).
  694.          */
  695.         tif->tif_flags &= ~TIFF_DIRTYDIRECT;
  696.         return(1);
  697. }
  698.  
  699. /****************************************************************************
  700.  * Read the next TIFF directory from a file and convert it to the internal format.
  701.  * We read directories sequentially.
  702.  */
  703. int
  704. TIFFReadDirectory(
  705.     TIFF     *tif
  706.     )
  707. {
  708.     static char        *module = "TIFFReadDirectory";
  709.            register TIFFDirEntry     *dp;
  710.         register int         n;
  711.         register TIFFDirectory     *td = NULL;
  712.         TIFFDirEntry         *dir = NULL;
  713.         long             v;
  714.         TIFFFieldInfo         *fip;
  715.         u_short         dircount;
  716.         char             *cp;
  717.         int             diroutoforderwarning = 0;
  718.         int            ok;
  719.  
  720.         tif->tif_diroff = tif->tif_nextdiroff;
  721.            if (tif->tif_diroff == 0)                /* no more directories */
  722.                 return(0);
  723.         if (!SeekOK(tif->tif_fd, tif->tif_diroff)) {
  724.                    TIFFError(module, "seek error accessing TIFF directory");
  725.                 return(0);
  726.         }
  727.         if (!ReadOK(tif->tif_fd, &dircount, sizeof(short))) {
  728.                 TIFFError(module, "can't read TIFF directory count");
  729.                 return(0);
  730.         }
  731.         if (tif->tif_flags & TIFF_SWAB)
  732.                    TIFFSwabShort(&dircount);
  733.         if ((dir = (TIFFDirEntry *)malloc((long)dircount * sizeof(TIFFDirEntry))) == NULL) {
  734.                 TIFFError(module, "out of memory reading TIFF directory");
  735.                 return(0);
  736.         }
  737.         if (!ReadOK(tif->tif_fd, dir, (long)dircount * sizeof(TIFFDirEntry))) {
  738.                 TIFFError(module, "can't read TIFF directory");
  739.                 goto bad;
  740.         }
  741.  
  742.         /*
  743.          * Read offset to next directory for sequential scans.
  744.          */
  745.         if (!ReadOK(tif->tif_fd, &tif->tif_nextdiroff, sizeof(long)))
  746.                 tif->tif_nextdiroff = 0;
  747.         if (tif->tif_flags & TIFF_SWAB)
  748.                 TIFFSwabLong((u_long *)&tif->tif_nextdiroff);
  749.  
  750.         tif->tif_flags &= ~TIFF_BEENWRITING;       /* reset before new dir */
  751.  
  752.         /*
  753.          * Setup default value and then make a pass over the fields to check type and tag information,
  754.          * and to extract info required to size data structures.  A second pass is made afterwards
  755.          * to read in everthing not taken in the first pass.
  756.          */
  757.         td = &tif->tif_dir;
  758.         if (tif->tif_diroff != tif->tif_header.tiff_diroff) {
  759.             /*** free any old stuff and reinit ***/
  760.                 TIFFFreeDirectory(tif);
  761.         }
  762.         TIFFDefaultDirectory(tif);
  763.  
  764.         /*
  765.          * Electronic Arts writes gray-scale TIFF files without a PlanarConfiguration directory entry.
  766.          * Thus we setup a default value here, even though the TIFF spec says there is no default value.
  767.          */
  768.         TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
  769.         for (fip = FieldInfo, dp = dir, n = dircount; n > 0; n--, dp++) {
  770.                 if (tif->tif_flags & TIFF_SWAB) {
  771.                            TIFFSwabArrayOfShort(&dp->tdir_tag, 2);
  772.                         TIFFSwabArrayOfLong(&dp->tdir_count, 2);
  773.                 }
  774.            /*
  775.          * Find the field information entry for this tag.
  776.          *
  777.          * Silicon Beach (at least) writes unordered directory tags (violating the spec).  Handle
  778.            * it here, but be obnoxious (maybe they'll fix it?).
  779.          */
  780.                 if (dp->tdir_tag < fip->field_tag) {
  781.                         if (!diroutoforderwarning) {
  782.                                 TIFFWarning(tif->tif_name, "Invalid TIFF directory; tags are not sorted in ascending order");
  783.                                 diroutoforderwarning = 1;
  784.                         }
  785.                         fip = FieldInfo;          /* O(n^2) */
  786.                 }
  787.                 while (fip < &FieldInfo[NFIELDINFO] && fip->field_tag < dp->tdir_tag)
  788.                            fip++;
  789.                 if (fip >= &FieldInfo[NFIELDINFO] || fip->field_tag != dp->tdir_tag) {
  790.                            TIFFWarning(tif->tif_name, "ignoring unknown field with tag %u (0x%x)", dp->tdir_tag, dp->tdir_tag);
  791.                         dp->tdir_tag = IGNORE;
  792.                         fip = FieldInfo;           /* restart search */
  793.                         continue;
  794.                 }
  795.  
  796.          /*
  797.          * Null out old tags that we ignore.
  798.          */
  799.                 if (fip->field_bit == (u_short)-1) {
  800.                            dp->tdir_tag = IGNORE;
  801.                         continue;
  802.                 }
  803.  
  804.          /*
  805.          * Check data type.
  806.          */
  807.                 while ((TIFFDataType)dp->tdir_type != fip->field_type) {
  808.                         fip++;
  809.                         if (fip >= &FieldInfo[NFIELDINFO] || fip->field_tag != dp->tdir_tag) {
  810.                                 TIFFError(module, "wrong data type %u for field '%s'", dp->tdir_type, fip[-1].field_name);
  811.                                 goto bad;
  812.                         }
  813.                 }
  814.                 switch (dp->tdir_tag) {
  815.                     case TIFFTAG_STRIPOFFSETS:
  816.                     case TIFFTAG_STRIPBYTECOUNTS:
  817.                             TIFFSetFieldBit(tif, fip->field_bit);
  818.                             break;
  819.                     case TIFFTAG_IMAGELENGTH:
  820.                     case TIFFTAG_PLANARCONFIG:
  821.                     case TIFFTAG_SAMPLESPERPIXEL:
  822.                             if (!TIFFSetField(tif, dp->tdir_tag, (int)TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset)))
  823.                                     goto bad;
  824.                             break;
  825.                     case TIFFTAG_ROWSPERSTRIP:
  826.                             if (!TIFFSetField(tif, dp->tdir_tag, (long)TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset)))
  827.                                     goto bad;
  828.                             break;
  829.                 }
  830.         }
  831.  
  832.         /*
  833.          * Allocate directory structure and setup defaults.
  834.          */
  835.         if (!TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS)) {
  836.                 MissingRequired(tif, "ImageLength");
  837.                 goto bad;
  838.         }
  839.         if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) {
  840.                 MissingRequired(tif, "PlanarConfiguration");
  841.                 goto bad;
  842.         }
  843.         td->td_stripsperimage = (td->td_rowsperstrip == 0xffffffffL ? (td->td_imagelength != 0 ? 1 : 0) : howmany(td->td_imagelength, td->td_rowsperstrip));
  844.         td->td_nstrips = td->td_stripsperimage;
  845.         if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
  846.                    td->td_nstrips *= td->td_samplesperpixel;
  847.         if (td->td_nstrips > 0 && !TIFFFieldSet(tif, FIELD_STRIPOFFSETS)) {
  848.                 MissingRequired(tif, "StripOffsets");
  849.                 goto bad;
  850.         }
  851.  
  852.         /*
  853.          * Second pass: extract other information.
  854.          *
  855.          * Should do a better job of verifying values.
  856.          */
  857.         for (dp = dir, n = dircount; n > 0; n--, dp++) {
  858.                 if (dp->tdir_tag == IGNORE)
  859.                         continue;
  860.                 if (dp->tdir_type == TIFF_ASCII) {
  861.                         if (dp->tdir_count > 0) {
  862.                                    if ((cp = malloc(dp->tdir_count)) == NULL)
  863.                                            goto bad;
  864.                                 ok = (TIFFFetchString(tif, dp, cp) && TIFFSetField(tif, dp->tdir_tag, cp));
  865.                                 free(cp);
  866.                                 if (!ok)
  867.                                            goto bad;
  868.                         }
  869.                         continue;
  870.                 }
  871.                 if (dp->tdir_type == TIFF_RATIONAL) {
  872.                         if (!TIFFSetField(tif, dp->tdir_tag, TIFFFetchRational(tif, dp)))
  873.                                    goto bad;
  874.                            continue;
  875.                 }
  876.                 switch (dp->tdir_tag) {
  877.                     case TIFFTAG_COMPRESSION:
  878.  
  879.          /*
  880.          * The 5.0 spec says the compression tag has one value, while earlier specs say it has
  881.          * one value per sample.  Because of this, we accept the tag if one value is supplied.
  882.          */
  883.                             if (dp->tdir_count == 1) {
  884.                                     v = TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset);
  885.                                     if (!TIFFSetField(tif, TIFFTAG_COMPRESSION, (int)v))
  886.                                             goto bad;
  887.                                     break;
  888.                             }
  889.                             /*** fall thru... ***/
  890.                     case TIFFTAG_MINSAMPLEVALUE:
  891.                     case TIFFTAG_MAXSAMPLEVALUE:
  892.                     case TIFFTAG_BITSPERSAMPLE:
  893.                             if (!TIFFFetchPerSampleShorts(tif, dp, &v) || !TIFFSetField(tif, dp->tdir_tag, (int)v))
  894.                                     goto bad;
  895.                             break;
  896.                     case TIFFTAG_STRIPOFFSETS:
  897.                             if (!TIFFFetchStripThing(tif, dp, td->td_nstrips, &td->td_stripoffset))
  898.                                     goto bad;
  899.                             TIFFSetFieldBit(tif, FIELD_STRIPOFFSETS);
  900.                             break;
  901.                     case TIFFTAG_STRIPBYTECOUNTS:
  902.                             if (!TIFFFetchStripThing(tif, dp, td->td_nstrips, &td->td_stripbytecount))
  903.                                     goto bad;
  904.                             TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS);
  905.                             break;
  906.                     case TIFFTAG_IMAGELENGTH:
  907.                     case TIFFTAG_ROWSPERSTRIP:
  908.                     case TIFFTAG_SAMPLESPERPIXEL:
  909.                     case TIFFTAG_PLANARCONFIG:
  910.                             /*** handled in first pass above ***/
  911.                             break;
  912.                     case TIFFTAG_GRAYRESPONSECURVE:
  913.                     case TIFFTAG_COLORRESPONSECURVE:
  914.                     case TIFFTAG_COLORMAP:
  915.                             v = (1L << td->td_bitspersample) * sizeof(u_short);
  916.                             if ((cp = malloc(dp->tdir_tag == TIFFTAG_GRAYRESPONSECURVE ? v : v * 3)) == NULL) 
  917.                                     goto bad;
  918.                             ok = (TIFFFetchData(tif, dp, cp) && TIFFSetField(tif, dp->tdir_tag, cp, cp + v, cp + 2 * v));
  919.                             free(cp);
  920.                             if (!ok)
  921.                                     goto bad;
  922.                             break;
  923.                     case TIFFTAG_PAGENUMBER:
  924.                             TIFFUnpackShorts(tif, td->td_pagenumber, dp);
  925.                             TIFFSetFieldBit(tif, FIELD_PAGENUMBER);
  926.                             break;
  927. /*
  928.  * BEGIN REV 4.0 COMPATIBILITY 
  929.  */
  930.                     case TIFFTAG_OSUBFILETYPE:
  931.                             v = 0;
  932.                             switch ((int)TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset)) {
  933.                                 case OFILETYPE_REDUCEDIMAGE:
  934.                                         v = FILETYPE_REDUCEDIMAGE;
  935.                                         break;
  936.                                 case OFILETYPE_PAGE:
  937.                                         v = FILETYPE_PAGE;
  938.                                         break;
  939.                             }
  940.                             if (!TIFFSetField(tif, dp->tdir_tag, (int)v))
  941.                                     goto bad;
  942.                             break;
  943. /*
  944.  * END REV 4.0 COMPATIBILITY 
  945.  */
  946.                     default:
  947.                             if (!TIFFSetField(tif, dp->tdir_tag, (int)TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset)))
  948.                                     goto bad;
  949.                             break;
  950.                 }
  951.         }
  952.         if (td->td_nstrips > 0 && !TIFFFieldSet(tif, FIELD_STRIPBYTECOUNTS)) {
  953.  
  954.     /*
  955.          * Some manufacturers violate the spec by not giving the size of the strips.  In this case, assume there
  956.          * is one uncompressed strip of data.
  957.          */
  958.                 if (td->td_nstrips > 1) {
  959.                         MissingRequired(tif, "StripByteCounts");
  960.                         goto bad;
  961.                 }
  962.                 TIFFWarning(tif->tif_name, "TIFF directory is missing required \"%s\" field, calculating from imagelength", FieldWithTag(TIFFTAG_STRIPBYTECOUNTS)->field_name);
  963.                 td->td_stripbytecount = (u_long *)malloc(sizeof(u_long));
  964.                 if (td->td_compression != COMPRESSION_NONE) {
  965.                         u_long     space = sizeof(TIFFHeader) + sizeof(short) + ((long)dircount * sizeof(TIFFDirEntry)) + sizeof(long);    /* calculate amount of space used by indirect values */
  966.  
  967.                         for (dp = dir, n = dircount; n > 0; n--, dp++) {
  968.                                 int     cc = (int)dp->tdir_count * datawidth[dp->tdir_type];
  969.  
  970.                                 if (cc > sizeof(long))
  971.                                         space += cc;
  972.                         }
  973.                         td->td_stripbytecount[0] = TIFFGetFileSize(tif->tif_fd) - space;
  974.                 } 
  975.                 else {
  976.                         u_long     rowbytes;
  977.  
  978.                         rowbytes = howmany(td->td_bitspersample * td->td_samplesperpixel * td->td_imagewidth, 8);
  979.                         td->td_stripbytecount[0] = td->td_imagelength * rowbytes;
  980.                 }
  981.                 TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS);
  982.                 if (!TIFFFieldSet(tif, FIELD_ROWSPERSTRIP))
  983.                         td->td_rowsperstrip = td->td_imagelength;
  984.         }
  985.         if (dir)
  986.                 free(dir);
  987.         if (!TIFFFieldSet(tif, FIELD_MAXSAMPLEVALUE))
  988.                 td->td_maxsamplevalue = (1L << td->td_bitspersample) - 1;
  989.  
  990.         /*
  991.          * Setup default compression scheme.
  992.          */
  993.         if (!TIFFFieldSet(tif, FIELD_COMPRESSION))
  994.                    TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
  995.  
  996.         /*
  997.          * Reinitialize i/o since we are starting on a new directory.
  998.          */
  999.         tif->tif_row = -1;
  1000.         tif->tif_curstrip = -1;
  1001.         tif->tif_scanlinesize = TIFFScanlineSize(tif);
  1002.         return(1);
  1003. bad:
  1004.         if (dir)
  1005.                 free(dir);
  1006.         return(0);
  1007. }
  1008.  
  1009. #define    CleanupField(field, member)    { \
  1010.                             if (TIFFFieldSet(tif, field)) { \
  1011.                                 free((char *)td->member); \
  1012.                                 td->member = 0; \
  1013.                             } \
  1014.                     }
  1015.  
  1016. /****************************************************************************
  1017.  *
  1018.  */
  1019. void
  1020. TIFFFreeDirectory(
  1021.     TIFF     *tif
  1022.     )
  1023. {
  1024.         register TIFFDirectory    *td = &tif->tif_dir;
  1025.  
  1026.         CleanupField(FIELD_GRAYRESPONSECURVE, td_grayresponsecurve);
  1027.         if (TIFFFieldSet(tif, FIELD_COLORRESPONSECURVE)) {
  1028.                 free(td->td_redresponsecurve);
  1029.                 td->td_redresponsecurve = 0;
  1030.                 free(td->td_greenresponsecurve);
  1031.                 td->td_greenresponsecurve = 0;
  1032.                 free(td->td_blueresponsecurve);
  1033.                 td->td_blueresponsecurve = 0;
  1034.         }
  1035.         if (TIFFFieldSet(tif, FIELD_COLORMAP)) {
  1036.                 free(td->td_redcolormap);
  1037.                 td->td_redcolormap = 0;
  1038.                 free(td->td_greencolormap);
  1039.                 td->td_greencolormap = 0;
  1040.                 free(td->td_bluecolormap);
  1041.                 td->td_bluecolormap = 0;
  1042.         }
  1043.         CleanupField(FIELD_DOCUMENTNAME, td_documentname);
  1044.         CleanupField(FIELD_ARTIST, td_artist);
  1045.         CleanupField(FIELD_DATETIME, td_datetime);
  1046.         CleanupField(FIELD_HOSTCOMPUTER, td_hostcomputer);
  1047.         CleanupField(FIELD_IMAGEDESCRIPTION, td_imagedescription);
  1048.         CleanupField(FIELD_MAKE, td_make);
  1049.         CleanupField(FIELD_MODEL, td_model);
  1050.         CleanupField(FIELD_SOFTWARE, td_software);
  1051.         CleanupField(FIELD_PAGENAME, td_pagename);
  1052.         if  (td->td_stripoffset) {
  1053.                 free((char *)td->td_stripoffset);
  1054.                 td->td_stripoffset = NULL;
  1055.         }
  1056.         if  (td->td_stripbytecount) {
  1057.                 free((char *)td->td_stripbytecount);
  1058.                 td->td_stripbytecount = NULL;
  1059.         }
  1060. }
  1061. #undef CleanupField
  1062.  
  1063. /****************************************************************************
  1064.  *
  1065.  */
  1066. static void
  1067. TIFFGetField1(
  1068.     TIFFDirectory     *td,
  1069.     u_short            tag,
  1070.     va_list        ap
  1071.     )
  1072. {
  1073.         switch (tag) {
  1074.             case TIFFTAG_SUBFILETYPE:
  1075.                     *va_arg(ap, u_long *) = td->td_subfiletype;
  1076.                     break;
  1077.             case TIFFTAG_IMAGEWIDTH:
  1078.                     *va_arg(ap, u_short *) = td->td_imagewidth;
  1079.                     break;
  1080.             case TIFFTAG_IMAGELENGTH:
  1081.                     *va_arg(ap, u_short *) = td->td_imagelength;
  1082.                     break;
  1083.             case TIFFTAG_BITSPERSAMPLE:
  1084.                     *va_arg(ap, u_short *) = td->td_bitspersample;
  1085.                     break;
  1086.             case TIFFTAG_COMPRESSION:
  1087.                     *va_arg(ap, u_short *) = td->td_compression;
  1088.                     break;
  1089.             case TIFFTAG_PHOTOMETRIC:
  1090.                     *va_arg(ap, u_short *) = td->td_photometric;
  1091.                     break;
  1092.             case TIFFTAG_THRESHHOLDING:
  1093.                     *va_arg(ap, u_short *) = td->td_threshholding;
  1094.                     break;
  1095.             case TIFFTAG_FILLORDER:
  1096.                     *va_arg(ap, u_short *) = td->td_fillorder;
  1097.                     break;
  1098.             case TIFFTAG_DOCUMENTNAME:
  1099.                     *va_arg(ap, char **) = td->td_documentname;
  1100.                     break;
  1101.             case TIFFTAG_ARTIST:
  1102.                     *va_arg(ap, char **) = td->td_artist;
  1103.                     break;
  1104.             case TIFFTAG_DATETIME:
  1105.                     *va_arg(ap, char **) = td->td_datetime;
  1106.                     break;
  1107.             case TIFFTAG_HOSTCOMPUTER:
  1108.                     *va_arg(ap, char **) = td->td_hostcomputer;
  1109.                     break;
  1110.             case TIFFTAG_IMAGEDESCRIPTION:
  1111.                     *va_arg(ap, char **) = td->td_imagedescription;
  1112.                     break;
  1113.             case TIFFTAG_MAKE:
  1114.                     *va_arg(ap, char **) = td->td_make;
  1115.                     break;
  1116.             case TIFFTAG_MODEL:
  1117.                     *va_arg(ap, char **) = td->td_model;
  1118.                     break;
  1119.             case TIFFTAG_SOFTWARE:
  1120.                     *va_arg(ap, char **) = td->td_software;
  1121.                     break;
  1122.             case TIFFTAG_ORIENTATION:
  1123.                     *va_arg(ap, u_short *) = td->td_orientation;
  1124.                     break;
  1125.             case TIFFTAG_SAMPLESPERPIXEL:
  1126.                     *va_arg(ap, u_short *) = td->td_samplesperpixel;
  1127.                     break;
  1128.             case TIFFTAG_ROWSPERSTRIP:
  1129.                     *va_arg(ap, u_long *) = td->td_rowsperstrip;
  1130.                     break;
  1131.             case TIFFTAG_MINSAMPLEVALUE:
  1132.                     *va_arg(ap, u_short *) = td->td_minsamplevalue;
  1133.                     break;
  1134.             case TIFFTAG_MAXSAMPLEVALUE:
  1135.                     *va_arg(ap, u_short *) = td->td_maxsamplevalue;
  1136.                     break;
  1137.             case TIFFTAG_XRESOLUTION:
  1138.                     *va_arg(ap, float *) = td->td_xresolution;
  1139.                     break;
  1140.             case TIFFTAG_YRESOLUTION:
  1141.                     *va_arg(ap, float *) = td->td_yresolution;
  1142.                     break;
  1143.             case TIFFTAG_PLANARCONFIG:
  1144.                     *va_arg(ap, u_short *) = td->td_planarconfig;
  1145.                     break;
  1146.             case TIFFTAG_XPOSITION:
  1147.                     *va_arg(ap, float *) = td->td_xposition;
  1148.                     break;
  1149.             case TIFFTAG_YPOSITION:
  1150.                     *va_arg(ap, float *) = td->td_yposition;
  1151.                     break;
  1152.             case TIFFTAG_PAGENAME:
  1153.                     *va_arg(ap, char **) = td->td_pagename;
  1154.                     break;
  1155.             case TIFFTAG_GRAYRESPONSEUNIT:
  1156.                     *va_arg(ap, u_short *) = td->td_grayresponseunit;
  1157.                     break;
  1158.             case TIFFTAG_GRAYRESPONSECURVE:
  1159.                     *va_arg(ap, u_short **) = td->td_grayresponsecurve;
  1160.                     break;
  1161.             case TIFFTAG_GROUP3OPTIONS:
  1162.                     *va_arg(ap, u_long *) = td->td_group3options;
  1163.                     break;
  1164.             case TIFFTAG_GROUP4OPTIONS:
  1165.                     *va_arg(ap, u_long *) = td->td_group4options;
  1166.                     break;
  1167.             case TIFFTAG_RESOLUTIONUNIT:
  1168.                     *va_arg(ap, u_short *) = td->td_resolutionunit;
  1169.                     break;
  1170.             case TIFFTAG_PAGENUMBER:
  1171.                     *va_arg(ap, u_short *) = td->td_pagenumber[0];
  1172.                     *va_arg(ap, u_short *) = td->td_pagenumber[1];
  1173.                     break;
  1174.             case TIFFTAG_COLORRESPONSEUNIT:
  1175.                     *va_arg(ap, u_short *) = td->td_colorresponseunit;
  1176.                     break;
  1177.             case TIFFTAG_COLORRESPONSECURVE:
  1178.                     *va_arg(ap, u_short **) = td->td_redresponsecurve;
  1179.                     *va_arg(ap, u_short **) = td->td_greenresponsecurve;
  1180.                     *va_arg(ap, u_short **) = td->td_blueresponsecurve;
  1181.                     break;
  1182.             case TIFFTAG_COLORMAP:
  1183.                     *va_arg(ap, u_short **) = td->td_redcolormap;
  1184.                     *va_arg(ap, u_short **) = td->td_greencolormap;
  1185.                     *va_arg(ap, u_short **) = td->td_bluecolormap;
  1186.                     break;
  1187.             case TIFFTAG_PREDICTOR:
  1188.                     *va_arg(ap, u_short *) = td->td_predictor;
  1189.                     break;
  1190.             case TIFFTAG_STRIPOFFSETS:
  1191.                     *va_arg(ap, u_long **) = td->td_stripoffset;
  1192.                     break;
  1193.             case TIFFTAG_STRIPBYTECOUNTS:
  1194.                     *va_arg(ap, u_long **) = td->td_stripbytecount;
  1195.                     break;
  1196.             case TIFFTAG_MATTEING:
  1197.                     *va_arg(ap, u_short *) = td->td_matteing;
  1198.                     break;
  1199.             case TIFFTAG_BADFAXLINES:
  1200.                     *va_arg(ap, u_long *) = td->td_badfaxlines;
  1201.                     break;
  1202.             case TIFFTAG_CLEANFAXDATA:
  1203.                     *va_arg(ap, u_short *) = td->td_cleanfaxdata;
  1204.                     break;
  1205.             case TIFFTAG_CONSECUTIVEBADFAXLINES:
  1206.                     *va_arg(ap, u_long *) = td->td_badfaxrun;
  1207.                     break;
  1208.         }
  1209.         va_end(ap);
  1210. }
  1211.  
  1212. /****************************************************************************
  1213.  * Return the value of a field in the internal directory structure.
  1214.  */
  1215. int
  1216. TIFFGetField(
  1217.     TIFF    *tif, 
  1218.     u_short    tag,
  1219.          ...
  1220.          )
  1221. {
  1222.     static char    *module = "TIFFGetField";
  1223.         TIFFFieldInfo    *fip = FindFieldInfo(tag, (TIFFDataType)0);
  1224.  
  1225.         if (!fip)
  1226.                 TIFFError(module, "unknown field, tag %u", tag);
  1227.         else if (TIFFFieldSet(tif, fip->field_bit)) {
  1228.                    va_list    ap;
  1229.  
  1230.                 va_start(ap, tag);
  1231.                 TIFFGetField1(&tif->tif_dir, tag, ap);
  1232.                 va_end(ap);
  1233.                 return(1);
  1234.         }
  1235.         return(0);
  1236. }
  1237.  
  1238. /****************************************************************************
  1239.  * Internal interface to TIFFGetField...
  1240.  */
  1241. static void
  1242. TIFFgetfield(
  1243.     TIFFDirectory    *td, 
  1244.     u_short       tag,
  1245.          ...
  1246.          )
  1247. {
  1248.         va_list    ap;
  1249.  
  1250.         va_start(ap, tag);
  1251.         TIFFGetField1(td, tag, ap);
  1252.         va_end(ap);
  1253. }
  1254.  
  1255. /****************************************************************************
  1256.  * Link the current directory into the directory chain for the file.
  1257.  */
  1258. static int
  1259. TIFFLinkDirectory(
  1260.     register TIFF    *tif
  1261.     )
  1262. {
  1263.         static char     *module = "TIFFLinkDirectory";
  1264.         u_short     dircount;
  1265.         long         nextdir;
  1266.  
  1267.         tif->tif_diroff = (lseek(tif->tif_fd, 0L, L_XTND) + 1) &~ 1L;
  1268.         if (tif->tif_header.tiff_diroff == 0) {
  1269.  
  1270.     /*
  1271.          * First directory, overwrite header.
  1272.          */
  1273.                 tif->tif_header.tiff_diroff = tif->tif_diroff;
  1274.                 lseek(tif->tif_fd, 0, L_SET);
  1275.                 if (!WriteOK(tif->tif_fd, &tif->tif_header, sizeof(tif->tif_header))) {
  1276.                         TIFFError(module, "error writing TIFF header");
  1277.                         return(0);
  1278.                 }
  1279.                 return(1);
  1280.         }
  1281.  
  1282.         /*
  1283.          * Not the first directory, search to the last and append.
  1284.          */
  1285.         nextdir = tif->tif_header.tiff_diroff;
  1286.         do {
  1287.                 if (!SeekOK(tif->tif_fd, nextdir) || !ReadOK(tif->tif_fd, &dircount, sizeof(dircount))) {
  1288.                         TIFFError(module, "error fetching directory count");
  1289.                         return(0);
  1290.                 }
  1291.                 if (tif->tif_flags & TIFF_SWAB)
  1292.                            TIFFSwabShort(&dircount);
  1293.                 lseek(tif->tif_fd, dircount * sizeof(TIFFDirEntry), L_INCR);
  1294.                 if (!ReadOK(tif->tif_fd, &nextdir, sizeof(nextdir))) {
  1295.                         TIFFError(module, "error fetching directory link");
  1296.                         return(0);
  1297.                 }
  1298.                 if (tif->tif_flags & TIFF_SWAB)
  1299.                         TIFFSwabLong((u_long *)&nextdir);
  1300.         } while (nextdir != 0);
  1301.         lseek(tif->tif_fd, -sizeof(nextdir), L_INCR);
  1302.         if (!WriteOK(tif->tif_fd, &tif->tif_diroff, sizeof(tif->tif_diroff))) {
  1303.                 TIFFError(module, "error writing directory link");
  1304.                 return(0);
  1305.         }
  1306.         return(1);
  1307. }
  1308.  
  1309. static long    dataoff = 0;
  1310.  
  1311. /****************************************************************************
  1312.  * Write a contiguous directory item.
  1313.  */
  1314. static int
  1315. TIFFWriteData(
  1316.     TIFF            *tif,
  1317.            TIFFDirEntry     *dir,
  1318.         char            *cp
  1319.         )
  1320. {
  1321.     static char    *module = "TIFFWriteData";
  1322.         u_long         cc;
  1323.  
  1324.         dir->tdir_offset = dataoff;
  1325.         cc = dir->tdir_count * (long)datawidth[dir->tdir_type];
  1326.     if (SeekOK(tif->tif_fd, dir->tdir_offset) && WriteOK(tif->tif_fd, cp, cc)) { 
  1327.                 dataoff += ((cc + 1) & ~1);
  1328.                 return(1);
  1329.         }
  1330.         TIFFError(module, "error writing data for field '%s'", FieldWithTag(dir->tdir_tag)->field_name);
  1331.         return(0);
  1332. }
  1333.  
  1334. /****************************************************************************
  1335.  *
  1336.  */
  1337. static int
  1338. TIFFWriteStripThing(
  1339.     TIFF          *tif, 
  1340.     u_short     tag, 
  1341.     TIFFDirEntry     *dir, 
  1342.     u_long         *lp
  1343.     )
  1344. {
  1345.         dir->tdir_tag = tag;
  1346.         dir->tdir_type = (short)TIFF_LONG;                 /* XXX */
  1347.         dir->tdir_count = tif->tif_dir.td_nstrips;
  1348.         if (dir->tdir_count > 1)
  1349.                 return(TIFFWriteData(tif, dir, (char *)lp));
  1350.         dir->tdir_offset = *lp;
  1351.         return(1);
  1352. }
  1353.  
  1354. /****************************************************************************
  1355.  *
  1356.  */
  1357. static int
  1358. TIFFWriteRational(
  1359.     TIFF             *tif, 
  1360.     u_short          tag, 
  1361.     TIFFDirEntry    *dir, 
  1362.     float            v
  1363.     )
  1364. {
  1365.         long     t[2];
  1366.  
  1367.         dir->tdir_tag = tag;
  1368.         dir->tdir_type = (short)TIFF_RATIONAL;
  1369.         dir->tdir_count = 1;
  1370.         /*** need algorithm to convert ... XXX ***/
  1371.         t[0] = v * 10000.0;
  1372.         t[1] = 10000;
  1373.         return(TIFFWriteData(tif, dir, (char *)t));
  1374. }
  1375.  
  1376. /****************************************************************************
  1377.  *
  1378.  */
  1379. static int
  1380. TIFFWritePerSampleShorts(
  1381.     TIFF               *tif, 
  1382.     u_short          tag, 
  1383.     TIFFDirEntry     *dir, 
  1384.     short              v
  1385.     )
  1386. {
  1387.         short     w[4];
  1388.         int     i;
  1389.         int    samplesperpixel = tif->tif_dir.td_samplesperpixel;
  1390.  
  1391.         dir->tdir_tag = tag;
  1392.         dir->tdir_type = (short)TIFF_SHORT;
  1393.         dir->tdir_count = samplesperpixel;
  1394.         if (samplesperpixel <= 2) {
  1395.                 if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) {
  1396.                         dir->tdir_offset = (long)v << 16;
  1397.                         if (samplesperpixel == 2)
  1398.                                 dir->tdir_offset |= (v & 0xffff);
  1399.                 } 
  1400.                 else {
  1401.                         dir->tdir_offset = v & 0xffff;
  1402.                         if (samplesperpixel == 2)
  1403.                                 dir->tdir_offset |= ((long)v << 16);
  1404.                 }
  1405.                 return(1);
  1406.         }
  1407.         for (i = 0; i < samplesperpixel; i++)
  1408.                 w[i] = v;
  1409.         return(TIFFWriteData(tif, dir, (char *)w));
  1410. }
  1411.  
  1412. /*
  1413.  * Shorthands for setting up and writing directory... 
  1414.  */
  1415. #define MakeShortDirent(tag, v)            dir->tdir_tag = tag; \
  1416.                             dir->tdir_type = (short)TIFF_SHORT; \
  1417.                             dir->tdir_count = 1; \
  1418.                             dir->tdir_offset = TIFFInsertData(tif, (int)TIFF_SHORT, v); \
  1419.                             dir++
  1420. #define    WriteRationalPair(tag1, v1, tag2, v2)     (TIFFWriteRational(tif, tag1, dir++, v1) && TIFFWriteRational(tif, tag2, dir++, v2))
  1421.  
  1422. /****************************************************************************
  1423.  * Write the contents of the current directory to the specified file.  This routine doesn't
  1424.  * handle overwriting a directory with auxiliary storage that's been changed.
  1425.  */
  1426. int
  1427. TIFFWriteDirectory(
  1428.     TIFF     *tif
  1429.     )
  1430. {
  1431.     static char    *module = "TIFFWriteDirectory";
  1432.         short         dircount, v;
  1433.         long        nfields, dirsize;
  1434.         char         *data, *cp;
  1435.         TIFFFieldInfo     *fip;
  1436.         TIFFDirEntry     *dir;
  1437.         TIFFDirectory     *td;
  1438.         u_long         b, off;
  1439.         u_long        fields[sizeof(td->td_fieldsset) / sizeof(u_long)];
  1440.  
  1441.         if (tif->tif_mode == O_RDONLY)
  1442.                 return(1);
  1443.         if (tif->tif_rawcc > 0 && !TIFFFlushData(tif)) {
  1444.                 TIFFError(module, "error flushing data before directory write");
  1445.                 return(0);
  1446.         }
  1447.  
  1448.         /*
  1449.          * Clear write state so that subsequent images with different characteristics get the right buffers
  1450.          * setup for them.
  1451.          */
  1452.         if (tif->tif_close)
  1453.                 (*tif->tif_close)(tif);
  1454.         if (tif->tif_cleanup)
  1455.                 (*tif->tif_cleanup)(tif);
  1456.         if (tif->tif_rawdata) {
  1457.                 free(tif->tif_rawdata);
  1458.                 tif->tif_rawdata = NULL;
  1459.                 tif->tif_rawcc = 0;
  1460.         }
  1461.         tif->tif_flags &= ~(TIFF_BEENWRITING | TIFF_BUFFERSETUP);
  1462.  
  1463.         td = &tif->tif_dir;
  1464.  
  1465.         /*
  1466.          * Size the directory so that we can calculate offsets for the data items that aren't kept
  1467.          * in-place in each field.
  1468.          */
  1469.         nfields = 0;
  1470.         for (b = 0; b <= FIELD_LAST; b++)
  1471.                 if (TIFFFieldSet(tif, b))
  1472.                         nfields += (b < FIELD_SUBFILETYPE ? 2 : 1);
  1473.         dirsize = nfields * sizeof(TIFFDirEntry);
  1474.         if ((data = malloc(dirsize)) == NULL) {
  1475.                 TIFFError(module, "out of memory writing directory");
  1476.                 return(0);
  1477.         }
  1478.  
  1479.         /*
  1480.          * Directory hasn't been placed yet, put it at the end of the file and link it
  1481.          * into the existing directory structure.
  1482.          */
  1483.         if (tif->tif_diroff == 0 && !TIFFLinkDirectory(tif))
  1484.                 return(0);
  1485.         dataoff = tif->tif_diroff + sizeof(short) + dirsize + sizeof(long);
  1486.         if (dataoff & 1L)
  1487.                 dataoff++;
  1488.     lseek(tif->tif_fd, dataoff, L_SET);
  1489.         dir = (TIFFDirEntry *)data;
  1490.  
  1491.         /*
  1492.          * Setup external form of directory entries and write data items.
  1493.          */
  1494.         bcopy(td->td_fieldsset, fields, sizeof(fields));
  1495.         for (fip = FieldInfo; fip < &FieldInfo[NFIELDINFO]; fip++) {
  1496.                 if (fip->field_bit == (u_short)-1 || !FieldSet(fields, fip->field_bit))
  1497.                         continue;
  1498.                 if (fip->field_type == TIFF_ASCII) {
  1499.                         TIFFgetfield(td, fip->field_tag, &cp);
  1500.                         dir->tdir_tag = fip->field_tag;
  1501.                         dir->tdir_type = TIFF_ASCII;
  1502. #if 0    /* LIN### */
  1503.                         dir->tdir_count = strlen(cp) + 1;
  1504.                     if (!TIFFWriteData(tif, dir++, cp))
  1505.                             goto bad;
  1506. #else    /* LIN### */
  1507.                         if ((dir->tdir_count = strlen(cp) + 1) > 4) {
  1508.                             if (!TIFFWriteData(tif, dir, cp))
  1509.                                     goto bad;
  1510.                     }
  1511.                     else
  1512.                         bcopy(cp, &dir->tdir_offset, dir->tdir_count);
  1513.                        dir++;
  1514. #endif    /* LIN### */
  1515.                         ResetFieldBit(fields, fip->field_bit);
  1516.                         continue;
  1517.                 }
  1518.                 switch (fip->field_bit) {
  1519.                     case FIELD_STRIPOFFSETS:
  1520.                     case FIELD_STRIPBYTECOUNTS:
  1521.                             if (!TIFFWriteStripThing(tif, fip->field_tag, dir++, fip->field_bit == FIELD_STRIPOFFSETS ? td->td_stripoffset : td->td_stripbytecount))
  1522.                                     goto bad;
  1523.                             break;
  1524.                     case FIELD_GRAYRESPONSECURVE:
  1525.                             dir->tdir_tag = fip->field_tag;
  1526.                             dir->tdir_type = (short)TIFF_SHORT;
  1527.                             dir->tdir_count = 1L << td->td_bitspersample;
  1528.  
  1529. #define    WRITE(x)    TIFFWriteData(tif, dir, (char *)x)
  1530.  
  1531.                             if (!WRITE(td->td_grayresponsecurve))
  1532.                                     goto bad;
  1533.                             dir++;
  1534.                             break;
  1535.                     case FIELD_COLORRESPONSECURVE:
  1536.                     case FIELD_COLORMAP:
  1537.                             dir->tdir_tag = fip->field_tag;
  1538.                             dir->tdir_type = (short)TIFF_SHORT;
  1539.                             /*** XXX -- yech, fool TIFFWriteData ***/
  1540.                             dir->tdir_count = 1L << td->td_bitspersample;
  1541.                             off = dataoff;
  1542.                             if (fip->field_tag == TIFFTAG_COLORMAP) {
  1543.                                     if (!WRITE(td->td_redcolormap) || !WRITE(td->td_greencolormap) || !WRITE(td->td_bluecolormap))
  1544.                                             goto bad;
  1545.                             } 
  1546.                             else {
  1547.                                     if (!WRITE(td->td_redresponsecurve) || !WRITE(td->td_greenresponsecurve) || !WRITE(td->td_blueresponsecurve))
  1548.                                             goto bad;
  1549.                             }
  1550. #undef    WRITE
  1551.                             dir->tdir_count *= 3L;
  1552.                             dir->tdir_offset = off;
  1553.                             dir++;
  1554.                             break;
  1555.                     case FIELD_IMAGEDIMENSIONS:
  1556.                             MakeShortDirent(TIFFTAG_IMAGEWIDTH, td->td_imagewidth);
  1557.                             MakeShortDirent(TIFFTAG_IMAGELENGTH,td->td_imagelength);
  1558.                             break;
  1559.                     case FIELD_POSITION:
  1560.                             if (!WriteRationalPair(TIFFTAG_XPOSITION, td->td_xposition, TIFFTAG_YPOSITION, td->td_yposition))
  1561.                                     goto bad;
  1562.                             break;
  1563.                     case FIELD_RESOLUTION:
  1564.                             if (!WriteRationalPair(TIFFTAG_XRESOLUTION, td->td_xresolution, TIFFTAG_YRESOLUTION, td->td_yresolution))
  1565.                                     goto bad;
  1566.                             break;
  1567.                     case FIELD_BITSPERSAMPLE:
  1568.                     case FIELD_MINSAMPLEVALUE:
  1569.                     case FIELD_MAXSAMPLEVALUE:
  1570.                             TIFFgetfield(td, fip->field_tag, &v);
  1571.                             if (!TIFFWritePerSampleShorts(tif, fip->field_tag, dir++, v))
  1572.                                     goto bad;
  1573.                             break;
  1574.                     case FIELD_PAGENUMBER: {
  1575.                             short     v1, v2;
  1576.  
  1577.                             dir->tdir_tag = TIFFTAG_PAGENUMBER;
  1578.                             dir->tdir_type = (short)TIFF_SHORT;
  1579.                             dir->tdir_count = 2;
  1580.                             TIFFgetfield(td, TIFFTAG_PAGENUMBER, &v1, &v2);
  1581.                             if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN)
  1582.                                     dir->tdir_offset = (v1 << 16) | (v2 & 0xffff);
  1583.                             else
  1584.                                     dir->tdir_offset = (v2 << 16) | (v1 & 0xffff);
  1585.                             dir++;
  1586.                             break;
  1587.                     }
  1588.                     default:
  1589.                             dir->tdir_tag = fip->field_tag;
  1590.                             dir->tdir_type = fip->field_type;
  1591.                             dir->tdir_count = fip->field_count;
  1592.                             if (fip->field_type == TIFF_SHORT) {
  1593.                                     TIFFgetfield(td, fip->field_tag, &v);
  1594.                                     dir->tdir_offset = TIFFInsertData(tif, dir->tdir_type, v);
  1595.                             } 
  1596.                             else
  1597.                                     TIFFgetfield(td, fip->field_tag, &dir->tdir_offset);
  1598.                             dir++;
  1599.                             break;
  1600.                 }
  1601.                 ResetFieldBit(fields, fip->field_bit);
  1602.         }
  1603.  
  1604.         /*
  1605.          * Write directory.
  1606.          */
  1607.     lseek(tif->tif_fd, tif->tif_diroff, L_SET);
  1608.         dircount = nfields;
  1609.         if (!WriteOK(tif->tif_fd, &dircount, sizeof(short))) {
  1610.                 TIFFError(module, "error writing directory count");
  1611.                 goto bad;
  1612.         }
  1613.         if (!WriteOK(tif->tif_fd, data, dirsize)) {
  1614.                 TIFFError(module, "error writing directory contents");
  1615.                 goto bad;
  1616.         }
  1617.         if (!WriteOK(tif->tif_fd, &tif->tif_nextdiroff, sizeof(long))) {
  1618.                 TIFFError(module, "error writing directory link");
  1619.                 goto bad;
  1620.         }
  1621.         TIFFFreeDirectory(tif);
  1622.         free(data);
  1623.         tif->tif_flags &= ~TIFF_DIRTYDIRECT;
  1624.  
  1625.         /*
  1626.          * Reset directory-related state for subsequent directories.
  1627.          */
  1628.         TIFFDefaultDirectory(tif);
  1629.         tif->tif_diroff = 0;
  1630.         tif->tif_curoff = 0;
  1631.         tif->tif_row = -1;
  1632.         tif->tif_curstrip = -1;
  1633.         return(1);
  1634. bad:
  1635.         free(data);
  1636.         return(0);
  1637. }
  1638. #undef    MakeShortDirent
  1639. #undef    WriteRationalPair
  1640.  
  1641. /****************************************************************************
  1642.  * Set the n-th directory as the current directory.
  1643.  * NB: Directories are numbered starting at 0.
  1644.  */
  1645. int
  1646. TIFFSetDirectory(
  1647.     register TIFF    *tif,
  1648.     int                n
  1649.     )
  1650. {
  1651.         static char     *module = "TIFFSetDirectory";
  1652.         u_short     dircount;
  1653.         long         nextdir;
  1654.  
  1655.         nextdir = tif->tif_header.tiff_diroff;
  1656.         while (n-- > 0 && nextdir != 0) {
  1657.                 if (!SeekOK(tif->tif_fd, nextdir) || !ReadOK(tif->tif_fd, &dircount, sizeof(dircount))) {
  1658.                         TIFFError(module, "error fetching directory count");
  1659.                         return(0);
  1660.                 }
  1661.                 if (tif->tif_flags & TIFF_SWAB)
  1662.                         TIFFSwabShort(&dircount);
  1663.                 lseek(tif->tif_fd, (long)dircount * sizeof(TIFFDirEntry), L_INCR);
  1664.                 if (!ReadOK(tif->tif_fd, &nextdir, sizeof(nextdir))) {
  1665.                         TIFFError(module, "error fetching directory link");
  1666.                         return(0);
  1667.                 }
  1668.                 if (tif->tif_flags & TIFF_SWAB)
  1669.                         TIFFSwabLong((u_long *)&nextdir);
  1670.         }
  1671.         tif->tif_nextdiroff = nextdir;
  1672.         return(TIFFReadDirectory(tif));
  1673. }
  1674.