home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD1.mdf / rexx / library2 / gbmrexx / gbm / gbmtif.c < prev    next >
C/C++ Source or Header  |  1993-10-02  |  36KB  |  1,324 lines

  1. /*
  2.  
  3. GBMTIF.C  Microsoft/Aldus Tagged Image File Format support
  4.  
  5. Reads and writes 1,4,8 and 24 bit colour files.
  6. Supports uncompressed and Packbits compressed files only.
  7. Input option: index=N (default is 0)
  8. Output options: artist=,software=,make=,model=,host=,documentname=,pagename=,
  9.         imagedescription=,pal1bpp
  10.  
  11. Added support to allow SamplePerPixel>=3 for RGB data (TIFF 6.0 new feature).
  12. Added rejection test of FillOrder!=1.
  13. Added rejection test of PlanarConfiguration!=1.
  14. Added support for CMYK images.
  15. Changed write of 1bpp data to Baseline black and white write.
  16. Added pal1bpp output option meaning don't force Baseline write of 1bpp data.
  17. Improved error messages substantially.
  18. Fixed Packbits compression.
  19. Added support for PlanarConfiguration==2 for RGB images only.
  20. Added Predictor==2 support for bps==8, spp=1 case.
  21. Added Predictor==2 support for bps==8, spp>=3 case.
  22.  
  23. */
  24.  
  25. /*...sincludes:0:*/
  26. #include <stdio.h>
  27. #include <ctype.h>
  28. #include <stddef.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <memory.h>
  32. #include <malloc.h>
  33. #ifdef AIX
  34. #include <unistd.h>
  35. #else
  36. #include <io.h>
  37. #endif
  38. #include <fcntl.h>
  39. #include <sys/types.h>
  40. #include <sys/stat.h>
  41. #include "standard.h"
  42. #include "gbm.h"
  43. #include "gbmtifh.h"
  44.  
  45. /*...vgbm\46\h:0:*/
  46. /*...vgbmtifh\46\h:0:*/
  47.  
  48. #ifndef min
  49. #define    min(a,b)    (((a)<(b))?(a):(b))
  50. #endif
  51. /*...e*/
  52.  
  53. /*...ssame:0:*/
  54. static BOOLEAN same(char *s1, char *s2, int n)
  55.     {
  56.     for ( ; n--; s1++, s2++ )
  57.         if ( tolower(*s1) != tolower(*s2) )
  58.             return ( FALSE );
  59.     return ( TRUE );
  60.     }
  61. /*...e*/
  62. /*...sfind_word:0:*/
  63. static char *find_word(char *str, char *substr)
  64.     {
  65.     char    buf [100+1], *s;
  66.     int    len = strlen(substr);
  67.  
  68.     for ( s  = strtok(strcpy(buf, str), " \t,");
  69.           s != NULL;
  70.           s  = strtok(NULL, " \t,") )
  71.         if ( same(s, substr, len) && s [len] == '\0' )
  72.             return ( str + (s - buf) );
  73.     return ( NULL );
  74.     }
  75. /*...e*/
  76. /*...sfind_word_prefix:0:*/
  77. static char *find_word_prefix(char *str, char *substr)
  78.     {
  79.     char    buf [100+1], *s;
  80.     int    len = strlen(substr);
  81.  
  82.     for ( s  = strtok(strcpy(buf, str), " \t,");
  83.           s != NULL;
  84.           s  = strtok(NULL, " \t,") )
  85.         if ( same(s, substr, len) )
  86.             return ( str + (s - buf) );
  87.     return ( NULL );
  88.     }
  89. /*...e*/
  90. /*...sreading ahead:0:*/
  91. #define    AHEAD_BUF    0x4000
  92.  
  93. typedef struct
  94.     {
  95.     byte    buf [AHEAD_BUF];
  96.     int    inx, cnt;
  97.     int    fd;
  98.     } AHEAD;
  99.  
  100. static AHEAD *create_ahead(int fd)
  101.     {
  102.     AHEAD *ahead;
  103.  
  104.     if ( (ahead = malloc(sizeof(AHEAD))) == NULL )
  105.         return ( NULL );
  106.  
  107.     ahead -> inx = 0;
  108.     ahead -> cnt = 0;
  109.     ahead -> fd  = fd;
  110.  
  111.     return ( ahead );
  112.     }
  113.  
  114. static void destroy_ahead(AHEAD *ahead)
  115.     {
  116.     free(ahead);
  117.     }    
  118.  
  119. static byte next(AHEAD *ahead)
  120.     {
  121.     if ( ahead -> inx >= ahead -> cnt )
  122.         {
  123.         ahead -> cnt = read(ahead -> fd, (char *) ahead -> buf, AHEAD_BUF);
  124.         ahead -> inx = 0;
  125.         }
  126.     return ( ahead -> buf [ahead -> inx++] );
  127.     }
  128. /*...e*/
  129.  
  130. static GBMFT tif_gbmft =
  131.     {
  132.     "TIFF",
  133.     "Tagged Image File Format support (almost TIFF 6.0 Baseline)",
  134.     "TIF",
  135.     GBM_FT_R1|GBM_FT_R4|GBM_FT_R8|GBM_FT_R24|
  136.     GBM_FT_W1|GBM_FT_W4|GBM_FT_W8|GBM_FT_W24,
  137.     };
  138.  
  139. /*...serror codes:0:*/
  140. #define    GBM_ERR_TIF_VERSION        ((GBM_ERR) 800)
  141. #define    GBM_ERR_TIF_N_TAGS        ((GBM_ERR) 801)
  142. #define    GBM_ERR_TIF_TAG_TYPE        ((GBM_ERR) 802)
  143. #define    GBM_ERR_TIF_HEADER        ((GBM_ERR) 803)
  144. #define    GBM_ERR_TIF_MISSING_TAG        ((GBM_ERR) 804)
  145. #define    GBM_ERR_TIF_SPP_BIT        ((GBM_ERR) 805)
  146. #define    GBM_ERR_TIF_BPS_BIT        ((GBM_ERR) 806)
  147. #define    GBM_ERR_TIF_SPP_RGB        ((GBM_ERR) 807)
  148. #define    GBM_ERR_TIF_BPS_RGB        ((GBM_ERR) 808)
  149. #define    GBM_ERR_TIF_SPP_PAL        ((GBM_ERR) 809)
  150. #define    GBM_ERR_TIF_BPS_PAL        ((GBM_ERR) 810)
  151. #define    GBM_ERR_TIF_SPP_CMYK        ((GBM_ERR) 811)
  152. #define    GBM_ERR_TIF_BPS_CMYK        ((GBM_ERR) 812)
  153. #define    GBM_ERR_TIF_COMP_1D_MH        ((GBM_ERR) 813)
  154. #define    GBM_ERR_TIF_COMP_T4        ((GBM_ERR) 814)
  155. #define    GBM_ERR_TIF_COMP_T6        ((GBM_ERR) 815)
  156. #define    GBM_ERR_TIF_COMP        ((GBM_ERR) 816)
  157. #define    GBM_ERR_TIF_COLORMAP        ((GBM_ERR) 817)
  158. #define    GBM_ERR_TIF_CORRUPT        ((GBM_ERR) 818)
  159. #define    GBM_ERR_TIF_PREDICTOR        ((GBM_ERR) 819)
  160. #define    GBM_ERR_TIF_N_STRIPS        ((GBM_ERR) 820)
  161. #define    GBM_ERR_TIF_PHOTO_TRANS        ((GBM_ERR) 821)
  162. #define    GBM_ERR_TIF_PHOTO_Y_Cb_Cr    ((GBM_ERR) 822)
  163. #define    GBM_ERR_TIF_PHOTO        ((GBM_ERR) 823)
  164. #define    GBM_ERR_TIF_FILLORDER        ((GBM_ERR) 824)
  165. #define    GBM_ERR_TIF_PLANARCONFIG_1    ((GBM_ERR) 825)
  166. #define    GBM_ERR_TIF_PLANARCONFIG_12    ((GBM_ERR) 826)
  167. #define    GBM_ERR_TIF_INKSET        ((GBM_ERR) 827)
  168. #define    GBM_ERR_TIF_ORIENT        ((GBM_ERR) 828)
  169. #define    GBM_ERR_TIF_INDEX        ((GBM_ERR) 829)
  170. /*...e*/
  171.  
  172. /*
  173. #define MAX_STRIPS    200
  174. */
  175. #define    MAX_STRIPS    ((PRIV_SIZE-8*sizeof(int)-0x100*sizeof(GBMRGB))/sizeof(long))
  176.  
  177. typedef struct
  178.     {
  179.     GBMRGB gbmrgb [0x100];
  180.     int rps, spp, bps, comp, photo, orient, planar, predictor;
  181.     long so [MAX_STRIPS];
  182.     } TIF_PRIV;
  183.  
  184. #define    ENC_NONE    ((int) 1)
  185. #define    ENC_G3_1D_MH    ((int) 2)
  186. #define    ENC_T4        ((int) 3)
  187. #define    ENC_T6        ((int) 4)
  188. #define    ENC_LZW        ((int) 5)
  189. #define    ENC_PACKBITS    ((int) 32773)
  190.  
  191. #define    PHOTO_BIT0    0
  192. #define    PHOTO_BIT1    1
  193. #define    PHOTO_RGB    2
  194. #define    PHOTO_PAL    3
  195. #define    PHOTO_TRANS    4
  196. #define    PHOTO_CMYK    5
  197. #define    PHOTO_Y_Cb_Cr    6
  198.  
  199. /*...srgb_bgr:0:*/
  200. static void rgb_bgr(byte *p, byte *q, int n)
  201.     {
  202.     while ( n-- )
  203.         {
  204.         byte    r = *p++;
  205.         byte    g = *p++;
  206.         byte    b = *p++;
  207.  
  208.         *q++ = b;
  209.         *q++ = g;
  210.         *q++ = r;
  211.         }
  212.     }
  213. /*...e*/
  214.  
  215. /*...stif_qft:0:*/
  216. GBM_ERR tif_qft(GBMFT *gbmft)
  217.     {
  218.     *gbmft = tif_gbmft;
  219.     return ( GBM_ERR_OK );
  220.     }
  221. /*...e*/
  222. /*...stif_rhdr:0:*/
  223. /*...svalue_of_tag_def:0:*/
  224. static long value_of_tag_def(IFD *ifd, short type, long def)
  225.     {
  226.     TAG    *tag;
  227.  
  228.     if ( (tag = locate_tag(ifd, type)) != NULL )
  229.         return ( value_of_tag(tag) );
  230.     else
  231.         return ( def );
  232.     }
  233. /*...e*/
  234.  
  235. GBM_ERR tif_rhdr(char *fn, int fd, GBM *gbm, char *opt)
  236.     {
  237.     TIF_PRIV *tif_priv = (TIF_PRIV *) gbm -> priv;
  238.     TAG *tag_w, *tag_h, *tag_so;
  239.     GBM_ERR rc;
  240.     IFH    *ifh;
  241.     IFD    *ifd;
  242.     int    inx = 0, strip, n_strips, fillorder;
  243.     char    *index;
  244.  
  245.     if ( (index = find_word_prefix(opt, "index=")) != NULL )
  246.         sscanf(index + 6, "%d", &inx);
  247.  
  248.     fn=fn; /* Suppress 'unref arg' compiler warnings */
  249.  
  250.     lseek(fd, 0L, SEEK_SET);
  251.     switch ( read_ifh_and_ifd(fd, inx, &ifh) )
  252.         {
  253.         case TE_OK:        rc = GBM_ERR_OK;        break;
  254.         case TE_MEM:        rc = GBM_ERR_MEM;        break;
  255.         case TE_VERSION:    rc = GBM_ERR_TIF_VERSION;    break;
  256.         case TE_N_TAGS:        rc = GBM_ERR_TIF_N_TAGS;    break;
  257.         case TE_TAG_TYPE:    rc = GBM_ERR_TIF_TAG_TYPE;    break;
  258.         case TE_N_IFD:        rc = GBM_ERR_TIF_INDEX;        break;
  259.         default:        rc = GBM_ERR_TIF_HEADER;    break;
  260.         }
  261.  
  262.     if ( rc != GBM_ERR_OK )
  263.         return ( rc );
  264.  
  265.     ifd = ifh -> ifd;
  266.  
  267.     if ( (tag_w  = locate_tag(ifd, T_IMAGEWIDTH  )) == NULL ||
  268.          (tag_h  = locate_tag(ifd, T_IMAGELENGTH )) == NULL ||
  269.          (tag_so = locate_tag(ifd, T_STRIPOFFSETS)) == NULL )
  270.         {
  271.         free_ifh(ifh);
  272.         return ( GBM_ERR_TIF_MISSING_TAG );
  273.         }
  274.  
  275.     gbm -> w           = (int) value_of_tag(tag_w);
  276.     gbm -> h           = (int) value_of_tag(tag_h);
  277.     tif_priv -> photo  = (int) value_of_tag_def(ifd, T_PHOTOMETRIC    , 1L);
  278.     tif_priv -> rps    = (int) value_of_tag_def(ifd, T_ROWSPERSTRIP   , (long) gbm -> h);
  279.     tif_priv -> spp    = (int) value_of_tag_def(ifd, T_SAMPLESPERPIXEL, 1L);
  280.     tif_priv -> bps    = (int) value_of_tag_def(ifd, T_BITSPERSAMPLE  , 1L);
  281.     tif_priv -> comp   = (int) value_of_tag_def(ifd, T_COMPRESSION    , 1L);
  282.     tif_priv -> orient = (int) value_of_tag_def(ifd, T_ORIENTATION    , 1L);
  283.     tif_priv -> planar = (int) value_of_tag_def(ifd, T_PLANARCONFIG   , 1L);
  284.  
  285.     rc = GBM_ERR_OK;
  286.     switch ( tif_priv -> photo )
  287.         {
  288. /*...sPHOTO_BITx    \45\ bitmap or greyscale:16:*/
  289. case PHOTO_BIT0:
  290. case PHOTO_BIT1:
  291.     if ( tif_priv -> spp != 1 )
  292.         rc = GBM_ERR_TIF_SPP_BIT;
  293.     else if ( tif_priv -> bps != 1 && tif_priv -> bps != 4 && tif_priv -> bps != 8 )
  294.         rc = GBM_ERR_TIF_BPS_BIT;
  295.     else
  296.         {
  297.         int    i, n_pal;
  298.  
  299.         n_pal = ( 1 << tif_priv -> bps );
  300.         for ( i = 0; i < n_pal; i++ )
  301.             {
  302.             tif_priv -> gbmrgb [i].r =
  303.             tif_priv -> gbmrgb [i].g =
  304.             tif_priv -> gbmrgb [i].b = (byte) ((0xff * i) / (n_pal - 1));
  305.             }
  306.         if ( tif_priv -> photo == PHOTO_BIT0 )
  307.             for ( i = 0; i < n_pal; i++ )
  308.                 {
  309.                 tif_priv -> gbmrgb [i].r ^= 0xff;
  310.                 tif_priv -> gbmrgb [i].g ^= 0xff;
  311.                 tif_priv -> gbmrgb [i].b ^= 0xff;
  312.                 }
  313.         }
  314.     gbm -> bpp = tif_priv -> bps;
  315.     break;
  316. /*...e*/
  317. /*...sPHOTO_RGB     \45\ 24 bit data:16:*/
  318. /* It is possible for sample per pixel to be greater than 3.
  319.    This implies there are extra samples (which we will ignore).
  320.    This is a new TIFF 6.0 feature. */
  321.  
  322. case PHOTO_RGB:
  323.     if ( tif_priv -> spp < 3 )
  324.         rc = GBM_ERR_TIF_SPP_RGB;
  325.     else if ( tif_priv -> bps != 8 )
  326.         rc = GBM_ERR_TIF_BPS_RGB;
  327.     gbm -> bpp = 24;
  328.     break;
  329. /*...e*/
  330. /*...sPHOTO_PAL     \45\ palettised:16:*/
  331. /*
  332. There are 2 known bugs in commonly available TIFF files today.
  333. UBU will only write a ColorMap tag with a length field of 256 (not 256 * 3).
  334. This bug is fixed inside my TIFF library itself!
  335. OS/2 Image Support will write all palette entrys as bytes!
  336. */
  337.  
  338. case PHOTO_PAL:
  339.     if ( tif_priv -> spp != 1 )
  340.         rc = GBM_ERR_TIF_SPP_PAL;
  341.     else if ( tif_priv -> bps != 1 && tif_priv -> bps != 4 && tif_priv -> bps != 8 )
  342.         rc = GBM_ERR_TIF_BPS_PAL;
  343.     else
  344.         {
  345.         int    i, n_pal;
  346.         TAG    *tag_cm;
  347.  
  348.         n_pal = (1 << tif_priv -> bps);
  349.         if ( (tag_cm = locate_tag(ifd, T_COLORMAP)) != NULL )
  350.             {
  351.             GBMRGB    *gbmrgb;
  352.  
  353.             for ( i = 0, gbmrgb = tif_priv -> gbmrgb; i < n_pal; i++, gbmrgb++ )
  354.                 {
  355.                 gbmrgb -> r = (byte) (value_of_tag_n(tag_cm,             i) >> 8);
  356.                 gbmrgb -> g = (byte) (value_of_tag_n(tag_cm,     n_pal + i) >> 8);
  357.                 gbmrgb -> b = (byte) (value_of_tag_n(tag_cm, 2 * n_pal + i) >> 8);
  358.                 }
  359. /*...sfix for OS\47\2 Image Support \40\and others\41\:40:*/
  360. {
  361. byte    bugfix = 0;
  362.  
  363. for ( i = 0, gbmrgb = tif_priv -> gbmrgb; i < n_pal; i++, gbmrgb++ )
  364.     bugfix |= (gbmrgb -> r | gbmrgb -> g | gbmrgb -> b);
  365.  
  366. if ( bugfix == 0 )
  367.     for ( i = 0, gbmrgb = tif_priv -> gbmrgb; i < n_pal; i++, gbmrgb++ )
  368.         {
  369.         gbmrgb -> r = (byte) value_of_tag_n(tag_cm,             i);
  370.         gbmrgb -> g = (byte) value_of_tag_n(tag_cm,     n_pal + i);
  371.         gbmrgb -> b = (byte) value_of_tag_n(tag_cm, 2 * n_pal + i);
  372.         }
  373. }
  374. /*...e*/
  375.             }
  376.         else
  377.             rc = GBM_ERR_TIF_COLORMAP;
  378.         }
  379.     gbm -> bpp = tif_priv -> bps;
  380.     break;
  381. /*...e*/
  382. /*...sPHOTO_TRANS   \45\ transparency mask:16:*/
  383. case PHOTO_TRANS:
  384.     rc = GBM_ERR_TIF_PHOTO_TRANS;
  385.     break;
  386. /*...e*/
  387. /*...sPHOTO_CMYK    \45\ CMYK or other seperated image:16:*/
  388. /* This is a colour seperated image.
  389.    Typically expect 4 seperations, for CMYK.
  390.    Can be other numbers, and possibly 4 with non standard ink colours.
  391.    Ignore all but 4 seperations which are CMYK.
  392.    Consider this a 24 bit RGB, mapping will occur from CMYK to RGB. */
  393.  
  394. case PHOTO_CMYK:
  395.     if ( tif_priv -> spp != 4 )
  396.         rc = GBM_ERR_TIF_SPP_CMYK;
  397.     else if ( tif_priv -> bps != 8 )
  398.         rc = GBM_ERR_TIF_BPS_CMYK;
  399.     else if ( value_of_tag_def(ifd, T_INKSET, 1L) != 1 )
  400.         rc = GBM_ERR_TIF_INKSET;
  401.     else
  402.         gbm -> bpp = 24;
  403.     break;
  404. /*...e*/
  405. /*...sPHOTO_Y_Cb_Cr \45\ Y\45\Cb\45\Cr colour space:16:*/
  406. case PHOTO_Y_Cb_Cr:
  407.     rc = GBM_ERR_TIF_PHOTO_Y_Cb_Cr;
  408.     break;
  409. /*...e*/
  410. /*...sdefault       \45\ wierd PhotometricInterpretation:16:*/
  411. default:
  412.     rc = GBM_ERR_TIF_PHOTO;
  413.     break;
  414. /*...e*/
  415.         }
  416.  
  417.     if ( rc != GBM_ERR_OK )
  418.         { free_ifh(ifh); return ( rc ); }
  419.  
  420.     /* Remember where strips are, and how big they are */
  421.  
  422.     n_strips = (gbm -> h + (tif_priv -> rps - 1)) / tif_priv -> rps;
  423.     if ( tif_priv -> photo == PHOTO_RGB && tif_priv -> planar == 2 )
  424.         n_strips *= 3;
  425.  
  426.     if ( n_strips > MAX_STRIPS )
  427.         { free_ifh(ifh); return ( GBM_ERR_TIF_N_STRIPS ); }
  428.  
  429.     for ( strip = 0; strip < n_strips; strip++ )
  430.         tif_priv -> so [strip] = value_of_tag_n(tag_so, strip);
  431.  
  432.     if ( tif_priv -> comp != ENC_NONE     &&
  433.          tif_priv -> comp != ENC_PACKBITS &&
  434.          tif_priv -> comp != ENC_LZW      )
  435. /*...sreject compression type:16:*/
  436. {
  437. free_ifh(ifh);
  438. switch ( tif_priv -> comp )
  439.     {
  440.     case ENC_G3_1D_MH:    return ( GBM_ERR_TIF_COMP_1D_MH );
  441.     case ENC_T4:        return ( GBM_ERR_TIF_COMP_T4    );
  442.     case ENC_T6:        return ( GBM_ERR_TIF_COMP_T6    );
  443.     default:        return ( GBM_ERR_TIF_COMP       );
  444.     }
  445. }
  446. /*...e*/
  447.  
  448.     if ( tif_priv -> orient != 1 && tif_priv -> orient != 4 )
  449.         { free_ifh(ifh); return ( GBM_ERR_TIF_ORIENT ); }
  450.  
  451.     fillorder = (int) value_of_tag_def(ifd, T_FILLORDER, 1L);
  452.     if ( fillorder != 1 )
  453.         { free_ifh(ifh); return ( GBM_ERR_TIF_FILLORDER ); }
  454.  
  455.     if ( tif_priv -> photo == PHOTO_RGB )
  456.         /* Allow photo of 1 or 2 */
  457.         {
  458.         if ( tif_priv -> planar != 1 && tif_priv -> planar != 2 )
  459.             { free_ifh(ifh); return ( GBM_ERR_TIF_PLANARCONFIG_12 ); }
  460.         }
  461.     else
  462.         /* Allow photo of 1 only */
  463.         {
  464.         if ( tif_priv -> planar != 1 )
  465.             { free_ifh(ifh); return ( GBM_ERR_TIF_PLANARCONFIG_1 ); }
  466.         }
  467.  
  468.     tif_priv -> predictor = (int) value_of_tag_def(ifd, T_PREDICTOR, 1L);
  469.  
  470.     /* Only allow predictor of 1, unless a special case we handle */
  471.     if ( tif_priv -> predictor != 1 &&
  472.          !(tif_priv -> comp == ENC_LZW &&
  473.            tif_priv -> bps == 8 &&
  474.            (tif_priv -> spp == 1 || tif_priv -> spp >= 3)) )
  475.         { free_ifh(ifh); return ( GBM_ERR_TIF_PREDICTOR ); }
  476.  
  477.     free_ifh(ifh);
  478.  
  479.     return ( GBM_ERR_OK );
  480.     }
  481. /*...e*/
  482. /*...stif_rpal:0:*/
  483. GBM_ERR tif_rpal(int fd, GBM *gbm, GBMRGB *gbmrgb)
  484.     {
  485.     TIF_PRIV *tif_priv = (TIF_PRIV *) gbm -> priv;
  486.  
  487.     fd=fd; /* Suppress 'unref arg' compiler warning */
  488.  
  489.     if ( gbm -> bpp != 24 )
  490.         memcpy(gbmrgb, tif_priv -> gbmrgb, (1 << gbm -> bpp) * sizeof(GBMRGB));
  491.  
  492.     return ( GBM_ERR_OK );
  493.     }
  494. /*...e*/
  495. /*...stif_rdata:0:*/
  496. /*
  497. TIFF data is usually stored top-left-origin based.
  498. ie: We ignore the private "Orientation" tag.
  499. Our data format in memory has bigger padding than TIFF.
  500. It has 'istride' bytes per line, GBM uses/requires 'stride' bytes per line.
  501. Therefore we read it to the part of the strip area and then expand downwards.
  502. */
  503.  
  504. /*...sget_strip_packbits \45\ get bytes with packbits decompression:0:*/
  505. static GBM_ERR get_strip_packbits(int fd, byte *dest, long n_bytes)
  506.     {
  507.     AHEAD    *ahead;
  508.  
  509.     if ( (ahead = create_ahead(fd)) == NULL )
  510.         return ( GBM_ERR_MEM );
  511.  
  512.     while ( n_bytes > 0 )
  513.         {
  514.         byte b = next(ahead);
  515.  
  516.         if ( b < 0x80 )
  517.             {
  518.             unsigned int count = b + 1;
  519.  
  520.             do
  521.                 *dest++ = next(ahead);
  522.             while ( --count > 0 );
  523.             n_bytes -= (b + 1);
  524.             }
  525.         else if ( b > 0x80 )
  526.             {
  527.             unsigned int count = 0x101 - (unsigned int) b;
  528.             byte c = next(ahead);
  529.  
  530.             memset(dest, c, count);
  531.             dest += count;
  532.             n_bytes -= count;
  533.             }
  534.         }
  535.  
  536.     destroy_ahead(ahead);
  537.     return ( GBM_ERR_OK );
  538.     }
  539. /*...e*/
  540. /*...sget_strip_lzw      \45\ get bytes with TIFF style LZW decompression:0:*/
  541. /*
  542. This code run on output of FotoTouch and some sample TIFFs from an afs
  543. directory on the IBM IP-network.
  544. */
  545.  
  546. /*...sread context:0:*/
  547. typedef struct
  548.     {
  549.     int fd;                /* File descriptor to read */
  550.     int inx, size;            /* Index and size in bits */
  551.     byte buf [255+3];        /* Buffer holding bits */
  552.     int code_size;            /* Number of bits to return at once */
  553.     word read_mask;            /* 2^code_size-1 */
  554.     } READ_CONTEXT;
  555.  
  556. static word read_code(READ_CONTEXT *c)
  557.     {
  558.     int raw_code, byte_inx;
  559.  
  560.     if ( c -> inx + c -> code_size > c -> size )
  561. /*...snot enough bits in buffer\44\ refill it:16:*/
  562. /* Not very efficient, but infrequently called */
  563.  
  564. {
  565. int bytes_to_lose = (c -> inx >> 3);
  566. int bytes;
  567.  
  568. /* Note biggest code size is 12 bits */
  569. /* And this can at worst span 3 bytes */
  570. memcpy(c -> buf, c -> buf + bytes_to_lose, 3);
  571. (c -> inx) &= 7;
  572. (c -> size) -= (bytes_to_lose << 3);
  573. bytes = 255 - ( c -> size >> 3 );
  574. if ( (bytes = read(c -> fd, c -> buf + (c -> size >> 3), bytes)) <= 0 )
  575.     return ( 0xffff );
  576. (c -> size) += (bytes << 3);
  577. }
  578. /*...e*/
  579.  
  580.     byte_inx = (c -> inx >> 3);
  581.     raw_code = ((c -> buf [byte_inx    ]) << 16) +
  582.            ((c -> buf [byte_inx + 1]) <<  8);
  583.     if ( c -> code_size > 8 )
  584.         raw_code += c -> buf [byte_inx + 2];
  585.     raw_code <<= ((c -> inx) & 7);
  586.     (c -> inx) += (byte) (c -> code_size);
  587.     raw_code >>= ( 24 - c -> code_size );
  588.     return ( (word) raw_code & c -> read_mask );
  589.     }
  590. /*...e*/
  591.  
  592. #define    INIT_CODE_SIZE    9
  593.  
  594. static GBM_ERR get_strip_lzw(int fd, byte *dest, long n_bytes)
  595.     {
  596.     word max_code;            /* 1 << code_size */
  597.     word clear_code;        /* Code to clear table */
  598.     word eoi_code;            /* End of information code */
  599.     word first_free_code;        /* First free code */
  600.     word free_code;            /* Next available free code slot */
  601.     int i, out_count = 0;
  602.     word code, cur_code, old_code, in_code, fin_char;
  603.     word *prefix, *suffix, *outcode;
  604.     READ_CONTEXT c;
  605.     BOOLEAN table_full = FALSE;
  606.  
  607.     n_bytes=n_bytes; /* Suppress 'unref arg' compiler warning */
  608.  
  609.     if ( (prefix = (word *) malloc(4096 * sizeof(word))) == NULL )
  610.         return ( GBM_ERR_MEM );
  611.     if ( (suffix = (word *) malloc(4096 * sizeof(word))) == NULL )
  612.         {
  613.         free(prefix);
  614.         return ( GBM_ERR_MEM );
  615.         }
  616.     if ( (outcode = (word *) malloc(4097 * sizeof(word))) == NULL )
  617.         {
  618.         free(suffix);        
  619.         free(prefix);
  620.         return ( GBM_ERR_MEM );
  621.         }
  622.  
  623.     /* Initial read context */
  624.  
  625.     c.inx            = 0;
  626.     c.size           = 0;
  627.     c.fd             = fd;
  628.     c.code_size      = INIT_CODE_SIZE;
  629.     c.read_mask      = (word) ( (1 << INIT_CODE_SIZE) - 1 );
  630.  
  631.     /* 2^min_code size accounts for all colours in file */
  632.  
  633.     clear_code = (word) ( 1 << (INIT_CODE_SIZE - 1) );
  634.     eoi_code = (word) (clear_code + 1);
  635.     free_code = first_free_code = (word) (clear_code + 2);
  636.  
  637.     max_code = (word) ( 1 << INIT_CODE_SIZE );
  638.  
  639.     while ( (code = read_code(&c)) != eoi_code && code != 0xffff )
  640.         {
  641.         if ( code == clear_code )
  642.             {
  643.             c.code_size = INIT_CODE_SIZE;
  644.             c.read_mask = (word) ( (1 << INIT_CODE_SIZE) - 1);
  645.             max_code = (word) ( 1 << INIT_CODE_SIZE );
  646.             free_code = first_free_code;
  647.             cur_code = old_code = code = read_code(&c);
  648.             if ( code == eoi_code || code == 0xffff )
  649.                 break;
  650.             fin_char = cur_code;
  651.             *dest++ = (byte) fin_char;
  652.             table_full = FALSE;
  653.             }
  654.         else
  655.             {
  656.             cur_code = in_code = code;
  657.             if ( cur_code >= free_code )
  658.                 {
  659.                 cur_code = old_code;
  660.                 outcode [out_count++] = fin_char;
  661.                 }
  662.             while ( cur_code > 0xff )
  663.                 {
  664.                 if ( out_count > 4096 )
  665.                     {
  666.                     free(outcode);
  667.                     free(suffix);
  668.                     free(prefix);
  669.                     return ( GBM_ERR_TIF_CORRUPT );
  670.                     }
  671.                 outcode [out_count++] = suffix [cur_code];
  672.                 cur_code = prefix [cur_code];
  673.                 }
  674.             fin_char = cur_code;
  675.             outcode [out_count++] = fin_char;
  676.             for ( i = out_count - 1; i >= 0; i-- )
  677.                 *dest++ = outcode [i];
  678.             out_count = 0;
  679.  
  680.             /* Update dictionary */
  681.  
  682.             if ( !table_full )
  683.                 {
  684.                 prefix [free_code] = old_code;
  685.                 suffix [free_code] = fin_char;
  686.  
  687.                 /* Advance to next free slot */
  688.  
  689.                 if ( ++free_code >= max_code - 1 )
  690.                     {
  691.                     if ( c.code_size < 12 )
  692.                         {
  693.                         c.code_size++;
  694.                         max_code <<= 1;
  695.                         c.read_mask = (word) (( 1 << c.code_size ) - 1);
  696.                         }
  697.                     else
  698.                         table_full = TRUE;
  699.                     }
  700.                 }
  701.             old_code = in_code;
  702.             }
  703.         }
  704.  
  705.     free(outcode);
  706.     free(suffix);
  707.     free(prefix);
  708.  
  709.     if ( code == 0xffff )
  710.         return ( GBM_ERR_READ );
  711.  
  712.     return ( GBM_ERR_OK );
  713.     }
  714. /*...e*/
  715. /*...sget_strip_lzw_pred \45\ get_strip_lzw with non 1 predictor fixup:0:*/
  716. static GBM_ERR get_strip_lzw_pred(
  717.     int fd,
  718.     byte *dest,
  719.     long n_bytes,
  720.     TIF_PRIV *tif_priv,
  721.     int w, int h
  722.     )
  723.     {
  724.     GBM_ERR rc;
  725.  
  726.     if ( (rc = get_strip_lzw(fd, dest, n_bytes)) != GBM_ERR_OK )
  727.         return ( rc );
  728.  
  729.     if ( tif_priv -> predictor == 2 )
  730.         /* Note: This is only allowed if bps==8 */
  731.             {
  732.             int x, y, spp = tif_priv -> spp;
  733.             for ( y = 0; y < h; y++, dest += w * spp )
  734.                 for ( x = spp; x < w * spp; x++ )
  735.                     dest [x] += dest [x - spp];
  736.             }
  737.  
  738.     return ( GBM_ERR_OK );
  739.     }
  740. /*...e*/
  741. /*...sget_strip_comp     \45\ get strip\44\ dealing with any compression:0:*/
  742. /* n_bytes is passed in as istride * n_lines */
  743.  
  744. static GBM_ERR get_strip_comp(
  745.     int fd,
  746.     byte *dest,
  747.     long so, long n_bytes,
  748.     TIF_PRIV *tif_priv,
  749.     int w, int h
  750.     )
  751.     {
  752.     lseek(fd, so, SEEK_SET);
  753.     switch ( tif_priv -> comp )
  754.         {
  755. /*...sENC_NONE     \45\ no compression:16:*/
  756. case ENC_NONE:
  757.     return ( ( (int) n_bytes == read(fd, dest, (int) n_bytes) ) ?
  758.             GBM_ERR_OK : GBM_ERR_READ );
  759. /*...e*/
  760. /*...sENC_PACKBITS \45\ packbits:16:*/
  761. case ENC_PACKBITS:
  762.     return ( get_strip_packbits(fd, dest, n_bytes) );
  763. /*...e*/
  764. /*...sENC_LZW      \45\ lzw:16:*/
  765. case ENC_LZW:
  766.     return ( get_strip_lzw_pred(fd, dest, n_bytes, tif_priv, w, h) );
  767. /*...e*/
  768.         }
  769.     return ( GBM_ERR_NOT_SUPP );
  770.     }
  771. /*...e*/
  772. /*...sget_strip          \45\ get strip\44\ discarding extra samples\44\ and CMYK mapping:0:*/
  773. /*
  774. If there are too many samples per pixel, this code can ignore the extra ones.
  775. Also, if CMYK data is being read, it will read the CMYK, and convert.
  776. This requires a temporary buffer, to read the original data in.
  777. The original data is then 'converted'.
  778. */
  779.  
  780. static GBM_ERR get_strip(
  781.     int fd,
  782.     byte *dest,
  783.     long so, long n_bytes,
  784.     TIF_PRIV *tif_priv,
  785.     int w, int h
  786.     )
  787.     {
  788.     byte *buf = dest;
  789.     GBM_ERR rc;
  790.  
  791.     if ( tif_priv -> photo == PHOTO_CMYK )
  792. /*...sallocate space for CMYK image:16:*/
  793. {
  794. n_bytes = (long) w * 4L * (long) h;
  795. if ( (buf = malloc(n_bytes)) == NULL )
  796.     return ( GBM_ERR_MEM );
  797. }
  798. /*...e*/
  799.     else if ( tif_priv -> photo == PHOTO_RGB && tif_priv -> spp > 3 )
  800. /*...sallocate space for image \43\ extra samples:16:*/
  801. {
  802. n_bytes = (long) w * tif_priv -> spp * (long) h;
  803. if ( (buf = malloc(n_bytes)) == NULL )
  804.     return ( GBM_ERR_MEM );
  805. }
  806. /*...e*/
  807.  
  808.     if ( (rc = get_strip_comp(fd, buf, so, n_bytes, tif_priv, w, h)) != GBM_ERR_OK )
  809.         {
  810.         if ( buf != dest )
  811.             free(buf);
  812.         return ( rc );
  813.         }
  814.  
  815.     if ( tif_priv -> photo == PHOTO_CMYK )
  816. /*...sconvert from CMYK to RGB:16:*/
  817. {
  818. int x, yy;
  819. byte *buf_p = buf, *dest_p = dest;
  820. for ( yy = 0; yy < h; yy++ )
  821.     for ( x = 0; x < w; x++ )
  822.         {
  823.         word c = *buf_p++;
  824.         word m = *buf_p++;
  825.         word y = *buf_p++;
  826.         word k = *buf_p++;
  827.  
  828.         /* Exploit 8 bit modulo arithmetic by biasing by + 0x100 */
  829.  
  830.         word r = 0x1ff - (c + k);
  831.         word g = 0x1ff - (m + k);
  832.         word b = 0x1ff - (y + k);
  833.  
  834.         if ( r < 0x100 ) r = 0x100;
  835.         if ( g < 0x100 ) g = 0x100;
  836.         if ( b < 0x100 ) b = 0x100;
  837.  
  838.         *dest_p++ = (byte) r;
  839.         *dest_p++ = (byte) g;
  840.         *dest_p++ = (byte) b;
  841.         }
  842.  
  843. free(buf);
  844. }
  845. /*...e*/
  846.     else if ( tif_priv -> photo == PHOTO_RGB && tif_priv -> spp > 3 )
  847. /*...sextract\44\ ignoring extra\45\samples:16:*/
  848. {
  849. int x, y, skip = tif_priv -> spp - 2;
  850. byte *buf_p = buf, *dest_p = dest;
  851. for ( y = 0; y < h; y++ )
  852.     for ( x = 0; x < w; x++ )
  853.         {
  854.         *dest_p++ = *buf_p++;
  855.         *dest_p++ = *buf_p++;
  856.         *dest_p++ = *buf_p  ;
  857.         buf_p += skip;
  858.         }
  859.  
  860. free(buf);
  861. }
  862. /*...e*/
  863.  
  864.     return ( GBM_ERR_OK );
  865.     }
  866. /*...e*/
  867. /*...sget_image          \45\ get all strips\44\ result is whole image:0:*/
  868. /*
  869. This routine calls get_strip() to get strips data one after another until it
  870. has read the entire images worth of data. Of course, scan lines are aligned on
  871. byte boundaries, and the data is usually considered to be image top to bottom.
  872. */
  873.  
  874. static GBM_ERR get_image(
  875.     int fd,
  876.     byte *dest,
  877.     TIF_PRIV *tif_priv,
  878.     GBM *gbm,
  879.     int *strip
  880.     )
  881.     {
  882.     GBM_ERR    rc;
  883.     int y, istride = ((gbm -> w * gbm -> bpp + 7) / 8);
  884.  
  885.     for ( y = 0; y < gbm -> h; y += tif_priv -> rps, (*strip)++ )
  886.         {
  887.         int n_lines = min(tif_priv -> rps, gbm -> h - y);
  888.         if ( (rc = get_strip(fd, dest + y * istride,
  889.                      tif_priv -> so [*strip],
  890.                      (long) n_lines * (long) istride,
  891.                      tif_priv,
  892.                      gbm -> w, n_lines)) != GBM_ERR_OK )
  893.             return ( rc );
  894.         }
  895.  
  896.     return ( GBM_ERR_OK );
  897.     }
  898. /*...e*/
  899. /*...sget_image_planar   \45\ get all strips\44\ allowing for PlanarConfiguration:0:*/
  900. /*
  901. get_image() will assume the data is in PlanarConfiguration==1, ie: chunky
  902. pixel mode. This is TRUE most of the time. But sometimes we will actually
  903. allow PlanarConfiguration==2. In this case, use get_image() and then fix-up
  904. the results.
  905.  
  906. */
  907.  
  908. static GBM_ERR get_image_planar(
  909.     int fd,
  910.     byte *dest,
  911.     TIF_PRIV *tif_priv,
  912.     GBM *gbm
  913.     )
  914.     {
  915.     int strip = 0;
  916.  
  917.     if ( tif_priv -> photo == PHOTO_RGB &&
  918.          tif_priv -> planar == 2 )
  919. /*...sread 3 seperate planes\44\ and combine them:16:*/
  920. /*
  921. If PhotometricInterpretation==RGB and
  922.    SamplesPerPixel>=3 and
  923.    BitsPerSample==8 then
  924.     we allow PlanarConfiguration==2
  925.  
  926. I have successfully read in a PlanarConfiguration==2 RGB TIFF file by using
  927. the "read 3 images" logic below. This image had RowsPerStrip==1, and so
  928. technically either fold below would have worked. I think the read 3 images
  929. logic is a better interpretation of the TIFF 6.0 spec., but until I find
  930. some other images I can handle, I will keep the alternative peice of code.
  931. */
  932.  
  933. {
  934. GBM_ERR rc;
  935. GBM gbm_planar;
  936. int saved_spp = tif_priv -> spp;
  937. int n_bytes = gbm -> w * gbm -> h;
  938. int x, y;
  939. byte *buf, *p [3];
  940.  
  941. if ( (buf = malloc(n_bytes * 3)) == NULL )
  942.     return ( GBM_ERR_MEM );
  943. p [0] = buf;
  944. p [1] = p [0] + n_bytes;
  945. p [2] = p [1] + n_bytes;
  946.  
  947. tif_priv -> spp = 1;
  948. /*...sread 3 images:16:*/
  949. {
  950. int i;
  951.  
  952. gbm_planar.w   = gbm -> w;
  953. gbm_planar.h   = gbm -> h;
  954. gbm_planar.bpp = 8;
  955. for ( i = 0; i < 3; i++ )
  956.     if ( (rc = get_image(fd, p [i], tif_priv, &gbm_planar, &strip)) != GBM_ERR_OK )
  957.         {
  958.         tif_priv -> spp = saved_spp;
  959.         free(buf);
  960.         return ( rc );
  961.         }
  962. }
  963. /*...e*/
  964. #ifdef NEVER
  965. /*...sread single image 3x too high:16:*/
  966. gbm_planar.w   = gbm -> w;
  967. gbm_planar.h   = gbm -> h * 3;
  968. gbm_planar.bpp = 8;
  969. if ( (rc = get_image(fd, buf, tif_priv, &gbm_planar, &strip)) != GBM_ERR_OK )
  970.     {
  971.     tif_priv -> spp = saved_spp;
  972.     free(buf);
  973.     return ( rc );
  974.     }
  975. /*...e*/
  976. #endif
  977. tif_priv -> spp = saved_spp;
  978.  
  979. for ( y = 0; y < gbm -> h; y++ )
  980.     for ( x = 0; x < gbm -> w; x++ )
  981.         {
  982.         *dest++ = *(p [0])++;
  983.         *dest++ = *(p [1])++;
  984.         *dest++ = *(p [2])++;
  985.         }
  986. free(buf);
  987. return ( GBM_ERR_OK );
  988. }
  989. /*...e*/
  990.     else
  991.         return ( get_image(fd, dest, tif_priv, gbm, &strip) );
  992.     }
  993. /*...e*/
  994. /*...sget_image_orient   \45\ get all strips\44\ correctly orientated:0:*/
  995. static GBM_ERR get_image_orient(
  996.     int fd,
  997.     byte *dest,
  998.     TIF_PRIV *tif_priv,
  999.     GBM *gbm
  1000.     )
  1001.     {
  1002.     switch ( tif_priv -> orient )
  1003.         {
  1004. /*...s1 \45\ usual Baseline required case:16:*/
  1005. /*
  1006. File has array [scanlines_down] of array [pixels_across] of pixel.
  1007. GBMs bitmap data is array [scanlines_up] of array [pixels_across] of pixel.
  1008. So call get_image_planar(), and vertically reflect resulting data.
  1009. */
  1010.  
  1011. case 1:
  1012.     {
  1013.     int istride = ((gbm -> bpp * gbm -> w + 7) / 8);
  1014.     byte *p0, *p1, *p2;
  1015.     GBM_ERR rc;
  1016.     if ( (rc = get_image_planar(fd, dest, tif_priv, gbm)) != GBM_ERR_OK )
  1017.         return ( rc );
  1018.     if ( (p0 = malloc(istride)) == NULL )
  1019.         return ( GBM_ERR_MEM );
  1020.     for ( p1 = dest, p2 = p1 + (gbm -> h - 1) * istride;
  1021.           p1 < p2;
  1022.           p1 += istride, p2 -= istride )
  1023.         {
  1024.         memcpy(p0, p1, istride);
  1025.         memcpy(p1, p2, istride);
  1026.         memcpy(p2, p0, istride);
  1027.         }
  1028.     free(p0);
  1029.     return ( GBM_ERR_OK );
  1030.     }
  1031. /*...e*/
  1032. /*...s4 \45\ vertically swapped case we can easily handle:16:*/
  1033. /*
  1034. File has array [scanlines_up] of array [pixels_across] of pixel.
  1035. Exactly matches GBMs layout of a bitmap.
  1036. So simply call get_image() and be done with.
  1037. */
  1038.  
  1039. case 4:
  1040.     return ( get_image_planar(fd, dest, tif_priv, gbm) );
  1041. /*...e*/
  1042.         }
  1043.     return ( GBM_ERR_NOT_SUPP ); /* Shouldn't get here */
  1044.     }
  1045. /*...e*/
  1046.  
  1047. GBM_ERR tif_rdata(int fd, GBM *gbm, byte *data)
  1048.     {
  1049.     TIF_PRIV *tif_priv = (TIF_PRIV *) gbm -> priv;
  1050.     int stride = ((gbm -> bpp * gbm -> w + 31) / 32) * 4;
  1051.     int istride = ((gbm -> bpp * gbm -> w + 7) / 8);
  1052.     int bias = gbm -> h * (stride - istride);
  1053.     GBM_ERR    rc;
  1054.  
  1055.     /* Read in data, packed close, and upside down */
  1056.  
  1057.     if ( (rc = get_image_orient(fd, data + bias, tif_priv, gbm)) != GBM_ERR_OK )
  1058.         return ( rc );
  1059.  
  1060. /*...snow expand out from byte padding to dword padding:8:*/
  1061. if ( bias )
  1062.     {
  1063.     int y;
  1064.     byte *dest = data, *src  = data + bias;
  1065.  
  1066.     for ( y = 0; y < gbm -> h; y++, dest += stride, src += istride )
  1067.         memcpy(dest, src, istride);
  1068.     }
  1069. /*...e*/
  1070. /*...snow RGB \45\\62\ BGR if 24 bit data returned:8:*/
  1071. if ( gbm -> bpp == 24 )
  1072.     {
  1073.     int y;
  1074.     byte *p = data;
  1075.  
  1076.     for ( y = 0; y < gbm -> h; y++, p += stride )
  1077.         rgb_bgr(p, p, gbm -> w);
  1078.     }
  1079. /*...e*/
  1080.  
  1081.     return ( GBM_ERR_OK );
  1082.     }
  1083. /*...e*/
  1084. /*...stif_w:0:*/
  1085. /*
  1086. Write out data in a single large strip for now.
  1087. Note that the palette entrys are written as ((r << 8) | r).
  1088. This means they are 257/256 too big (insignificant).
  1089. Most programs only look at the top 8 bits (ie: no error).
  1090. A few (incorrectly) look at the bottom 8 bits.
  1091. Therefore we cater for all programs, with minimal fuss.
  1092. */
  1093.  
  1094. /*...suser_tag:0:*/
  1095. static BOOLEAN user_tag(IFD *ifd, char *name, short type, char *opt, char *def)
  1096.     {
  1097.     char    buf [200+1], *s;
  1098.  
  1099.     if ( (s = find_word_prefix(opt, name)) != NULL )
  1100.         sscanf(s + strlen(name), "%s", buf);
  1101.     else
  1102.         strcpy(buf, def);
  1103.  
  1104.     if ( *buf == '\0' )
  1105.         return ( TRUE );
  1106.  
  1107.     return ( add_ascii_tag(ifd, type, buf) );
  1108.     }
  1109. /*...e*/
  1110.  
  1111. GBM_ERR tif_w(char *fn, int fd, GBM *gbm, GBMRGB *gbmrgb, byte *data, char *opt)
  1112.     {
  1113.     BOOLEAN    baseline = ( find_word(opt, "pal1bpp") == NULL );
  1114.     int    stride = ((gbm -> bpp * gbm -> w + 31) / 32) * 4;
  1115.     int    ostride = ((gbm -> bpp * gbm -> w + 7) / 8);
  1116.     int    y;
  1117.     byte    *src;
  1118.     IFH    *ifh;
  1119.     IFD    *ifd;
  1120.     long    w = gbm -> w;
  1121.     long    h = gbm -> h;
  1122.     long    stripoffset, stripbytecount;
  1123.     short    samplesperpixel, bitspersample [3], photo;
  1124.     short    colormap [0x100+0x100+0x100];
  1125.     BOOLEAN    ok;
  1126.  
  1127.     fn=fn; /* Suppress 'unref arg' compiler warning */
  1128.  
  1129.     if ( (ifh = make_ifh()) == NULL )
  1130.         return ( GBM_ERR_MEM );
  1131.  
  1132.     ifd = ifh -> ifd;
  1133.  
  1134.     if ( gbm -> bpp == 1 && baseline )
  1135.         {
  1136.         word k0 = (word) gbmrgb [0].r + (word) gbmrgb [0].g + (word) gbmrgb [0].b;
  1137.         word k1 = (word) gbmrgb [1].r + (word) gbmrgb [1].g + (word) gbmrgb [1].b;
  1138.         samplesperpixel   = 1;
  1139.         bitspersample [0] = 1;
  1140.         photo = ( k0 < k1 ) ? PHOTO_BIT1 : PHOTO_BIT0; /* Black is zero : White is zero */
  1141.         }
  1142.     else if ( gbm -> bpp == 24 )
  1143.         {
  1144.         samplesperpixel   = 3;
  1145.         bitspersample [0] = 
  1146.         bitspersample [1] = 
  1147.         bitspersample [2] = 8;
  1148.         photo = PHOTO_RGB;
  1149.         }
  1150.     else
  1151.         {
  1152.         samplesperpixel   = 1;
  1153.         bitspersample [0] = (short) gbm -> bpp;
  1154.         photo = PHOTO_PAL;
  1155.         }
  1156.  
  1157.     ok = add_long_tag(ifd, T_IMAGEWIDTH, &w, 1) &&
  1158.          add_long_tag(ifd, T_IMAGELENGTH, &h, 1) &&
  1159.          add_long_tag(ifd, T_STRIPOFFSETS, &stripoffset, 1) &&
  1160.          add_long_tag(ifd, T_STRIPBYTECOUNTS, &stripbytecount, 1) &&
  1161.          add_short_tag(ifd, T_SAMPLESPERPIXEL, &samplesperpixel, 1) &&
  1162.          add_short_tag(ifd, T_BITSPERSAMPLE, bitspersample, samplesperpixel) &&
  1163.          add_short_tag(ifd, T_PHOTOMETRIC, &photo, 1) &&
  1164.          user_tag(ifd, "artist=", T_ARTIST, opt, "") &&
  1165.          user_tag(ifd, "software=", T_MAKE, opt, "Generalised Bitmap Module") &&
  1166.          user_tag(ifd, "make=", T_MAKE, opt, "") &&
  1167.          user_tag(ifd, "model=", T_MODEL, opt, "") &&
  1168.          user_tag(ifd, "hostcomputer=", T_HOSTCOMPUTER, opt, "") &&
  1169.          user_tag(ifd, "documentname=", T_DOCNAME, opt, "") &&
  1170.          user_tag(ifd, "pagename=", T_PAGENAME, opt, "") &&
  1171.          user_tag(ifd, "imagedescription=", T_DESCRIPTION, opt, "");
  1172.  
  1173.     if ( gbm -> bpp != 24 )
  1174.         {
  1175.         int    i, n_cols = (1 << gbm -> bpp);
  1176.  
  1177.         for ( i = 0; i < n_cols; i++ )
  1178.             {
  1179.             short    r = (short) gbmrgb [i].r;
  1180.             short    g = (short) gbmrgb [i].g;
  1181.             short    b = (short) gbmrgb [i].b;
  1182.  
  1183.             colormap [             i] = ((r << 8) | r);
  1184.             colormap [    n_cols + i] = ((g << 8) | g);
  1185.             colormap [2 * n_cols + i] = ((b << 8) | b);
  1186.             }
  1187.         if ( gbm -> bpp != 1 || !baseline )
  1188.             ok &= add_short_tag(ifd, T_COLORMAP, colormap, n_cols * 3);
  1189.         }
  1190.  
  1191.     if ( !ok )
  1192.         {
  1193.         free_ifh(ifh);
  1194.         return ( GBM_ERR_MEM );
  1195.         }
  1196.  
  1197.     if ( !write_ifh_and_ifd(ifh, fd) )
  1198.         {
  1199.         free_ifh(ifh);
  1200.         return ( GBM_ERR_WRITE );
  1201.         }
  1202.  
  1203.     stripoffset = lseek(fd, 0L, SEEK_CUR);
  1204.  
  1205.     src = data + ((gbm -> h - 1) * stride);
  1206.     if ( gbm -> bpp == 24 )
  1207. /*...sreverse and write:16:*/
  1208. {
  1209. byte    *line;
  1210.  
  1211. if ( (line = malloc(ostride)) == NULL )
  1212.     {
  1213.     free_ifh(ifh);
  1214.     return ( GBM_ERR_MEM );
  1215.     }
  1216. for ( y = 0; y < gbm -> h; y++, src -= stride )
  1217.     {
  1218.     rgb_bgr(src, line, gbm -> w);        
  1219.     if ( write(fd, line, ostride) != ostride )
  1220.         {
  1221.         free(line);
  1222.         free_ifh(ifh);
  1223.         return ( GBM_ERR_WRITE );
  1224.         }
  1225.     }
  1226. free(line);
  1227. }
  1228. /*...e*/
  1229.     else
  1230. /*...swrite:16:*/
  1231. for ( y = 0; y < gbm -> h; y++, src -= stride )
  1232.     if ( write(fd, src, ostride) != ostride )
  1233.         {
  1234.         free_ifh(ifh);
  1235.         return ( GBM_ERR_WRITE );
  1236.         }
  1237. /*...e*/
  1238.  
  1239.     stripbytecount = lseek(fd, 0L, SEEK_CUR) - stripoffset;
  1240.     
  1241.     update_long_tag(ifd, T_STRIPOFFSETS, &stripoffset);
  1242.     update_long_tag(ifd, T_STRIPBYTECOUNTS, &stripbytecount);
  1243.  
  1244.     if ( !update_ifd(ifd, fd) )
  1245.         {
  1246.         free_ifh(ifh);
  1247.         return ( GBM_ERR_WRITE );
  1248.         }
  1249.  
  1250.     free_ifh(ifh);
  1251.  
  1252.     return ( GBM_ERR_OK );
  1253.     }
  1254. /*...e*/
  1255. /*...stif_err:0:*/
  1256. char *tif_err(GBM_ERR rc)
  1257.     {
  1258.     switch ( (int) rc )
  1259.         {
  1260.         case GBM_ERR_TIF_VERSION:
  1261.             return ( "version number not 42" );
  1262.         case GBM_ERR_TIF_N_TAGS:
  1263.             return ( "too many tags in file" );
  1264.         case GBM_ERR_TIF_TAG_TYPE:
  1265.             return ( "bad tag type" );
  1266.         case GBM_ERR_TIF_HEADER:
  1267.             return ( "corrupt header" );
  1268.         case GBM_ERR_TIF_MISSING_TAG:
  1269.             return ( "ImageWidth, ImageLength or StripOffsets tag missing" );
  1270.         case GBM_ERR_TIF_SPP_BIT:
  1271.             return ( "SamplesPerPixel tag must be 1 for bitmap or greyscale file" );
  1272.         case GBM_ERR_TIF_BPS_BIT:
  1273.             return ( "BitsPerSample tag must be 1,4 or 8 for bitmap or greyscale file" );
  1274.         case GBM_ERR_TIF_SPP_RGB:
  1275.             return ( "SamplesPerPixel tag must be 3 or more for RGB file" );
  1276.         case GBM_ERR_TIF_BPS_RGB:
  1277.             return ( "BitsPerSample tag must be 8 for RGB file" );
  1278.         case GBM_ERR_TIF_SPP_PAL:
  1279.             return ( "SamplesPerPixel tag must be 1 for palettised file" );
  1280.         case GBM_ERR_TIF_BPS_PAL:
  1281.             return ( "BitsPerSample tag must be 1,4 or 8 for paletteised file" );
  1282.         case GBM_ERR_TIF_SPP_CMYK:
  1283.             return ( "SamplesPerPixel tag must be 4 for CMYK file" );
  1284.         case GBM_ERR_TIF_BPS_CMYK:
  1285.             return ( "BitsPerSample tag must be 8 for CMYK file" );
  1286.         case GBM_ERR_TIF_COMP_1D_MH:
  1287.             return ( "Compression tag is CCITT 1D Modified Huffman, not supported" );
  1288.         case GBM_ERR_TIF_COMP_T4:
  1289.             return ( "Compression tag is CCITT T.4 G3 Facsimile, not supported");
  1290.         case GBM_ERR_TIF_COMP_T6:
  1291.             return ( "Compression tag is CCITT T.6 G4 Facsimile, not supported");
  1292.         case GBM_ERR_TIF_COMP:
  1293.             return ( "Compression tag not uncompressed, PackBits or LZW, not supported" );
  1294.         case GBM_ERR_TIF_COLORMAP:
  1295.             return ( "ColorMap tag missing" );
  1296.         case GBM_ERR_TIF_CORRUPT:
  1297.             return ( "encoded data is corrupt" );
  1298.         case GBM_ERR_TIF_PREDICTOR:
  1299.             return ( "Predictor tag bad" );
  1300.         case GBM_ERR_TIF_N_STRIPS:
  1301.             return ( "too many strips" );
  1302.         case GBM_ERR_TIF_PHOTO_TRANS:
  1303.             return ( "PhotometricInterpretation tag is transparency mask, not supported" );
  1304.         case GBM_ERR_TIF_PHOTO_Y_Cb_Cr:
  1305.             return ( "PhotometricInterpreation tag is Y-Cb-Cr colour space, not supported" );
  1306.         case GBM_ERR_TIF_PHOTO:
  1307.             return ( "PhotometricInterpretation tag unsupported/bad" );
  1308.         case GBM_ERR_TIF_FILLORDER:
  1309.             return ( "FillOrder tag must be 1" );
  1310.         case GBM_ERR_TIF_PLANARCONFIG_1:
  1311.             return ( "PlanarConfiguration tag must be 1 for non RGB files" );
  1312.         case GBM_ERR_TIF_PLANARCONFIG_12:
  1313.             return ( "PlanarConfiguration tag must be 1 or 2 for RGB files" );
  1314.         case GBM_ERR_TIF_INKSET:
  1315.             return ( "InkSet tag indicates non-CMYK colour seperations" );
  1316.         case GBM_ERR_TIF_ORIENT:
  1317.             return ( "Orientation tag must be 1 or 4" );
  1318.         case GBM_ERR_TIF_INDEX:
  1319.             return ( "less bitmaps in file than index requested" );
  1320.         }
  1321.     return ( NULL );
  1322.     }
  1323. /*...e*/
  1324.