"Fossies" - the Fresh Open Source Software Archive

Member "imal-3.7.7b/xmtnimage11.cc" (23 Sep 2014, 97340 Bytes) of archive /linux/misc/imal-source.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "xmtnimage11.cc" see the Fossies "Dox" file reference documentation.

    1 //--------------------------------------------------------------------------//
    2 // xmtnimage11.cc                                                           //
    3 // Reading & writing TIF files                                              //
    4 // Latest revision: 10-10-2012                                              //
    5 // Copyright (C) 2008 by Thomas J. Nelson                                   //
    6 // See xmtnimage.h for Copyright Notice                                     //
    7 //--------------------------------------------------------------------------//
    8 
    9 #include "xmtnimage.h"
   10 
   11 extern int         ci;                 // current image
   12 extern Image      *z;
   13 extern Globals     g;
   14 #include "tiffio.h"                  // For libtiff version
   15 
   16 //------Variables for writing TIF files-------//
   17 
   18 taginfo *tag;
   19 short int totaltags;
   20 int stripline;
   21 int currentstrip;
   22 int image_quant=0;
   23 
   24 //--------------------------------------------------------------------------//
   25 // bitflip                                                                  //
   26 //--------------------------------------------------------------------------//
   27 char bitflip(char c)
   28 {
   29   int k;
   30   char a = 0;
   31   for(k=0;k<8;k++)
   32   { 
   33     if( c&(1<<k) ) a |= (1<<(7-k));
   34   }   
   35   return 0xff & a;
   36 }
   37 
   38 //--------------------------------------------------------------------------//
   39 // readtiffile - all this junk just figure out which tiff routine to use.   //
   40 //--------------------------------------------------------------------------//
   41 int readtiffile(char *filename, char *actual_filename)
   42 {
   43    FILE *fp;
   44                               // Up to 16 colors with different bits/pixels
   45    int cbps[16] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
   46    int k,ok=0;
   47    int mac=0;                         //  =1 if a Macintosh tif file
   48    image_quant=0;
   49    short int tif_byteorder=0;
   50    short int tif_version=0;
   51    short int tif_noofdirectories=0;
   52    int tif_offsettoIFD=0;
   53    short int tif_tag=0;
   54    short int tif_type=0;
   55    int tif_length       =0;
   56    int tif_value        =0;
   57 
   58    int tif_compression  =1;
   59    //int tif_photointerp  =1;
   60    int tif_sampperpixel =0;
   61    short int second_image=0;       
   62    //int tif_fillorder    =1;
   63    int bytestouse       =4;
   64    int tif_value_bps    =1;
   65    int bps=1;
   66    char junk;
   67        
   68    if ((fp=fopen(filename,"r")) == NULL)
   69    {   error_message(filename, errno);
   70        return(NOTFOUND);
   71    }
   72    if(g.tif_skipbytes) for(k=0;k<g.tif_skipbytes;k++) fread(&junk,1,1,fp);
   73 
   74    fread(&tif_byteorder,2,1,fp);  // This must be the same in all Tif files
   75    if(tif_byteorder==0x4d4d) mac=1; else mac=0;
   76    tif_fread(&tif_version,2,fp,mac,2); 
   77    tif_fread(&tif_offsettoIFD,4,fp,mac,4);
   78 
   79    fseek(fp, g.tif_skipbytes+tif_offsettoIFD, SEEK_SET);
   80    tif_fread(&tif_noofdirectories,2,fp,mac,2);
   81 
   82    for(k=1;k<=tif_noofdirectories;k++) 
   83    {
   84        tif_tag = 0;
   85        tif_fread(&tif_tag,2,fp,mac,2);
   86        tif_fread(&tif_type,2,fp,mac,2);
   87        tif_fread(&tif_length,4,fp,mac,4);
   88 
   89             // Bytestouse are needed in case it is mac file
   90        if(tif_type==1) bytestouse = 1;
   91        if(tif_type==2) bytestouse = 1;
   92        if(tif_type==3) bytestouse = 2;
   93        if(tif_type==4) bytestouse = 4;
   94        if(tif_type==5) bytestouse = 4;
   95        if(tif_length>1)bytestouse = 4;
   96 
   97        tif_fread(&tif_value,4,fp,mac,bytestouse);    
   98        if(bytestouse==1) tif_value &= 0xff;
   99        if(bytestouse==2) tif_value &= 0xffff;
  100        if(!second_image)
  101        {  
  102           switch (tif_tag)
  103           {  case 256: //tif_imagewidth   = tif_value; 
  104                        break;
  105              case 257: // tif_imagelength  = tif_value; 
  106                        break;
  107              case 258: bps = tif_value;
  108                        tif_value_bps = bps;
  109                        break;
  110              case 259: tif_compression  = tif_value; break;
  111              case 262: // tif_photointerp  = tif_value;
  112                        // if(tif_photointerp==5) cmyk=1; else cmyk=0;
  113                        break;
  114              case 266: //tif_fillorder    = tif_value; 
  115                        break;
  116              case 277: tif_sampperpixel = tif_value; break;
  117              default: break;
  118          }
  119        }         
  120    }
  121 
  122    ////  Now that we know the samples/pixel it is safe to guess at
  123    ////  what bps means.
  124 
  125    if((tif_value_bps!=0) && ((tif_sampperpixel>1)||(tif_value_bps>32)) )
  126    {  bps = 0;
  127       for(k=0; k<tif_sampperpixel; k++)
  128       {   cbps[k] = tif_value_at(tif_value_bps+k*2,2,fp,mac);
  129           bps += cbps[k];
  130       }
  131    }
  132    if(!between(bps, 0, 48))
  133    {   message("Bad bits/sample in TIFF file");  
  134        bps = tif_value_bps*tif_sampperpixel;
  135    }
  136 
  137    if(tif_sampperpixel<=0)
  138    { // message("Bad samples/pixel in TIFF file,\nusing 1"); 
  139       tif_sampperpixel=1; 
  140    }
  141 
  142    fclose(fp); // CHAPG  Error!
  143 
  144 
  145    ok=1;
  146    switch(tif_compression)
  147    {   case -1   :
  148        case 0    : 
  149        case 1    :
  150        case 5    :
  151        case 32773:
  152        case 32901: ok=1; break;
  153        default   : ok=0;
  154    }
  155    if(ok)
  156          return readtiffile_general(filename, actual_filename);
  157    else
  158          return readtiffile_libtiff(filename, actual_filename);
  159 }     
  160  
  161 
  162 
  163 //--------------------------------------------------------------------------//
  164 // readtiffile_libtiff                                                      //
  165 // libtiff just crashes if it tries to read an unsupported type of tif      //
  166 // file. So we have to read the file twice: once to find out if libtiff     //
  167 // can handle it, and once to actually read it.                             //
  168 // we mainly need libtiff to read LZW compressed tiffs. libtiff can't       //
  169 // handle the vast majority of scientific tiffs.                            //
  170 //--------------------------------------------------------------------------//
  171 int readtiffile_libtiff(char *filename, char *actual_filename)
  172 {
  173   TIFF *image;
  174   int bpp,bytes,ct=COLOR,x,y,rr,gg,bb,errors=0;
  175   uint16 photo, bps, spp, fillorder;
  176   uint32 width, height;
  177   tsize_t stripSize;
  178   unsigned long imageOffset, result;
  179   int stripMax, stripCount;
  180   char *buffer, tempbyte;
  181   unsigned long bufferSize, count;
  182   char tempstring[128];
  183 
  184   if((image = TIFFOpen(filename, "r")) == NULL)
  185   {   message("Could not open incoming image\n");
  186       return ERROR;
  187   }      
  188   if((TIFFGetField(image, TIFFTAG_SAMPLESPERPIXEL, &spp) == 0) || (spp != 1)) errors++;
  189   if((TIFFGetField(image, TIFFTAG_BITSPERSAMPLE, &bps) == 0) || (bps != 1)) errors++;
  190   bpp = bps * spp;
  191   stripSize = TIFFStripSize (image);
  192   stripMax = TIFFNumberOfStrips (image);
  193   imageOffset = 0;
  194   if(TIFFGetField(image, TIFFTAG_IMAGEWIDTH, &width) == 0) errors++;
  195   if(TIFFGetField(image, TIFFTAG_IMAGELENGTH, &height) == 0) errors++;
  196   if(TIFFGetField(image, TIFFTAG_PHOTOMETRIC, &photo) == 0) errors++;
  197   switch(photo)  // colortype
  198   {     case 0:
  199         case 1:  ct = GRAY; break;
  200         case 3:  ct = INDEXED; break;
  201         default: ct = COLOR; break;
  202   }
  203 
  204   //// Libtiff wastes space here, uses buffer larger than needed
  205   //// to hold image. The only solution is to use a giant buffer
  206   //// for the data, then copy the data into the image buffer.
  207   //// This could be over 10 MB ...
  208   
  209   bufferSize = TIFFNumberOfStrips (image) * stripSize; // can be larger than x*y*bytes/pixel
  210   newimage(actual_filename, 0, 0, width, height, bpp, ct, 
  211       1, g.want_shell, 1, PERM, 1, g.window_border, 0);  
  212   if((buffer = (char *) malloc(bufferSize)) == NULL)
  213   {   message("Could not allocate enough memory\nfor the uncompressed image");
  214       TIFFClose(image);
  215       return NOMEM;
  216   }      
  217   for (stripCount = 0; stripCount < stripMax; stripCount++)
  218   {   if((result = TIFFReadEncodedStrip (image, stripCount,
  219           buffer + imageOffset, stripSize)) == (uint)-1) errors++;
  220       imageOffset += result;
  221   }
  222 
  223   if(photo == PHOTOMETRIC_MINISWHITE)// Flip bits, note different from example
  224       for(count = 0; count < bufferSize; count++)
  225          buffer[count] = ~buffer[count];
  226   if(TIFFGetField(image, TIFFTAG_FILLORDER, &fillorder) == 0) errors++;
  227   if(fillorder == FILLORDER_MSB2LSB && bpp>8)// We need to swap bits -- ABCDEFGH becomes HGFEDCBA
  228   {   for(count = 0; count < bufferSize; count++)
  229       {    tempbyte = 0;
  230            if(buffer[count] & 128) tempbyte += 1;
  231            if(buffer[count] & 64) tempbyte += 2;
  232            if(buffer[count] & 32) tempbyte += 4;
  233            if(buffer[count] & 16) tempbyte += 8;
  234            if(buffer[count] & 8) tempbyte += 16;
  235            if(buffer[count] & 4) tempbyte += 32;
  236            if(buffer[count] & 2) tempbyte += 64;
  237            if(buffer[count] & 1) tempbyte += 128;
  238            buffer[count] = tempbyte;
  239       }
  240   }
  241   bytes = min(bufferSize,width*height*bpp/8);
  242   memcpy(z[ci].image_1d, buffer, bytes);
  243 
  244   //// Another abomination to fix the weird byte order in libtiff
  245 
  246   if(bpp>=24)   
  247   {    for(y=0; y<(int)height; y++)  
  248        for(x=0; x<(int)width; x++)  
  249        {    RGBat(z[ci].image[0][y]+3*x, bpp, rr, gg, bb); 
  250             swap(rr,bb);
  251             rr = 255-rr; gg = 255-gg; bb = 255-bb;
  252             setRGBbytes(z[ci].image[0][y]+3*x, rr, gg, bb, bpp);
  253         }
  254   } 
  255   free(buffer);
  256   TIFFClose(image);
  257   if(errors)
  258   {   sprintf(tempstring, "%d Errors reading TIFF file", errors);
  259       // message(tempstring); 
  260   }
  261   return OK;
  262 }
  263 
  264 
  265 //--------------------------------------------------------------------------//
  266 // readtiffile_general                                                      //
  267 // Non-libtiff method                                                       //
  268 // Assumes 32-bit integers and 16-bit short integers.                       //
  269 // Returns error code (OK if successful).                                   //
  270 // Based on information in the document "TIFF Revision 6.0 Final Q June 3,  //
  271 // 1992" from Aldus Corporation.                                            //
  272 //--------------------------------------------------------------------------//
  273 int readtiffile_general(char *filename, char *actual_filename)
  274 {  
  275 
  276 
  277    if(memorylessthan(16384)){  message(g.nomemory,ERROR); return(NOMEM); } 
  278    FILE *fp;
  279    uchar *buffer=NULL;
  280    uchar color1,color2;
  281    int* yvalue=0;  
  282 
  283    char temp2[128];
  284    char tempstring[1024];
  285    int palette[3][256];
  286    int ct=0,cmyk=0,i,i2,j,k,k2,ok=1,y,vv,frame;
  287    int r1,g1,b1,a,value;
  288    uint color;
  289    int mac=0;                         //  =1 if a Macintosh tif file
  290    g.getout=0;
  291    int sizefac=1;
  292    int image_type=7;
  293    image_quant=0;
  294    int invertbytes = g.invertbytes;
  295 
  296    double pfac;
  297    short int tif_byteorder=0;
  298    short int tif_version=0;
  299    short int tif_noofdirectories=0;
  300    short unsigned int palettetemp=0;
  301 
  302    int tif_offsettoIFD=0;
  303    short int tif_tag=0;
  304    short int tif_type=0;
  305    int w=0, tile=0;
  306    int status=OK;
  307    double xfac,yfac;
  308    int ytimesyfac, kxfac,kyfac;
  309      // tif_xoffset = x pixel starting position
  310 
  311    char *tif_string;
  312    int tif_length       =0;
  313    int tif_value        =0;
  314 
  315    int tif_imagewidth   =0;
  316    int tif_imagelength  =0;
  317    int tif_bitspersample=8;
  318    int tif_compression  =1;
  319    int tif_photointerp  =1;
  320    int tif_sampperpixel =0;
  321    int tif_rowsperstrip =0;
  322    int tif_stripbytes   =0;
  323    int tif_planarconfig =1;
  324    int tif_grayresponse =0; 
  325    int tif_grayrespcurv =0;
  326    int tif_start        =0;
  327    int tif_integer      =0;
  328    int tif_colormap     =0;
  329    int tif_tilelength   =0;
  330    int tif_tilewidth    =0;
  331    int tif_tileoffsets  =0;
  332    int tif_tileoffsettype=0;
  333    
  334 
  335    short int second_image=0;       
  336    int tif_predictor    =1;
  337    int tiles_across     =1;
  338    int tiles_down       =1;
  339    int tilexstart       =0;
  340    int tileystart       =0;
  341    int tif_stripsperimage=0;
  342    int tif_fillorder    =1;
  343    int* tif_strip=NULL;       // File offset for start of each strip 
  344    int* bytesperstrip=NULL;   // No.of bytes in each strip
  345    int mbpp  = g.bitsperpixel;   // Bits/pixel to store image in memory 
  346    int strip            =0;   // Counter for strips     
  347    int nooftiles        =1;   // If not broken up, it is 1 big tile
  348    int pos;
  349    int bytestouse       =4;
  350    int tif_value_bps    =1;
  351    int plane            =0;
  352                               // Up to 16 colors with different bits/pixels
  353    int cbps[16] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
  354    int bps=1;
  355    int cc,mm,yy,kk,ts,tb;
  356 
  357    int bytestoread;
  358    int* tileoffset=NULL;      // File offset for start of each tile
  359    int xtile=1,ytile=1;       // indexes to keep track of location
  360    int otif_imagelength =0;
  361    int length;
  362    int alloc1=0,alloc2  =0;   // Flags if arrays allocated    
  363    int alloc3=0,alloc4  =0;   // Flags if arrays allocated    
  364    int alloc5           =0;
  365    int dbpp;                  // difference in bits/pixel 
  366    int count            =0;                 
  367    int shift            =0;   // Amount to shift 4-bpp images
  368    int bitmask          =0;  
  369    int highest          =0;
  370    int palette_factor   =1;
  371    char junk;
  372    uchar cf,rr,gg,bb;
  373    uchar rr2,gg2,bb2;
  374    int red, green, blue;
  375        
  376    if ((fp=fopen(filename,"r")) == NULL)
  377    {   error_message(filename, errno);
  378        return(NOTFOUND);
  379    }
  380    if(g.tif_skipbytes) for(k=0;k<g.tif_skipbytes;k++) fread(&junk,1,1,fp);
  381    tif_string = new char[1024];
  382 
  383    fread(&tif_byteorder,2,1,fp);  // This must be the same in all Tif files
  384    if(tif_byteorder==0x4d4d) mac=1; else mac=0;
  385    tif_fread(&tif_version,2,fp,mac,2); 
  386    tif_fread(&tif_offsettoIFD,4,fp,mac,4);
  387 
  388    fseek(fp, g.tif_skipbytes+tif_offsettoIFD, SEEK_SET);
  389    tif_fread(&tif_noofdirectories,2,fp,mac,2);
  390 
  391    for(k=1;k<=tif_noofdirectories;k++) 
  392    {
  393        tif_tag = 0;
  394        tif_fread(&tif_tag,2,fp,mac,2);
  395        tif_fread(&tif_type,2,fp,mac,2);
  396        tif_fread(&tif_length,4,fp,mac,4);
  397 
  398             // Bytestouse are needed in case it is mac file
  399        if(tif_type==1) bytestouse = 1;
  400        if(tif_type==2) bytestouse = 1;
  401        if(tif_type==3) bytestouse = 2;
  402        if(tif_type==4) bytestouse = 4;
  403        if(tif_type==5) bytestouse = 4;
  404        if(tif_length>1)bytestouse = 4;
  405 
  406        tif_fread(&tif_value,4,fp,mac,bytestouse);    
  407        if(bytestouse==1) tif_value &= 0xff;
  408        if(bytestouse==2) tif_value &= 0xffff;
  409        if(!second_image)
  410        {  
  411           switch (tif_tag)
  412           {  case 256: tif_imagewidth   = tif_value; break;
  413              case 257: tif_imagelength  = tif_value; break;
  414              case 258: bps = tif_value;  // The meaning of this may
  415                                          // change depending on the
  416                                          // tif_sampperpixel, which could
  417                                          // be read later.
  418                        tif_value_bps = bps;
  419                        break;
  420              case 259: tif_compression  = tif_value; break;
  421              case 262: tif_photointerp  = tif_value;
  422                        if(tif_photointerp==5) cmyk=1; else cmyk=0;
  423                        break;
  424              case 266: tif_fillorder    = tif_value; break;
  425              case 273: if(!tif_start) tif_start = tif_value;
  426                        //  tif_stripoffsets = tif_value;
  427                        break;
  428              case 274: ////tif_orientation  = tif_value;
  429                        break;
  430              case 277: tif_sampperpixel = tif_value; break;
  431              case 278: tif_rowsperstrip = tif_value;
  432                        if(tif_rowsperstrip>1000000) 
  433                        {   sprintf(tempstring,"Error in TIFF file:\ntif_rowsperstrip = %d\nI'm assuming it should be %d",
  434                                    tif_rowsperstrip, tif_imagelength);
  435                            message(tempstring);
  436                            tif_rowsperstrip=tif_imagelength;
  437                        }
  438                        tif_stripsperimage = (tif_imagelength + 
  439                           tif_rowsperstrip - 1)/tif_rowsperstrip;
  440                        break;
  441              case 279:         // This value will be ignored if it turns
  442                                // out that there is only one strip.
  443                        tif_stripbytes   = tif_value;break;
  444              case 280: //// tif_minvalue     = tif_value;
  445                        break;
  446              case 281: //// tif_maxvalue     = tif_value;
  447                        break;
  448              case 282: //// tif_xres         = tif_value;
  449                        break;
  450              case 283: //// tif_yres         = tif_value;
  451                        break;
  452              case 284: tif_planarconfig = tif_value;break;
  453              case 290: tif_grayresponse = tif_value;break; 
  454              case 291: tif_grayrespcurv = tif_value;break;
  455              case 317: tif_predictor    = tif_value;break;       
  456              case 320: tif_colormap     = tif_value;break;       
  457              case 322: tif_tilewidth    = tif_value;break;
  458              case 323: tif_tilelength   = tif_value;break;
  459              case 324: tif_tileoffsets  = tif_value;
  460                        tif_tileoffsettype= tif_type;
  461                        break;
  462              case 325: //// tif_tilebytes = tif_value;
  463                        break;
  464           }
  465 
  466           length=tif_length*bytestouse;
  467           strip = 0;
  468           if((length>4)||(tif_type==5)) /* read field pointed to by value*/
  469           {  pos=ftell(fp);          
  470              fseek(fp, g.tif_skipbytes+tif_value, SEEK_SET);             
  471              if(tif_tag==273)
  472              {   tif_strip = new int[tif_length+40];
  473                  if(tif_strip==NULL){ message(g.nomemory,ERROR); goto tifend;}
  474                  alloc1=1;
  475              }  
  476              if(tif_tag==279)
  477              {   bytesperstrip=new int[tif_length+40];
  478                  if(bytesperstrip==NULL)
  479                  {   message(g.nomemory,ERROR); 
  480                      goto tifend; 
  481                  }
  482                  alloc2=1;
  483              }
  484              if(tif_type==4)              /* series of 4-byte integers */  
  485              {
  486                   for(j=0;j<tif_length;j++)
  487                   {  tif_integer=0;
  488                      tif_fread(&tif_integer,4,fp,mac,4);    
  489                      if((tif_tag==273)&&(alloc1==1))
  490                          tif_strip[strip]=tif_integer;
  491                      if((tif_tag==279)&&(alloc2==1))
  492                          bytesperstrip[strip]=tif_integer;
  493                      if(alloc1) tif_start=tif_strip[0];    
  494                      strip++;
  495                      if(strip>tif_length)
  496                      {    
  497                           message("Error: strip number exceeds\nnumber of image lines",ERROR);  
  498                           status = NOMEM;
  499                           goto tifend;
  500                      }     
  501                   }
  502              } 
  503              if(tif_tag==271)       /* make string */
  504                   fread(tif_string,min(100,tif_length),1,fp);
  505 
  506              fseek(fp,pos,SEEK_SET); /* jump back to where we were before*/
  507           }
  508        }   
  509    } 
  510 
  511    ////  Now that we know the samples/pixel it is safe to guess at
  512    ////  what bps means.
  513 
  514    if((tif_value_bps!=0) && ((tif_sampperpixel>1)||(tif_value_bps>32)) )
  515    {  bps = 0;
  516       for(k=0; k<tif_sampperpixel; k++)
  517       {   cbps[k] = tif_value_at(tif_value_bps+k*2,2,fp,mac);
  518           bps += cbps[k];
  519       }
  520    }
  521    //// Special hack for 48 bit tiffs made by registax
  522    if(tif_value_bps==16 && tif_sampperpixel==3)
  523    {
  524       for(k=0; k<tif_sampperpixel; k++) cbps[k]=16;      
  525       bps = 48;
  526    }
  527    if(!between(bps, 0, 48))
  528    {   message("Bad bits/sample in TIFF file");  
  529        bps = tif_value_bps*tif_sampperpixel;
  530    }
  531    tif_bitspersample = bps;
  532 
  533    if(tif_sampperpixel<=0)
  534    { // message("Bad samples/pixel in TIFF file,\nusing 1"); 
  535       tif_sampperpixel=1; 
  536    }
  537 
  538    ////  If it is 1 strip and no list of strip bytes was found, create
  539    ////  a short list and put strip length in.                        
  540 
  541    if(alloc1==0)
  542    {  alloc1=1;
  543       tif_strip = new int[256];
  544       tif_strip[0] = tif_start;
  545    }  
  546    if(alloc2==0)
  547    {  alloc2=1;
  548       bytesperstrip=new int[256];
  549       bytesperstrip[0] = tif_stripbytes;
  550    }
  551 
  552    tif_fread(&tif_offsettoIFD,4,fp,mac,4);   
  553    if(tif_offsettoIFD)
  554    {   second_image++;
  555        //if(second_image==1)
  556        //  message("Only the 1st image in your file will be displayed");
  557    }    
  558 
  559    strcpy(tempstring,"Sorry, can't read "); 
  560    ok=0;   
  561         //---To add a new compression:-------------------------------
  562         //     1. change ok to 1 after corresponding compression type
  563         //     2. remove strcat statement
  564         //     3. add decoding in tif_getlineofpixels
  565         //-----------------------------------------------------------
  566 
  567    switch(tif_compression)  
  568    {   case -1   :
  569        case 0    : 
  570        case 1    :ok=1; break;
  571        case 2    :ok=0; strcat(tempstring,"CCITT RLE");  break;
  572        case 5    :ok=1; break;     //LZW
  573        case 6    :ok=0; strcat(tempstring,"JPEG");  break;
  574        case 32766:ok=0; strcat(tempstring,"2-bit RLE/NeXT\n");break;
  575        case 32771:ok=0; strcat(tempstring,"CCITT/align\n");break;
  576        case 32773:ok=1; break;     //PackBits 
  577        case 32809:ok=0; strcat(tempstring,"Thunderscan\n");break;
  578        case 32900:ok=0; strcat(tempstring,"Pixar RLE");  break;
  579        case 32901:ok=1; break;     //SGI RLE (16bpp packbits)
  580        default   :ok=0; 
  581                   strcat(tempstring,"type ");   
  582                   itoa(tif_compression,temp2,10);
  583                   strcat(tempstring,temp2);   
  584                   strcat(tempstring,"\n");   
  585                   break;
  586       }
  587 
  588    if(!ok)
  589    {  strcat(tempstring," compressed TIF images");
  590       message(tempstring,WARNING);
  591       status = ERROR;
  592       goto tifend;
  593    }    
  594 
  595          //---If 2 or more samples per pixel (color), make bpp ----//
  596          //---at least 16. `mbpp' is now the bits/pixel for the----//
  597          //---image in image[] buffer. `tif_bitspersample' is  ----//
  598          //---the original bits/pixel of the image file.       ----//
  599 
  600    if((tif_sampperpixel>1)&&(tif_bitspersample<16)) 
  601    {  message("Using 16 bpp for color image",WARNING);
  602       mbpp = max(tif_bitspersample, 16);
  603    }
  604    else mbpp=tif_bitspersample;
  605 
  606    //---pfac = No. of pixels to worry about for each byte----//
  607    //---     = 8 for 1 bit/pixel, 1 for 8 bits/pixel     ----//
  608    //---make it slightly smaller in case of round off err----//
  609 
  610    pfac = 7.9999/(double)tif_bitspersample;
  611 
  612    if((mbpp==1)||(mbpp==4))
  613       while(tif_imagewidth%(int)(1.001*pfac)) tif_imagewidth++;
  614    mbpp = max(8, mbpp);
  615 
  616    sizefac = max(g.off[g.bitsperpixel], (1+mbpp)/8);
  617    sizefac = max(2,sizefac);     // In case 3 samples/pixel -> 16 bpp
  618 
  619        //----In case the image is broken up into `tiles'---------//    
  620 
  621    if(tif_tilewidth)        
  622    {  
  623        tiles_across = (tif_imagewidth +tif_tilewidth -1)/tif_tilewidth;
  624        tiles_down   = (tif_imagelength+tif_tilelength-1)/tif_tilelength;
  625        nooftiles = tiles_across * tiles_down;
  626 
  627        //----Actual image width & length are now greater----// 
  628        //----because of bytes wasted to pad up to tile  ----// 
  629        //----boundaries.                                ----//
  630 
  631        otif_imagelength = tif_imagelength;
  632        tif_imagewidth = tif_tilewidth * tiles_across; 
  633        tif_imagelength = tif_tilelength * tiles_down; 
  634                              
  635        //---A tiled image can have its offsets listed   ----//
  636        //---as if they were strips, or can have separate----//
  637        //---tile offsets. Use (nooftiles > 1) to test   ----//
  638        //---if it is a tiled image. Use (tif_tileoffsets----//
  639        //---!=0) to test if it has tile offsets.        ----//
  640 
  641        if(tif_tileoffsets)   
  642        {   tileoffset = new int(nooftiles);
  643            if(tileoffset==NULL){ message(g.nomemory,ERROR); goto tifend;}
  644            alloc3=1;
  645            fseek(fp, g.tif_skipbytes+tif_tileoffsets, SEEK_SET);
  646            for(k=0;k<nooftiles;k++)
  647            {   if(tif_tileoffsettype==3)bytestoread=2; else bytestoread=4;
  648                tif_fread(&tileoffset[k],bytestoread,fp,mac,bytestoread);
  649            }
  650        }    
  651    }else
  652    {   tif_tilewidth  = tif_imagewidth;
  653        tif_tilelength = tif_imagelength;
  654        otif_imagelength = tif_imagelength;
  655    }   
  656 
  657    ////  Limitations for some types of files                     
  658    ////  LZW files must be vertical & full size if they are 8bpp.
  659    ////  TIF files must be full size to de-difference correctly. 
  660 
  661    if(tif_compression==5) 
  662    {    if(tif_bitspersample!=8) { g.tif_xsize=1; g.tif_ysize=1;  }
  663    }    
  664    if(tif_predictor==2) { g.tif_xsize=1; g.tif_ysize=1;  }
  665 
  666    //---------start of allocate space section----------------//
  667 
  668    yvalue = new int[tif_imagelength+1];
  669    if(yvalue!=0)
  670    {    alloc5=1;
  671         for(k=0;k<=tif_imagelength;k++) yvalue[k]=k;   // Not used, for interlaced gifs
  672    }else{ message(g.nomemory,ERROR); goto tifend;}
  673 
  674    if(tif_rowsperstrip==0) tif_rowsperstrip = tif_imagelength;
  675    buffer = new uchar[tif_rowsperstrip*sizefac*(tif_imagewidth+4)];  
  676    if(buffer==NULL){ message(g.nomemory,ERROR); goto tifend;}
  677    alloc4=1;
  678    if(tif_sampperpixel>1) ct=COLOR; else ct=INDEXED;
  679    if(tif_imagelength > 1e8){ message("Error reading tif file"); goto tifend; }
  680 
  681    status=newimage(actual_filename, g.tif_xoffset, g.tif_yoffset,
  682                    (int)(0.99999 + (tif_imagewidth)*g.tif_xsize),
  683                    (int)(0.99999 + (tif_imagelength)*g.tif_ysize),
  684                    mbpp, ct, 1, g.want_shell, 1, PERM, 1,
  685                    g.window_border, 0);  
  686 
  687    if(status != OK){ message(g.nomemory,ERROR); goto tifend;}
  688    z[ci].backedup = 0;
  689    cf = 0;
  690    frame = z[ci].cf;
  691    z[ci].bpp = mbpp;  // needed for readLZWencodedfile
  692    
  693    //-----------end of allocate space section----------------//
  694 
  695    if(tif_grayresponse)
  696    {  fseek(fp, g.tif_skipbytes+tif_grayrespcurv, SEEK_SET);
  697       for(k=0;k<=255;k++)        // Gamma[][] is allocated in all images
  698       {    z[ci].gamma[k]=0;     // Set to 0 because 32 bit integers
  699            tif_fread(&z[ci].gamma[k],2,fp,mac,2);
  700       }
  701    }
  702 
  703    //----If image has palette, read & set palette------------//
  704 
  705    highest=0;
  706    palette_factor = 1;
  707    if((1<<tif_bitspersample) > 256)
  708    {  // message("Error reading colormap!");
  709    }else
  710    if(tif_colormap && tif_photointerp==3)
  711    {  fseek(fp, g.tif_skipbytes+tif_colormap, SEEK_SET);
  712       for(k=0;k<(1<<tif_bitspersample);k++)
  713       {   tif_fread(&palettetemp,2,fp,mac,2);
  714           highest=max(highest,palettetemp);
  715           palette[0][k] = palettetemp;
  716       }
  717       for(k=0;k<(1<<tif_bitspersample);k++)
  718       {   tif_fread(&palettetemp,2,fp,mac,2);
  719           highest=max(highest,palettetemp);
  720           palette[1][k] = palettetemp;
  721       }
  722       for(k=0;k<(1<<tif_bitspersample);k++)
  723       {   tif_fread(&palettetemp,2,fp,mac,2);
  724           highest=max(highest,palettetemp);
  725           palette[2][k] = palettetemp;
  726       }
  727       if(highest<64) palette_factor = 1;       // 6 bit colormap
  728       else if(highest<256) palette_factor=4;   // 8 bit colormap
  729       else palette_factor=1024;                // 16-bit colormap
  730       for(k=0;k<(1<<tif_bitspersample);k++)
  731       {   g.palette[k].red = min(63, palette[0][k]/palette_factor);
  732           g.palette[k].green = min(63, palette[1][k]/palette_factor);
  733           g.palette[k].blue = min(63, palette[2][k]/palette_factor);
  734       }
  735       setpalette(g.palette);
  736    }
  737 
  738   xfac=g.tif_xsize;
  739   kxfac=(int)(xfac*64);           // integer to speed up multiplication
  740                                   // so  xfac*k  ==  ((kxfac*k)>>6).
  741   yfac=g.tif_ysize;               // yfac=size in y dimension, 0-1 1=full size
  742   kyfac=(int)(yfac*64);           // integer to speed up multiplication
  743                                   // so  yfac*k  ==  ((kyfac*k)>>6).
  744 
  745   //// Determine if image is a standard bpp Tif 
  746 
  747   ts = 0;
  748   if(tif_sampperpixel>1)
  749   {  if(cbps[0]) ts++;
  750      if(cbps[1]) ts++;
  751      if(cbps[2]) ts++;
  752      if(cbps[3]) ts++;
  753   }
  754   tb = tif_bitspersample;   
  755   image_type=8;                                    // custom
  756   if (tb==1 )           image_type=0;              // monochrome
  757   if((tb==4 )&&(ts==0)) image_type=1;              // 4 bpp        
  758   if((tb==8 )&&(ts==0)) image_type=2;              // 8 bpp palette
  759   if((tb==16)&&(ts==3)) image_type=4;              // 16 bpp color
  760   if((tb==24)&&(ts==3)) image_type=5;              // 24 bpp color
  761   if((tb==32)&&(ts>=3)) image_type=6;              // 32 bpp color
  762   if((tb==48)&&(ts==3)) image_type=7;              // 48 bpp color
  763   fseek(fp, g.tif_skipbytes+tif_start, SEEK_SET);
  764 
  765   ////  Start reading image data. Pretend the image could have both    
  766   ////  and strips even though it currently can only have one or the   
  767   ////  other. It is only a matter of time before the spec. changes    
  768   ////  again to allow both.                                           
  769   tileystart = 0;
  770 
  771   if(tif_compression==5)
  772   {
  773         readLZWencodedfile(fp,0,9,256,tif_imagewidth,tif_imagelength,kxfac,
  774               kyfac,tif_bitspersample,TIF,tif_stripsperimage,
  775               bytesperstrip,tif_strip,yvalue);
  776      
  777         ////  Horizontally de-difference (LZW only)   
  778         ////  rr,gg,bb must be signed characters.      
  779 
  780         if(tif_predictor==2)   
  781         { for(j=0;j<tif_imagelength;j++) 
  782           {  rr2=0;gg2=0;bb2=0;
  783              for(i=0;i<tif_imagewidth*g.off[tb];i+=g.off[tb])
  784              {  
  785                 value= pixelat(z[ci].image[z[ci].cf][j]+i,tb);
  786                 valuetoRGB(value,r1,g1,b1,tb);
  787                 rr=r1; gg=g1; bb=b1;
  788                 rr += rr2;
  789                 gg += gg2;
  790                 bb += bb2;
  791                 value = RGBvalue(rr,gg,bb,tb);
  792                 putpixelbytes(z[ci].image[z[ci].cf][j]+i,value,1,tb,1);
  793                 rr2=rr; gg2=gg; bb2=bb;
  794              }  
  795           }     
  796         }
  797   }              
  798   else
  799   for(tile=0;tile<nooftiles;tile++)
  800   {
  801      y = tileystart;
  802      if(tif_tileoffsets) fseek(fp, g.tif_skipbytes+tileoffset[tile],SEEK_SET);
  803      currentstrip=0;
  804      stripline=0;
  805      while(1)
  806      {    ytimesyfac=(int)(y*yfac);    
  807           
  808           //--------Get some bytes---------------------//
  809 
  810           w = (int)((tif_tilewidth)/pfac);
  811 
  812           if(tif_planarconfig==2) w/=3;
  813 
  814           tif_getlineofpixels(fp, buffer, w, tif_compression, tif_bitspersample,
  815                     mac, tif_rowsperstrip, tif_strip, nooftiles);
  816 
  817           //--------If they are padding bytes in a ----//
  818           //--------tiled image, throw them away   ----//
  819         
  820           if((nooftiles>1)&&(ytile==tiles_down)&&(y>otif_imagelength))
  821               memset(buffer,0,(int)(tif_imagewidth*g.tif_xsize));
  822 
  823           ////  Flip bits
  824           if(tif_fillorder == 2)
  825              for(k=0; k<w; k++) buffer[k] = bitflip(buffer[k]);
  826 
  827           ////  Default case is significantly slower, so keep special   
  828           ////  cases for the common types of 8,16,24,and 32 bpp.    
  829 
  830           switch(image_type)
  831           {  
  832              case 7:             // 48 bit
  833                if(tif_planarconfig==2)
  834                {
  835                   for(k=0;k<tif_imagewidth;k++)
  836                       z[ci].image[cf][y][k*6+4-plane] = buffer[k];
  837                }else         
  838                {  for(k=0;k<w;k+=6)
  839                   {   
  840                       red   = (buffer[k+1]<<8) + buffer[k+0];  
  841                       green = (buffer[k+3]<<8) + buffer[k+2];
  842                       blue  = (buffer[k+5]<<8) + buffer[k+4];
  843                       i = ((kxfac*k)>>6) + tilexstart;                    
  844                       if(xfac!=1)
  845                       {  i = ((kxfac*k)>>6) + tilexstart; 
  846                          i += 4-(i&3);   //Align i to start on pixel boundary
  847                       }else
  848                       {  i = k + tilexstart; 
  849                       }
  850                       setRGBbytes(z[ci].image[frame][ytimesyfac]+i, red, green, blue, 48);
  851                     }
  852                }
  853                break;
  854 
  855 
  856              case 6:             // 32 bpp, 2 or more colors
  857                if(tif_planarconfig==2)
  858                {
  859                   for(k=0;k<tif_imagewidth;k++)
  860                       z[ci].image[cf][y][k*4+3-plane] = buffer[k];
  861                }else         
  862                {  if(cmyk && g.read_cmyk)
  863                   { for(k=0;k<w;k+=4)
  864                     {  
  865                         if(g.fix_cmyk)
  866                         {   if(invertbytes)
  867                             {   cc = buffer[k+1];  // Note: reversed bytes
  868                                 mm = buffer[k+2];
  869                                 yy = buffer[k+3];
  870                                 kk = buffer[k+4];
  871                             }else
  872                             {   
  873                                 cc = buffer[k+3];  // Note: reversed bytes
  874                                 mm = buffer[k+2];
  875                                 yy = buffer[k+1];
  876                                 kk = buffer[k+0];
  877                             }
  878                         }
  879                         else
  880                         {   if(invertbytes)
  881                             {   cc = buffer[k+4];  // Note: reversed bytes
  882                                 mm = buffer[k+3];
  883                                 yy = buffer[k+2];
  884                                 kk = buffer[k+1];
  885                             }else
  886                             {   
  887                                 cc = buffer[k+0];  // Note: reversed bytes
  888                                 mm = buffer[k+1];
  889                                 yy = buffer[k+2];
  890                                 kk = buffer[k+3];
  891                             }
  892                         }
  893                         i = ((kxfac*k)>>6) + tilexstart;                    
  894                         if(xfac!=1)
  895                         {  i = ((kxfac*k)>>6) + tilexstart; 
  896                            i += 4-(i&3);   //Align i to start on pixel boundary
  897                         }else
  898                         {  i = k + tilexstart; 
  899                         }
  900                         rr = max(0,min(255,255-cc-kk));
  901                         gg = max(0,min(255,255-mm-kk));
  902                         bb = max(0,min(255,255-yy-kk));
  903                         vv = RGBvalue(rr,gg,bb,32);
  904                         putpixelbytes(z[ci].image[frame][ytimesyfac]+i, vv, 1, 32, 1);
  905                     }
  906                   }else
  907                   { for(k=0;k<w;k+=4)
  908                     {   if(xfac!=1)
  909                         {  i = ((kxfac*k)>>6) + tilexstart; 
  910                            i += 4-(i&3); // Align i to start on pixel boundary
  911                         }else
  912                         {  i = k + tilexstart; 
  913                         }
  914                         rr = buffer[k+2];
  915                         gg = buffer[k+1];
  916                         bb = buffer[k+0];
  917                         vv = RGBvalue(rr,gg,bb,32);
  918                         putpixelbytes(z[ci].image[frame][ytimesyfac]+i, vv, 1, 32, 1);
  919                     }
  920                   }  
  921                }
  922                break;
  923              case 5:    // 24 bpp, 2 or more colors
  924                if(tif_planarconfig==2)
  925                {
  926                   for(k=0;k<tif_imagewidth;k++)
  927                       z[ci].image[cf][y][k*3+2-plane] = buffer[k];
  928                }else 
  929                for(k=0;k<w;k+=3)
  930                {      if(xfac!=1)
  931                       {  i = ((kxfac*k)>>6) + tilexstart; 
  932                          while(i%3) i++; // Align i to start on pixel boundary
  933                       }else
  934                       {  i = k + tilexstart; 
  935                       }                  
  936                       z[ci].image[z[ci].cf][ytimesyfac][i+2] = buffer[k  ];
  937                       z[ci].image[z[ci].cf][ytimesyfac][i+1] = buffer[k+1];
  938                       z[ci].image[z[ci].cf][ytimesyfac][i+0] = buffer[k+2];
  939                }
  940                break;
  941              case 4:   // 16 bpp, 2 or more colors
  942                for(k=0;k<w;k+=2)
  943                {      if(xfac!=1)
  944                       {  i = ((kxfac*k)>>6) + tilexstart; 
  945                          i += i & 1;    // Align i to start on pixel boundary
  946                       }else
  947                       {  i = k + tilexstart; 
  948                       }
  949                       z[ci].image[z[ci].cf][ytimesyfac][i+1] = buffer[k  ];
  950                       z[ci].image[z[ci].cf][ytimesyfac][i  ] = buffer[k+1];
  951                }
  952                break; 
  953              case 2:    // 8 bpp, 1 color
  954                if(xfac==1)
  955                      memcpy(z[ci].image[z[ci].cf][ytimesyfac]+tilexstart,buffer,w);
  956                else
  957                      for(k=0;k<w;k++)
  958                      {   i = (kxfac*(k+tilexstart)) >> 6; 
  959                          z[ci].image[z[ci].cf][ytimesyfac][i] = buffer[k];
  960                      }   
  961                break;
  962              case 1:   // 4 bpp from a VGA - can have 4 bit palette
  963                 shift = 4;
  964                 if((tif_colormap)&&(tif_photointerp==3)) shift=0;
  965                 if(tif_planarconfig==1)
  966                 {     for(k=0;k<w;k++)
  967                       {  color1=(buffer[k]>>4)<<shift;
  968                          color2=(buffer[k]&0x0f)<<shift;
  969                          if(xfac==1)
  970                          { z[ci].image[z[ci].cf][ytimesyfac][(k<<1)+tilexstart  ]= color1;
  971                            z[ci].image[z[ci].cf][ytimesyfac][(k<<1)+tilexstart+1]= color2;
  972                          }else
  973                          { i =((kxfac*((k<<1)  ))>>6) + tilexstart;
  974                            z[ci].image[z[ci].cf][ytimesyfac][i]=color1;
  975                            i =((kxfac*((k<<1)+1))>>6) + tilexstart;
  976                            z[ci].image[z[ci].cf][ytimesyfac][i]=color2;
  977                          }
  978                       }
  979                 }else 
  980                 {message("Error reading TIF file-\nunsupported planar config",ERROR);
  981                  status=ERROR;
  982                 }    
  983                 break;
  984              case 0:       // monochrome- convert to 8 bpp then to color_type
  985                 for(i=0;i<w;i++)
  986                 { 
  987                      for(k2=0;k2<8;k2++)
  988                      {   
  989                          bitmask = 1 << (7-k2);
  990                          color = (buffer[i] & bitmask) >> (7-k2);
  991                          if(color) color=255;
  992                          if(tif_photointerp==0) color=255-color;
  993                          if(xfac==1)
  994                             z[ci].image[z[ci].cf][ytimesyfac][i*8+k2+tilexstart]=color; 
  995                          else    
  996                          {   i2 = ( (kxfac*i*8+k2 ) >> 6 ) + tilexstart;
  997                              z[ci].image[z[ci].cf][ytimesyfac][i2]=color;  
  998                          }    
  999                      }
 1000                 }    
 1001                 break;
 1002              default:
 1003                mbpp = z[ci].bpp;
 1004                getbits(0,buffer,0,RESET);  //reset
 1005                count=0;
 1006                for(k=0,k2=0;;k+=g.off[mbpp],k2++)
 1007                {   count++;                  
 1008                    if(count>tif_tilewidth) break;
 1009                    if(tif_sampperpixel==1)
 1010                    {   value = getbits(tif_bitspersample,buffer,w,TIF);
 1011                        if(tif_bitspersample<=8) // filter thru current palette
 1012                        {   dbpp = 8-tif_bitspersample;
 1013                            value++;
 1014                            value <<= dbpp;
 1015                            value--;
 1016                            valuetoRGB(value,r1,g1,b1,8);   //get palette entries
 1017                            value = RGBvalue(r1,g1,b1,mbpp);//calc.output value
 1018                        }else
 1019                        if(tif_bitspersample<=16) // convert to 16 bpp
 1020                        {   dbpp = 16-tif_bitspersample;
 1021                            value++;
 1022                            value <<= dbpp;
 1023                            value--;
 1024                        }else
 1025                        if(tif_bitspersample<=24) // convert to 24 bpp
 1026                        {   value++;
 1027                            dbpp = 24-tif_bitspersample;
 1028                            value <<= dbpp;
 1029                            value--;
 1030                        }else
 1031                        if(tif_bitspersample<=32) // convert to 32 bpp
 1032                        {   value++;
 1033                            dbpp = 32-tif_bitspersample;
 1034                            value <<= dbpp;
 1035                            value--;
 1036                        }    
 1037                    }else 
 1038                    {   
 1039 
 1040                        r1 = getbits(cbps[0],buffer,w,TIF);
 1041                        g1 = getbits(cbps[1],buffer,w,TIF);
 1042                        b1 = getbits(cbps[2],buffer,w,TIF);
 1043                        kk= getbits(cbps[3],buffer,w,TIF);
 1044 
 1045                        dbpp = g.redbpp[mbpp]   - cbps[0];
 1046                        if(dbpp>0) r1 <<= ( dbpp);
 1047                        if(dbpp<0) r1 >>= (-dbpp);
 1048                      
 1049                        dbpp = g.greenbpp[mbpp] - cbps[1];    
 1050                        if(dbpp>0) g1 <<= ( dbpp);
 1051                        if(dbpp<0) g1 >>= (-dbpp);
 1052                      
 1053                        dbpp = g.bluebpp[mbpp]  - cbps[2];  
 1054                        if(dbpp>0) b1 <<= ( dbpp);
 1055                        if(dbpp<0) b1 >>= (-dbpp);
 1056                        if((g.read_cmyk)&&(cmyk))
 1057                        {    dbpp = g.redbpp[mbpp] - cbps[3];  
 1058                             if(dbpp>0) kk <<= ( dbpp);
 1059                             if(dbpp<0) kk >>= (-dbpp);
 1060 
 1061                             a  = g.maxred[mbpp];
 1062                             r1 = max(0,min(a,a-r1-kk));
 1063                             a  = g.maxgreen[mbpp];
 1064                             g1 = max(0,min(a,a-g1-kk));
 1065                             a  = g.maxblue[mbpp];
 1066                             b1 = max(0,min(a,a-b1-kk));
 1067                        }
 1068                        value = RGBvalue(r1,g1,b1,mbpp);  //Pixel value in memory
 1069                    }                      
 1070 
 1071                    if(xfac!=1)
 1072                    {       i = ((kxfac*k)>>6) + tilexstart; 
 1073                            switch(g.off[mbpp])//Align i to start on pixel boundary
 1074                            {  case 2: i &= 0xfffffffe; break;
 1075                               case 3: i -= i%3;        break;
 1076                               case 4: i &= 0xfffffffc; break;  
 1077                            }   
 1078                    }else i = k + tilexstart;                   
 1079                    putpixelbytes(z[ci].image[z[ci].cf][ytimesyfac]+i, value, 1,
 1080                            mbpp, 1);
 1081                }
 1082                break;  
 1083           }  
 1084           if(keyhit()) if(getcharacter()==27){ status=ABORT; break; }
 1085           if(g.getout){ status=ABORT; break; }
 1086           y++;     
 1087           if(tif_planarconfig==2 && y>=tif_imagelength && plane<tif_sampperpixel-1)
 1088           {   plane++; y=0; }
 1089           if(y-tileystart>=tif_tilelength) break;  // At end of a tile
 1090           if(y>tif_imagelength) break;             // Finished entire image
 1091      }
 1092      tilexstart += tif_tilewidth;
 1093      xtile++;
 1094      if(xtile > tiles_across)
 1095      {   tilexstart=0;
 1096          xtile=1;
 1097          ytile++;
 1098          tileystart += tif_tilelength;
 1099      }  
 1100        
 1101   }   
 1102 
 1103 tifend:
 1104   fclose(fp);
 1105   z[ci].touched = 0;
 1106 
 1107   switch(tif_photointerp)
 1108   {     case 0:
 1109         case 1:  z[ci].colortype=GRAY; break;
 1110         case 3:  z[ci].colortype=INDEXED; break;
 1111         default: z[ci].colortype=COLOR; break;
 1112   }
 1113 
 1114   if(tif_sampperpixel==1 && tif_bitspersample>8) z[ci].colortype=GRAY;
 1115   if(tif_sampperpixel==1 && tif_photointerp==0) invertimage(ci);
 1116   if(!mac && tif_bitspersample>8 && z[ci].colortype==GRAY) swap_image_bytes(ci);
 1117   
 1118   if(alloc5) delete[] yvalue;
 1119   if(alloc4) delete[] buffer;
 1120   if(alloc3) delete[] tileoffset;
 1121   if(alloc2) delete[] bytesperstrip;
 1122   if(alloc1) delete[] tif_strip;
 1123   delete[] tif_string;
 1124   return(status);      
 1125 }
 1126 
 1127 
 1128 
 1129 //--------------------------------------------------------------------------//
 1130 // getbits                                                                  //
 1131 // Gets n bits from a buffer. n can be 0 to sizeof(int).                    //
 1132 // Returns an int. The bits are right-shifted.                              //
 1133 // Works for 16 or 32-bit integers.                                         //
 1134 //                                                                          //
 1135 // blockpos  = Current position in array `block' (wraps to 0 if all the     //
 1136 //             bytes are used, i.e. if blockpos exceeds blocksize.          //
 1137 // blocksize = Size of array `block'                                        //
 1138 // block     = char array of the data already read from disk                //
 1139 //                                                                          //
 1140 // Keeps track of bits left over and bytes unread.                          //
 1141 // If mode==RESET                                                           //
 1142 //  Starts over at start of buffer                                          //
 1143 // If mode==NONE                                                            //
 1144 //  Assumes bits are not packed. Gets 1 or more even bytes per call.        //
 1145 // If mode==GIF                                                             //
 1146 //  Assumes bits are packed in the following format (example for n=9) :     //
 1147 //                      7  6  5  4    3  2  1  0                            //
 1148 //                    ----------------------------                          //
 1149 //     Byte 1          a7 a6 a5 a4   a3 a2 a1 a0                            //
 1150 //     Byte 2          b6 b5 b4 b3   b2 b1 b0 a8                            //
 1151 //     Byte 3          c5 c4 c3 c2   c1 c0 b8 b7                            //
 1152 //     Byte 4          d4 c3 d2 d1   d0 c8 c7 c6                            //
 1153 //     ...                                                                  //
 1154 // If mode==TIF                                                             //
 1155 //  Assumes bits are packed in the following format (example for n=9) :     //
 1156 //                      7  6  5  4    3  2  1  0                            //
 1157 //                    ----------------------------                          //
 1158 //     Byte 1          a8 a7 a6 a5   a4 a3 a2 a1                            //
 1159 //     Byte 2          a0 b8 b7 b6   b5 b4 b3 b2                            //
 1160 //     Byte 3          b1 b0 c8 c7   c6 c5 c4 c3                            //
 1161 //     Byte 4          c2 c1 c0 d8   d7 d6 d5 d4                            //
 1162 //     ...                                                                  //
 1163 //--------------------------------------------------------------------------//
 1164 int getbits (int n, uchar* block, int blocksize, int mode)
 1165 {
 1166    static int blockpos = 0;
 1167    static int bitsleft = 8;
 1168    static uchar nextbyte = block[0];
 1169 
 1170    
 1171    int newno=0,answer=0;
 1172    int need = n;
 1173    int n1 = n;                                   // No.of bits from 1st byte
 1174 
 1175    newno=0;
 1176    answer=0;
 1177 
 1178    if(mode==RESET)
 1179    {  bitsleft=8;
 1180       blockpos=0;
 1181       nextbyte=block[0];
 1182       return(0);
 1183    }
 1184    else if(mode==NONE)
 1185    {  bitsleft=((n+7)>>3)<<3;                // Bits to get (next mult. of 8)  
 1186       while(bitsleft)
 1187       {  
 1188          bitsleft -= 8;
 1189          answer += nextbyte;
 1190          if(bitsleft) answer <<= 8;
 1191          blockpos++;        
 1192          if(blockpos >= blocksize) blockpos=0;
 1193          nextbyte = block[blockpos];  
 1194       }            
 1195    } 
 1196    else if(mode==GIF)do
 1197    {
 1198       n1 = min(min(8, need), bitsleft);
 1199       newno = bits(nextbyte, 7+n1-bitsleft, n1); // also right-shifts newno
 1200       newno <<= (n - need);
 1201       answer += newno;
 1202       bitsleft -= n1;
 1203       need -= n1;
 1204 
 1205       if(!bitsleft)
 1206       {   blockpos++;        
 1207           if(blockpos >= blocksize) blockpos=0;
 1208           nextbyte = block[blockpos];       // Get rest of bits from next byte
 1209           bitsleft = 8;
 1210       }
 1211       if(blockpos >= blocksize)
 1212       {   blockpos=0;
 1213           nextbyte = block[0];
 1214           bitsleft=8;
 1215       }
 1216 
 1217    } while(need);
 1218    else if(mode==TIF) do
 1219    {
 1220                                             // Nextbyte is the byte being used
 1221 
 1222       n1 = min(min(8, need), bitsleft);     // n1=No.of bits to take from byte
 1223 
 1224                                             // newno = Value obtained from the
 1225                                             //   n1 bits (right-shifted by the
 1226                                             //   function bits()).
 1227       newno = bits(nextbyte, bitsleft-1, n1); 
 1228       bitsleft -= n1;
 1229       need -= n1;
 1230       newno <<= need;
 1231       answer += newno;
 1232 
 1233       if(!bitsleft)
 1234       {   blockpos++;        
 1235           if(blockpos >= blocksize) 
 1236           {   blockpos=0;
 1237               nextbyte=0;
 1238           }else
 1239           {   nextbyte = block[blockpos];   // Get rest of bits from next byte
 1240           }
 1241           bitsleft = 8;
 1242       }
 1243       if(blockpos >= blocksize)
 1244       {   blockpos=0;
 1245           nextbyte=0;
 1246           bitsleft=8;
 1247       }
 1248 
 1249    } while(need);
 1250    else answer=0;
 1251 
 1252    return(answer);
 1253 }
 1254 
 1255 
 1256 //--------------------------------------------------------------------------//
 1257 // tif_value_at                                                             //
 1258 // Read value from a tiff file when the given tif_value is a pointer.       //
 1259 //--------------------------------------------------------------------------//
 1260 short int tif_value_at(unsigned int tif_pointer, int size, FILE* fp, int mac)
 1261 { 
 1262      int result=0;
 1263      int pos=0;
 1264      pos=ftell(fp);          
 1265      fseek(fp,g.tif_skipbytes+tif_pointer,SEEK_SET);             
 1266      tif_fread(&result,size,fp,mac,size);   
 1267      fseek(fp,pos,SEEK_SET);   /* jump back to where we were before*/     
 1268      return(result);
 1269 }
 1270 
 1271 
 1272 
 1273 //--------------------------------------------------------------------------//
 1274 // tif_fread                                                                //
 1275 // Read a value from a tiff file, taking into account mac Tif's             //
 1276 // For mac files, you also need to specify how many bytes to use, because   //
 1277 //  tags always read 4 bytes, but mac's may only use the 1st 2 or all 4.    //
 1278 //  Example:   1 128  0  0   =  384 (if tif_type==4)(4 byte)                //
 1279 //             0   0  0  3   =    3 (if tif_type==3)(2 byte)                //
 1280 //  (this only applies when reading the tif_value).                         //
 1281 // Maximum = 8 bytes.                                                       //
 1282 //--------------------------------------------------------------------------//
 1283 int tif_fread(char* a, int bytes, FILE* fp, int mac, int bytestouse)
 1284 {  mac=mac;                // keep compiler quiet
 1285    bytestouse=bytestouse;
 1286    fread(a,bytes,1,fp);
 1287 #ifndef LITTLE_ENDIAN
 1288    if(bytestouse!=0) swapbytes((uchar*)a, bytes, bytestouse);
 1289 #endif
 1290 
 1291    return bytes;
 1292 }
 1293 
 1294 int tif_fread(uchar* a, int bytes, FILE* fp, int mac, int bytestouse)
 1295 {  mac=mac;                // keep compiler quiet
 1296    bytestouse=bytestouse;
 1297    fread(a,bytes,1,fp);
 1298 #ifndef LITTLE_ENDIAN
 1299    if(bytestouse!=4 && bytestouse!=0) swapbytes(a, bytes, bytestouse);
 1300 #endif
 1301    return bytes;
 1302 }
 1303 
 1304 int tif_fread(short int* a, int bytes, FILE* fp, int mac, int bytestouse)
 1305 {  mac=mac; bytes=bytes; bytestouse=2;  // keep compiler quiet
 1306    if(bytestouse==3) return 0; //keep compiler quiet
 1307    short int k;  
 1308    k = getword(fp);
 1309    if(mac) k = (k>>8) + ((k&0xff)<<8);
 1310    *a = (short int)(k & 0xffff);
 1311    return bytes;
 1312 }
 1313 
 1314 int tif_fread(ushort *a, int bytes, FILE* fp, int mac, int bytestouse)
 1315 {  mac=mac; bytes=bytes; bytestouse=2;  // keep compiler quiet
 1316    if(bytestouse==3) return 0; //keep compiler quiet
 1317    ushort k;
 1318    k = getword(fp);
 1319    if(mac) k = (k>>8) + ((k&0xff)<<8);
 1320    *a = (ushort)k;
 1321    return bytes;
 1322 }
 1323 
 1324 int tif_fread(int* a, int bytes, FILE* fp, int mac, int bytestouse)
 1325 {  int k;
 1326    int answer;
 1327    uchar buf[8];
 1328    fread(buf,bytes,1,fp);
 1329    answer = 0;
 1330    if(mac)
 1331    {   
 1332       for(k=0;k<bytes;k++) 
 1333           answer += ((buf[bytestouse-1-k]) << (k<<3)); 
 1334    }   
 1335    else 
 1336    {  for(k=0;k<bytes;k++) answer += ((buf[k]) << (k<<3));  }
 1337    *a = answer;
 1338    return bytes;
 1339 }
 1340 
 1341 
 1342 //--------------------------------------------------------------------------//
 1343 // tif_getlineofpixels                                                      //
 1344 // Reads a line of pixels in the specified compression format.              //
 1345 // `length'    =  bytes per line                                            //
 1346 // `stripline' is a global = which line in the strip                        //
 1347 // `currentstrip'is a global = which strip                                  //
 1348 // Reads enough bytes for 1 horiz.line of pixels. Assumes a strip is an     //
 1349 // integral number of scan lines. Doesn't handle LZW (handled elsewhere).   //
 1350 //--------------------------------------------------------------------------//
 1351 void tif_getlineofpixels(FILE* fp, uchar* buffer, int length, int compression, 
 1352    int bpp, int mac, int rowsperstrip, int* tif_strip, int nooftiles)
 1353 {
 1354     int count=0, k, n, c;
 1355     if((nooftiles<=1)&&(stripline==0)) 
 1356         fseek(fp, g.tif_skipbytes+tif_strip[currentstrip], SEEK_SET);
 1357     switch(compression)
 1358     {   case 2:           // CCITT RLE
 1359              break;
 1360         case 5:           // LZW - handled elsewhere
 1361              break;
 1362         case 32773:       // PackBits   
 1363              do
 1364              {   tif_fread(&n,1,fp,mac,1);
 1365                  if(between(n,0,127))
 1366                  {   
 1367                      tif_fread((char*)(buffer+count),n+1,fp,mac,n+1);
 1368                      count += n+1;
 1369                  }    
 1370                  else if(n != -128)
 1371                  {   
 1372                      if(n>0) n=-256+n;
 1373                      tif_fread(&c,1,fp,mac,1);
 1374                      for(k=count;k<count+(-n+1);k++) *(buffer+k)=c;
 1375                      count += -n+1;
 1376                  }
 1377              }while(count<length);
 1378              break;
 1379         case 32901:       // SG RLE 16 bpp PackBits (untested)
 1380              do
 1381              {   tif_fread(&n,1,fp,mac,1);
 1382                  if(n>=0)
 1383                  {   if(bpp==8) 
 1384                      {  tif_fread((char*)(buffer+count),n+1,fp,mac,n+1);
 1385                         count += n+1;
 1386                      }else
 1387                      {  tif_fread((char*)(buffer+count),2*n+2,fp,mac,2*n+2);
 1388                         count += 2*n+2;
 1389                      }
 1390                  }    
 1391                  else if(n != -128)
 1392                  {   tif_fread(&c,1,fp,mac,1);
 1393                      if(bpp==8)
 1394                      {  for(k=count;k<count+(-n+1);k++) *(buffer+count)=c;
 1395                         count += -n+1;
 1396                      }else  
 1397                      {  for(k=count;k<count+(-2*n+2);k++) *(buffer+count)=c;
 1398                         count += -2*n+2;
 1399                      }   
 1400 
 1401                  }
 1402              }while(count<length);
 1403              break;
 1404         case 1:          // Swap bytes here if image quant (bytes are in wrong
 1405                          // order). 
 1406              tif_fread(buffer,length,fp,mac,g.off[bpp]);  
 1407              // if(image_quant && bpp==16) swapbytes(buffer,length,2);
 1408              break;
 1409         default:          // No compression or unknown
 1410              tif_fread(buffer,length,fp,mac,0);  
 1411              // if(image_quant && bpp==16) swapbytes(buffer,length,2);
 1412              break;
 1413     }
 1414     stripline++;
 1415     if(stripline==rowsperstrip) { stripline=0; currentstrip++; }
 1416     getbits(0,buffer,0,RESET);  //reset
 1417 }
 1418 
 1419 
 1420 //--------------------------------------------------------------------------//
 1421 // abouttiffile                                                             //
 1422 // Display information about tif file.                                      //
 1423 //--------------------------------------------------------------------------//
 1424 void abouttiffile(char *filename, int compressed)
 1425 {  
 1426    static char *listtitle;
 1427    static char **info;                                    
 1428    if(memorylessthan(16384)){  message(g.nomemory,ERROR); return; } 
 1429    FILE *fp;
 1430    char temp[256];
 1431    char label1[16]="rgb????????????";
 1432    char label2[16]="cmyk???????????";
 1433    int j,k;
 1434    int tif_sampperpixel=0;
 1435    int tif_colormap    =0;
 1436    int tif_value_bps   =1;
 1437    int tif_byteorder   =0;
 1438    int tif_version     =0;
 1439    int tif_noofdirectories=0;
 1440    int tif_offsettoIFD=0;
 1441    int tif_tag=0;
 1442    int tif_type=0;
 1443    int tif_start=0;
 1444    int tif_integer=0;  
 1445    int tif_integer2=0;  
 1446    int tif_photointerp=0;
 1447    int cbps[16],bps=1;        // Up to 16 colors with different bits/pixels
 1448    int mac=0;
 1449    int bytestouse = 4;
 1450    int bytes;
 1451    char junk;
 1452    int count=1;
 1453    char tif_string[1024];
 1454    int length;
 1455    int tif_length     =0;
 1456    int tif_value      =0;
 1457    if((fp=open_file(filename, compressed, TNI_READ, g.compression, g.decompression, 
 1458        g.compression_ext))==NULL) return ;
 1459                          //// Can't read tif file thru pipe so jump out.
 1460                          //// Some files are pipe-friendly but for others the
 1461                          //// only alternative is to create a temp file.
 1462                          //// This is too much trouble just to get information.
 1463    if(compressed)    
 1464    {   sprintf(temp, "TIF file compressed with\n%s",g.compression);
 1465        message(temp);
 1466        close_file(fp, compressed); 
 1467        return; 
 1468    }
 1469    
 1470    if(g.tif_skipbytes) for(k=0;k<g.tif_skipbytes;k++) fread(&junk,1,1,fp);
 1471 
 1472    fread(&tif_byteorder,2,1,fp);  // This must be the same in all Tif files
 1473    if(tif_byteorder==0x4d4d) mac=1; else mac=0;
 1474    tif_fread(&tif_version,2,fp,mac,2); 
 1475    tif_fread(&tif_offsettoIFD,4,fp,mac,4);
 1476 
 1477    fseek(fp, g.tif_skipbytes+tif_offsettoIFD, SEEK_SET);
 1478    tif_fread(&tif_noofdirectories,2,fp,mac,2);
 1479 
 1480    //-------------Put information in list box-------------------------//
 1481 
 1482    listtitle = new char[100];
 1483    strcpy(listtitle, "About the File");
 1484    int listcount=-1;
 1485    info = new char*[100];   // max. 100 lines - Change if you add more items
 1486 
 1487    info[++listcount] = new char[100];                       
 1488    sprintf(info[listcount],"Filename:  %s",basefilename(filename));
 1489 
 1490    info[++listcount] = new char[100];                       
 1491    sprintf(info[listcount],"File format: TIFF");
 1492 
 1493    info[++listcount] = new char[100];                       
 1494    if(tif_byteorder==0x4d4d) 
 1495    {   sprintf(info[listcount],"Byte order: big endian");
 1496        mac=1; 
 1497    }else
 1498    {   sprintf(info[listcount],"Byte order: little endian");
 1499        mac=0;
 1500    }
 1501 
 1502 
 1503 
 1504    info[++listcount] = new char[100];                       
 1505    if(mac) sprintf(info[listcount],"Macintosh TIFF file");
 1506    else    sprintf(info[listcount],"PC (Intel) TIFF file");
 1507 
 1508    info[++listcount] = new char[100];                       
 1509    sprintf(info[listcount],"TIFF version %d",tif_version);
 1510    
 1511    info[++listcount] = new char[100];                       
 1512    sprintf(info[listcount],"Offset to IFD  %d",tif_offsettoIFD);
 1513 
 1514    Tiftag t[100];
 1515    int tc=0;
 1516    for(k=1;k<=tif_noofdirectories;k++) 
 1517    {
 1518        tif_tag=0;
 1519        tif_fread(&tif_tag, 2, fp, mac, 2);   
 1520        tif_fread(&tif_type, 2, fp, mac, 2);  
 1521        tif_fread(&tif_length, 4, fp, mac, 4);
 1522        if(tif_type==1) bytestouse = 1;
 1523        if(tif_type==2) bytestouse = 1;
 1524        if(tif_type==3) bytestouse = 2;
 1525        if(tif_type==4) bytestouse = 4;
 1526        if(tif_type==5) bytestouse = 4;
 1527 
 1528        if(tif_length>1) bytestouse = 4;
 1529 
 1530        tif_fread(&tif_value, 4, fp, mac, bytestouse);    
 1531        if(bytestouse==1) tif_value &= 0xff;
 1532        if(bytestouse==2) tif_value &= 0xffff;
 1533 
 1534        ////  If tag is an offset, store in array so it can be sorted.
 1535        length=tif_length*bytestouse;
 1536        if((length>4)||(tif_type==5)) 
 1537        {   t[tc].tag    = tif_tag;
 1538            t[tc].value  = tif_value;
 1539            t[tc].length = tif_length;
 1540            t[tc].type   = tif_type;
 1541            tc++;
 1542        }
 1543            
 1544        info[++listcount] = new char[100];                       
 1545        if(listcount > 200) break;
 1546 
 1547        switch(tif_tag)
 1548        {     case 254: sprintf(info[listcount],"new subfile type %d",tif_value);break;
 1549              case 255: sprintf(info[listcount],"subfile type %d",tif_value);break;
 1550              case 256: sprintf(info[listcount],"image width  %d",tif_value);break;
 1551              case 257: sprintf(info[listcount],"image length %d",tif_value);break;
 1552              case 258: bps = tif_value;  // The meaning of this may
 1553                                          // change depending on the
 1554                                          // tif_sampperpixel, which could
 1555                                          // be read later.
 1556                        tif_value_bps = bps;
 1557                        if((tif_value_bps!=0) && ((tif_sampperpixel>1)||(tif_value_bps>32)) )
 1558                            sprintf(info[listcount],"bpp offset %d", bps);
 1559                        else
 1560                            sprintf(info[listcount],"bits/pixel %d", bps);
 1561                        break;
 1562              case 259: switch(tif_value)
 1563                        {  case 0:
 1564                           case 1    :strcpy(temp,"none");       break;
 1565                           case 2    :strcpy(temp,"CCITT RLE");  break;
 1566                           case 5    :strcpy(temp,"LZW");        break;
 1567                           case 6    :strcpy(temp,"JPEG");       break;
 1568                           case 32766:strcpy(temp,"2bit RLE/NeXT");break;
 1569                           case 32771:strcpy(temp,"CCITT/align");break;
 1570                           case 32773:strcpy(temp,"PackBits");   break;
 1571                           case 32809:strcpy(temp,"Thunderscan");break;
 1572                           case 32900:strcpy(temp,"Pixar RLE");  break;
 1573                           case 32901:strcpy(temp,"SGI RLE");    break;
 1574                           default: strcpy(temp,"other");
 1575                        }
 1576                        sprintf(info[listcount],"compression %s",temp);
 1577                        break;
 1578              case 262: switch(tif_value)
 1579                        {  case 0:  strcpy(temp,"B/W-gray");      break;
 1580                           case 1:  strcpy(temp,"Neg.B/W-gray");  break;
 1581                           case 2:  strcpy(temp,"RGB color");     break;
 1582                           case 3:  strcpy(temp,"Pal.color");     break;
 1583                           case 4:  strcpy(temp,"Transparency");  break;
 1584                           case 5:  strcpy(temp,"CMYK color");    break;
 1585                           default: strcpy(temp,"Other");         break;
 1586                        }
 1587                        tif_photointerp=tif_value;
 1588                        sprintf(info[listcount],"photo interp  %s",temp);break;
 1589              case 263: sprintf(info[listcount],"thresholding  %d",tif_value);break; 
 1590              case 266: sprintf(info[listcount],"fill order    %d ",tif_value);break;
 1591              case 269: sprintf(info[listcount],"document name offset %d",tif_value);break;               
 1592              case 270: sprintf(info[listcount],"image descrip.offset %d",tif_value);break;
 1593              case 271: sprintf(info[listcount],"make offset   %d  ",tif_value);break;
 1594              case 272: sprintf(info[listcount],"model offset  %d ",tif_value);break;
 1595              case 273: if(!tif_start)tif_start=tif_value;
 1596                        sprintf(info[listcount],"strip offsets %d",tif_value);break;
 1597              case 274: sprintf(info[listcount],"orientation   %d",tif_value);break;
 1598              case 277: tif_sampperpixel = tif_value;                         
 1599                        sprintf(info[listcount],"samples/pixel %d",tif_value);break;
 1600              case 278: sprintf(info[listcount],"rows/strip    %d",tif_value);break;
 1601              case 279: sprintf(info[listcount],"strip bytes   %d",tif_value);break;
 1602              case 280: sprintf(info[listcount],"min value     %d",tif_value);break;
 1603              case 281: sprintf(info[listcount],"max value     %d",tif_value);break;
 1604              case 282: sprintf(info[listcount],"x resolution  %d",tif_value);break;
 1605              case 283: sprintf(info[listcount],"y resolution  %d",tif_value);break;
 1606              case 284: sprintf(info[listcount],"image planes  %d",tif_value);break;
 1607              case 286: sprintf(info[listcount],"x position    %d",tif_value);break;
 1608              case 287: sprintf(info[listcount],"y position    %d",tif_value);break;
 1609              case 288: sprintf(info[listcount],"free offsets  %d",tif_value);break;                
 1610              case 289: sprintf(info[listcount],"free bytes    %d",tif_value);break;               
 1611              case 290: sprintf(info[listcount],"gray response %d",tif_value);break; 
 1612              case 291: sprintf(info[listcount],"gray resp.curve at %d",tif_value);break;
 1613              case 296: if(tif_value==1) strcpy(temp,"none");
 1614                        if(tif_value==2) strcpy(temp,"inches");
 1615                        if(tif_value==3) strcpy(temp,"centimeters");                     
 1616                        sprintf(info[listcount],"resolution unit %d  units %s",tif_value,temp);
 1617                        break;
 1618              case 301: sprintf(info[listcount],"color resp.curve %d",tif_value);break;
 1619              //case 305: sprintf(info[listcount],"software ");break;
 1620              case 306: sprintf(info[listcount],"date & time ");break;
 1621              case 315: sprintf(info[listcount],"artist"); break;
 1622              case 316: sprintf(info[listcount],"host computer");break;
 1623              case 317: sprintf(info[listcount],"predictor   %d",tif_value);break;
 1624              case 318: sprintf(info[listcount],"white point %d",tif_value);break;
 1625              case 319: sprintf(info[listcount],"Primary chromaticities %d",tif_value);
 1626              case 320: sprintf(info[listcount],"color map offset %d ",tif_value);
 1627                        tif_colormap     = tif_value;break;       
 1628              case 322: sprintf(info[listcount],"tile width   %d",tif_value);break;
 1629              case 323: sprintf(info[listcount],"tile length  %d",tif_value);break;
 1630              case 324: sprintf(info[listcount],"tile offsets %d",tif_value);break;
 1631              case 325: sprintf(info[listcount],"tile bytes   %d",tif_value);break;
 1632              case 338: sprintf(info[listcount],"extra samples %d",tif_value);break;
 1633              default: 
 1634                 if((unsigned)tif_tag>=32768)
 1635                       sprintf(info[listcount],"  (Unknown vendor-specific tag) %d",tif_value);
 1636                 else
 1637                       sprintf(info[listcount],"  value  %d",tif_value);
 1638        }
 1639      
 1640    }
 1641    qsort(t, tc, sizeof(Tiftag), tif_cmp);
 1642 
 1643    for(k=1;k<tc;k++) 
 1644    {
 1645        tif_tag = t[k].tag;
 1646        tif_length = t[k].length;
 1647        tif_value = t[k].value;
 1648        tif_type = t[k].type;
 1649        
 1650        length=tif_length*bytestouse;
 1651        if((length>4)||(tif_type==5)) /* read field pointed to by value*/
 1652        {    
 1653              // pos=ftell(fp);          
 1654              fseek(fp, g.tif_skipbytes+tif_value, SEEK_SET);             
 1655              switch(tif_type)
 1656              { case 1:      /* series of chars */  
 1657                   for(j=0;j<tif_length;j++)
 1658                   {  tif_integer=0;
 1659                      tif_fread(&tif_integer,1,fp,mac,1);
 1660                      // sprintf(info[listcount]," byte %d",tif_integer);    
 1661                   }
 1662                   break;
 1663                case 2:      /* string */
 1664                   bytes = min(100,tif_length);
 1665                   tif_fread(tif_string, bytes, fp, mac, bytes);
 1666                   info[++listcount] = new char[100];                       
 1667                   if(tif_tag==305) sprintf(info[listcount],"software %s",tif_string);
 1668                   else sprintf(info[listcount],"  %s",tif_string);           
 1669                   break;
 1670                case 3:      /* series of 2-byte integers */  
 1671                   info[++listcount] = new char[100];                       
 1672                   sprintf(info[listcount],"  No.of 2-byte ints %d",tif_length);
 1673                   for(j=0;j<tif_length;j++)
 1674                   {  tif_integer=0;
 1675                      tif_fread(&tif_integer,2,fp,mac,2);
 1676                      // sprintf(info[listcount]," int %d",tif_integer);    
 1677                   }
 1678                   break;
 1679                case 4:      /* series of 4-byte integers */  
 1680                   info[++listcount] = new char[100];                       
 1681                   if(tif_tag==273)
 1682                      sprintf(info[listcount],"  No.of strips  %d",tif_length);
 1683                   else
 1684                      sprintf(info[listcount],"  No.of 4-byte ints  %d",tif_length);
 1685                   tif_integer=0;
 1686                   for(j=0;j<tif_length;j++)
 1687                   {  tif_integer=0;
 1688                      tif_fread(&tif_integer,4,fp,mac,4);
 1689                      if((tif_tag==273)&&(j==0))
 1690                      {   tif_start=tif_integer;    
 1691                          info[++listcount] = new char[100];                       
 1692                          sprintf(info[listcount],"Image start %d",tif_start);                
 1693                      }
 1694                      if(tif_tag==273)      sprintf(info[listcount]," strip start %d",tif_integer);    
 1695                      else if(tif_tag==279) sprintf(info[listcount]," bytes/strip %d",tif_integer); 
 1696                      else                  sprintf(info[listcount]," int %d",tif_integer);    
 1697 
 1698                   }
 1699                   break;
 1700                case 5:      /* 2 4-byte integers */  
 1701                   tif_integer=0;
 1702                   tif_fread(&tif_integer,4,fp,mac,4);
 1703                   tif_fread(&tif_integer2,4,fp,mac,4);
 1704                   break;
 1705              } 
 1706        }
 1707      
 1708    }
 1709    if((tif_colormap)&&(tif_photointerp==3))
 1710    {   info[++listcount] = new char[100];                       
 1711        sprintf(info[listcount],"Palette present");
 1712    }
 1713 
 1714      // Now that we know the samples/pixel it is safe to guess at
 1715      // what bps means.
 1716      // Maybe it was bits/pixel or maybe it was pointer to a list of
 1717      // tif_sampperpixel bits/pixel's.
 1718 
 1719    info[++listcount] = new char[100];                       
 1720    sprintf(info[listcount],"tif_samp/pixel %d",tif_sampperpixel);
 1721 
 1722    if((tif_value_bps!=0) && ((tif_sampperpixel>1)||(tif_value_bps>32)) )
 1723    {  bps = 0;
 1724       for(k=0;k<tif_sampperpixel;k++)
 1725       {   cbps[k] = tif_value_at(tif_value_bps+k*2, 2, fp, mac);
 1726           strcpy(temp," x");
 1727           strcat(temp," bits/samp");
 1728           if(tif_photointerp==5) temp[1]=label2[k];
 1729           else temp[1]=label1[k];
 1730           info[++listcount] = new char[100];                       
 1731           sprintf(info[listcount],"%s %d",temp, cbps[k]);
 1732           bps += cbps[k];
 1733       }
 1734       info[++listcount] = new char[100];                       
 1735       sprintf(info[listcount],"Total bits/pixel %d", bps);
 1736    }
 1737 
 1738    tif_value=0;
 1739    tif_offsettoIFD=0;     
 1740    
 1741    tif_fread(&tif_offsettoIFD,4,fp,mac,4);
 1742    if(tif_offsettoIFD > 0)
 1743    {   count++;
 1744        info[++listcount] = new char[100];                       
 1745        sprintf(info[listcount],"Image number %d",count);
 1746        info[++listcount] = new char[100];                       
 1747        sprintf(info[listcount],"Offset to next IFD %d",tif_offsettoIFD);
 1748    }    
 1749    else
 1750    {   info[++listcount] = new char[100];                       
 1751        sprintf(info[listcount],"Image data start %d",tif_start);
 1752    }
 1753    close_file(fp, compressed);  
 1754 
 1755    ////-----------------done filling list---------------////
 1756 
 1757    static listinfo *l;
 1758    l = new listinfo;
 1759    l->title  = listtitle;
 1760    l->info   = info;
 1761    l->count  = listcount+1;
 1762    l->itemstoshow = min(20,listcount+1);
 1763    l->firstitem   = 0;
 1764    l->wantsort    = 0;
 1765    l->wantsave    = 0;
 1766    l->helptopic   = 1;
 1767    l->allowedit   = 0;
 1768    l->selection   = &g.crud;
 1769    l->width       = 0;
 1770    l->transient   = 1;
 1771    l->wantfunction = 0;
 1772    l->autoupdate   = 0;
 1773    l->deletebutton = 0;
 1774    l->clearbutton  = 0;
 1775    l->exportbutton = 0;
 1776    l->highest_erased = 0;
 1777    l->x = 0;
 1778    l->y = 0;
 1779    l->f1 = null;
 1780    l->f2 = null;
 1781    l->f3 = null;
 1782    l->f4 = delete_list;
 1783    l->f5 = null;
 1784    l->f6 = null;
 1785    l->listnumber = 0;
 1786    l->wc = 0;
 1787    list(l);
 1788 }
 1789 
 1790 
 1791 //--------------------------------------------------------------------------//
 1792 // tif_cmp - for qsort                                                      //
 1793 //--------------------------------------------------------------------------//
 1794 int tif_cmp(const void *p, const void *q)
 1795 {
 1796    return sgn( ((Tiftag*)p)->value - ((Tiftag*)q)->value);
 1797 }
 1798 
 1799 
 1800 //--------------------------------------------------------------------------//
 1801 // writetiffile  -  Returns 0 if successful, error number if unsuccessful   //
 1802 //   TIF class R                                                            //
 1803 //   The image offset is                                                    //
 1804 //        10 for header                                                     //
 1805 //      + 12*(no.of tags)  (==18 if B/W, 21 if color)                       //
 1806 //      + 4  for the 4 extra bytes after the list of tags.                  //
 1807 //      + 16 for the x-resolution & y-resolution (tags 282,283)             //
 1808 //      + 512 for gray response curve  (if want_color_type==1)              //
 1809 //      + 1536 for palette (if want_color_type==2)                          //
 1810 //   All int's are assumed to be 32 bits. Short int's are 16 bits.          //
 1811 //--------------------------------------------------------------------------//
 1812 int writetiffile(char *filename, int write_all, int compress)
 1813 {
 1814    if(memorylessthan(16384)){  message(g.nomemory,ERROR); return(NOMEM); } 
 1815    FILE *fp;
 1816    char softwarestring[15];
 1817    short int palettetemp, shortk;
 1818    int a, dbpp, count=0, frame, ino, j, k, oldxend, size=0, size1, size2,
 1819        status=OK, xstart, xend, y, ystart, yend, ui2=0, ui2tot=0;
 1820    uint value=0, xresptr=0, yresptr=0, bytecountptr=0, ui=0, uir, uig, uib;
 1821 
 1822    strcpy(softwarestring,"tnimage ");
 1823    strcat(softwarestring, g.version);
 1824    int* stripoffset;          // File offset for start of each strip
 1825    int* bytesperstrip=NULL;   // No.of bytes in each strip
 1826    uchar* bufr=NULL;
 1827    uchar* bufr2=NULL;
 1828 
 1829    double bppfac       = 1.0; // Desired bytes/pixel to save as
 1830    int intbppfac      = 1;    // bppfac rounded up to next integer   
 1831    int lengthinpixels = 0;
 1832    int widthinpixels  = 0;
 1833    int bytesperrow    = 0;
 1834    int photointerp    = 0;
 1835    int bpptag         = 0;
 1836    int bytecounttag   = 0;
 1837    int xrestag        = 0;
 1838    int yrestag        = 0;
 1839    int grayrestag     = 0;
 1840    int grayresptr     = 0;
 1841    int softwaretag    = 0;
 1842    int softwareptr    = 0;
 1843    int colormaptag    = 0; 
 1844    int colormapptr    = 0;
 1845    int tif_offset     = 0;
 1846    int bppptr         = 0;   // Pointer to file offset for bpp
 1847    int samplesperpixel= 0;   // No. of colors/pixel (1,3, or 4)
 1848    int rowsperstrip   = 4;   // Rows of pixels/strip
 1849    int noofstrips     = 0;   // Total no.of strips
 1850    int stripoffsettag = 0;   // Tag count when strip offset tag is written
 1851    int stripoffsetptr = 0;   // File offset of strip offset tag
 1852    int strip          = 0;   // Counter for strips
 1853    int totalbytes     = 0;   // Counter for no.of bytes of image data written
 1854    int bytesperimage  = 0;   // Total no.of bytes in the image
 1855    int round_bpp      = 8*((7+g.want_bpp)/8);  // want_bpp rounded up to next 8
 1856    int rr,gg,bb,kk=0;
 1857    int shiftamount    = 0;
 1858    int evenbits;
 1859    int mbpp           = g.bitsperpixel; 
 1860    int alloc1=0;
 1861    int alloc2=0;
 1862    int alloc3=0;
 1863    int alloc4=0;
 1864    int alloc5=0;
 1865 
 1866    char header[8] = { 0x49,0x49,0x2a,0x00,0x08,0x00,0x00,0x00 }; 
 1867    char zero[4]   = { 0x00,0x00,0x00,0x00 };
 1868    short int RGBbpp[8];
 1869 
 1870    RGBbpp[0] = g.want_redbpp;
 1871    RGBbpp[1] = g.want_greenbpp;
 1872    RGBbpp[2] = g.want_bluebpp;
 1873    RGBbpp[3] = g.want_blackbpp;
 1874 
 1875    if(write_all==1)
 1876    {  xstart = z[ci].xpos;
 1877       ystart = z[ci].ypos;
 1878       xend   = xstart + z[ci].xsize-1;
 1879       yend   = ystart + z[ci].ysize-1;
 1880    }
 1881    else
 1882    {  xstart = g.selected_ulx;
 1883       xend   = g.selected_lrx;
 1884       ystart = g.selected_uly;
 1885       yend   = g.selected_lry;
 1886    }
 1887 
 1888    oldxend = xend;
 1889    frame = z[ci].cf;
 1890 
 1891    if((fp=open_file(filename, compress, TNI_WRITE, g.compression, g.decompression, 
 1892        g.compression_ext))==NULL) 
 1893        return CANTCREATEFILE;
 1894 
 1895    //----Fill tiff_header with image information---------------------//  
 1896  
 1897    lengthinpixels = yend-ystart+1;
 1898    widthinpixels  = xend-xstart+1;
 1899 
 1900    //---Increase so it is multiple of 8 (scan lines must start on----//
 1901    //---a byte boundary).                                        ----//
 1902 
 1903    evenbits = ((widthinpixels*g.want_bpp+7)/8)*8; 
 1904    while(widthinpixels*g.want_bpp < evenbits) 
 1905    {   widthinpixels++;
 1906        xend++;
 1907    }
 1908   
 1909    noofstrips = max(1,(lengthinpixels+rowsperstrip-1)/rowsperstrip);
 1910 
 1911    //------color information-----------------------------------------//
 1912 
 1913    ////  If entire image is being saved, get bytes using the original  
 1914    ////  bpp of the image. Otherwise, use the screen bpp.             
 1915    ////  Pixel values will be converted into want_bpp bits/pixel.       
 1916 
 1917    if(write_all) mbpp=z[ci].bpp;
 1918    else mbpp = g.bitsperpixel;
 1919 
 1920    switch(g.want_bpp)
 1921    {  case 1:  bppfac=1.0;  break;
 1922       case 8:  bppfac=1.0;  break;
 1923       case 15: bppfac=1.875;break;
 1924       case 16: bppfac=2.0;  break;
 1925       case 24: bppfac=3.0;  break;
 1926       case 32: bppfac=4.0;  break;
 1927       case 48: bppfac=6.0;  break;
 1928       default: bppfac=g.want_bpp/8.0; break;
 1929    }  
 1930    intbppfac = ((7+g.want_bpp)/8);
 1931 
 1932    ////  Determine Tif parameters - samples/pixel, photointerp, etc.  
 1933    ////  Samples/pixel is the highest color, even if intermediate ones  
 1934    ////   have 0 bits/pixel.                                        
 1935    
 1936    bytesperrow    = (int)(widthinpixels * bppfac);
 1937    samplesperpixel = g.want_noofcolors;
 1938    if(g.usegrayscale) photointerp = 0;           //
 1939                else photointerp = 2;             // RGB color
 1940 
 1941    switch(g.want_color_type)
 1942    {   case 0:                                   // monochrome
 1943              g.want_noofcolors = 1;
 1944              bytesperrow    = widthinpixels/8;
 1945              photointerp    = 1;
 1946              samplesperpixel= 1;
 1947              message("Saving as monochrome");
 1948              break;
 1949        case 1:   
 1950              photointerp    = 1;                 // 8 bpp grayscale
 1951              samplesperpixel= 1;
 1952              break;
 1953        case 2:   
 1954              photointerp    = 3;                 // 8 bpp palette
 1955              samplesperpixel= 1;
 1956              break;
 1957        case 3:   break;                          // 15 bpp
 1958        case 4:                                   // 16 bpp
 1959        case 5:                                   // 24 bpp
 1960              if(g.want_noofcolors==1)
 1961              {  if(g.want_bpp==8) photointerp = 3; else photointerp = 1;
 1962              }
 1963              break;                        
 1964        case 6:
 1965              samplesperpixel = 4;                // 32 bpp
 1966              if(g.save_cmyk) photointerp=5;      // cmyk 
 1967              break;             
 1968        case 7:                                   // 48 bpp
 1969              samplesperpixel = 3;
 1970              break;
 1971        case 8:                                   // custom
 1972              // For case #8, want_noofcolors, want_redbpp, want_bluebpp,
 1973              // and want_greenbpp must be previously set. 
 1974              // If want_noofcolors is 1, they are ignored.
 1975              // If want_noofcolors >1, want_noofcolors must equal the 
 1976              //    no.of colors with non-zero bpp.
 1977 
 1978              if(g.want_noofcolors==1)
 1979              {  if(g.want_bpp==8) photointerp = 3; else photointerp = 1;
 1980              }
 1981              if((g.save_cmyk)&&(samplesperpixel==4)) photointerp=5;  // cmyk 
 1982              break;
 1983    }
 1984    bytesperimage  = bytesperrow*lengthinpixels;
 1985 
 1986    //-------arrays---------------------------------------------------//
 1987 
 1988    stripoffset   = new int[noofstrips];
 1989    if(stripoffset==NULL){ message(g.nomemory,ERROR); goto wtifend;}
 1990    alloc1=1;
 1991 
 1992    bytesperstrip = new int[noofstrips];
 1993    if(bytesperstrip==NULL){ message(g.nomemory,ERROR); goto wtifend;}
 1994    alloc2=1;
 1995 
 1996    size1         = rowsperstrip*(int)(intbppfac*widthinpixels)+10;
 1997    size2         = rowsperstrip*(int)(g.off[mbpp]*widthinpixels)+10;
 1998    size          = max(size1,size2);
 1999    bufr          = new uchar[size];
 2000      if(bufr==NULL){ message(g.nomemory,ERROR); goto wtifend;}
 2001      alloc3=1;
 2002    bufr2         = new uchar[size];
 2003      if(bufr2==NULL){ message(g.nomemory,ERROR); goto wtifend;}
 2004      alloc4=1;
 2005    tag           = new taginfo[256];                // Max. of 256 tags
 2006      if(tag==NULL){ message(g.nomemory,ERROR); goto wtifend;}
 2007      alloc5=1;
 2008    bufr[size-1]=99;                    // Sentinel value
 2009    bufr2[size-1]=99;                   // Sentinel value
 2010 
 2011    ////  tags are 12 bytes each            
 2012    ////  * denotes a pointer to file offset   
 2013 
 2014    totaltags=0;                        // A global (incremented by nexttag()) 
 2015 
 2016    //       Tag ID no.
 2017    //       Type(1=byte,2=string,3=16bit int,4=32bit int,5=2 32bit ints)
 2018    //       Count (no. of values)
 2019    //       Value
 2020    nexttag(255,3,1,1);                 // Subfile type - for compatibility
 2021    nexttag(256,4,1,widthinpixels);     // image width
 2022    nexttag(257,4,1,lengthinpixels);    // image length
 2023    
 2024    bpptag = totaltags;                 // fill in bpp ptr later if RGB                                   
 2025    nexttag(258,3,samplesperpixel,g.want_bpp); //*list of bits/sample for all 3 colors 
 2026 
 2027    nexttag(259,3,1,1);                 // compression (none)
 2028    nexttag(262,3,1,photointerp);       // photometric interp
 2029    nexttag(266,3,1,1);                 // fill order (1)
 2030 
 2031    stripoffsettag = totaltags;         // fill in actual stripoffsettag later                                       
 2032    nexttag(273,4,noofstrips,stripoffsetptr);   //*ptr to array of strip offsets
 2033    
 2034    nexttag(274,3,1,1);                 // orientation (1)
 2035    nexttag(277,3,1,samplesperpixel);   // samples/pixel(no.of color channels)
 2036    nexttag(278,4,1,rowsperstrip);      // rows/strip   
 2037 
 2038    bytecounttag = totaltags;           // fill in actual bytecountptr later                                       
 2039    nexttag(279,4,noofstrips,bytecountptr); //*pointer to strip byte count list   
 2040 
 2041    xrestag = totaltags;                // fill in actual xresptr later
 2042    nexttag(282,5,1,xresptr);           //*pointer to x resolution 
 2043 
 2044    yrestag = totaltags;                // fill in actual yresptr later
 2045    nexttag(283,5,1,yresptr);           //*pointer to y resolution
 2046 
 2047    nexttag(284,3,1,1);                 // planar config (1)
 2048                                        // Gray scale or palette color
 2049    if((g.want_color_type==1)||(g.want_color_type==2))
 2050    {  nexttag(290,3,1,3);              // gray response unit (set to 3)
 2051       grayrestag = totaltags;          //*fill in actual grayresptr later
 2052       nexttag(291,3,256,grayresptr);   // gray resp.curve- 512 bytes because short
 2053    }                                   
 2054    nexttag(296,3,1,2);                 // resolution unit 2=inches   
 2055    softwaretag = totaltags;            // fill in actual pointer later
 2056                                        //*pointer to software tag 
 2057    nexttag(305,2,sizeof(softwarestring),softwareptr);    
 2058    if(photointerp==3)                  // Palette color
 2059    {  colormaptag = totaltags;         //*fill in actual colormapptr later
 2060       nexttag(320,3,768,colormapptr);  // color map=1536 bytes because short int
 2061    }
 2062     
 2063    ////  Total no.of tags is now known, so we can calculate offsets.   
 2064    ////  This will finish inserting the data in the tag fields.        
 2065    ////  The data pointed to by these tags will have to be written in  
 2066    ////  the same order as it appears below to preserve the pointers.  
 2067 
 2068    tif_offset   = 10 + 12 * totaltags + 4;
 2069    xresptr = tif_offset;               // Finish tag 282 ptr to xres 
 2070    tag[xrestag].value = xresptr;  
 2071    tif_offset += 8;
 2072 
 2073    yresptr = tif_offset;               // Finish tag 283 ptr to yres
 2074    tag[yrestag].value = yresptr;
 2075    tif_offset += 8;
 2076                                        // Finish tag 291 - Gray response ptr
 2077    if((g.want_color_type==1)||(g.want_color_type==2))
 2078    {   grayresptr = tif_offset;
 2079        tag[grayrestag].value = grayresptr;
 2080        tif_offset += 512;
 2081    }
 2082    if(photointerp==3)                  // Finish tag 320 - Palette ptr
 2083    {   colormapptr = tif_offset;
 2084        tag[colormaptag].value = colormapptr;
 2085        tif_offset += 1536;             // Spec says short int not byte!
 2086    }     
 2087    if(g.want_noofcolors>1)             // Finish tag 258 ptr to RGB bpp list
 2088    {   bppptr = tif_offset;
 2089        tag[bpptag].value = bppptr;
 2090        tif_offset += 2*samplesperpixel;
 2091    }
 2092    
 2093    softwareptr = tif_offset;           // Finish Tag 305 ptr to software ID
 2094    tag[softwaretag].value = softwareptr;
 2095    tif_offset += sizeof(softwarestring);
 2096 
 2097    bytecountptr = tif_offset;          // Finish Tag 279 ptr to byte counts
 2098    if(noofstrips>1)                    // If more than 1 strip, 279 is a ptr
 2099    {  tag[bytecounttag].value = bytecountptr;
 2100       ui = bytesperimage;              // ui is bytes remaining in image
 2101                                        // Calculate bytes/strip
 2102       for(k=0;k<noofstrips;k++)          
 2103       {  bytesperstrip[k] = min((int)ui, rowsperstrip * bytesperrow); 
 2104          ui -= bytesperstrip[k];
 2105          tif_offset += 4;
 2106       }
 2107    }else                               // If only 1 strip, 279 is image size,    
 2108    {                                   // stored in the `value' part of the
 2109                                        // tag, so nothing is added here.
 2110      tag[bytecounttag].value = bytesperimage;
 2111      bytesperstrip[0]=bytesperimage;   // This makes it easier to handle
 2112                                        // but bytesperstrip[0] does not get
 2113                                        // written if there is only 1 strip
 2114    }
 2115   
 2116    //---This one must be last in case there is only 1 strip so the---//
 2117    //---image data offset will be correct.                        ---//
 2118 
 2119    if(noofstrips>1)                    // Finish Tag 273 strip offsets
 2120    {                                   // If more than 1 strip, 273 is a ptr
 2121                                        // to a list of strip offsets
 2122        stripoffsetptr = tif_offset;    // Finish Tag 273 - strip offsets
 2123        tag[stripoffsettag].value = stripoffsetptr;
 2124        for(k=0;k<noofstrips;k++)
 2125        {  stripoffset[k]= stripoffsetptr + 4*noofstrips + totalbytes;
 2126           totalbytes += bytesperstrip[k];
 2127           tif_offset += 4;
 2128        }
 2129    }else                               // If only 1 strip, 273 is starting  
 2130    {                                   // offset of all image data (stored
 2131                                        // in `value' part of the tag).
 2132        tag[stripoffsettag].value = tif_offset;
 2133        stripoffset[0] = tif_offset;
 2134    }
 2135    
 2136    ////  End of tags - start writing to disk.      
 2137    ////  Must be in the same order as above.   
 2138 
 2139    fwrite(header,8,1,fp);              // 8 bytes = header + 1st IFD offset
 2140    putword(totaltags,fp);              // 2 bytes = total no.of tags         
 2141    for(k=0;k<totaltags;k++) 
 2142       puttag(tag[k],fp);               // 12 bytes for each tag
 2143    fwrite(zero,4,1,fp);                // 4 zero's
 2144 
 2145                                        //-----End of IFD's-----------//
 2146 
 2147    k=300; putdword(k,fp);              // x resolution
 2148    k=1;   putdword(k,fp);
 2149    k=300; putdword(k,fp);              // y resolution
 2150    k=1;   putdword(k,fp);
 2151                                        // Gray response gamma curve
 2152    if((g.want_color_type==1)||(g.want_color_type==2))
 2153    { 
 2154       if(write_all==1)  
 2155       {
 2156          for(k=0;k<256;k++){ shortk=z[ci].gamma[k]; putword(shortk,fp); }
 2157       }else
 2158       {
 2159          for(k=0;k<256;k++){ shortk=k; putword(shortk,fp); }
 2160       }
 2161    }
 2162    if(photointerp==3)                  // Palette (color map)
 2163    {  
 2164       for(j=0;j<256;j++)
 2165       {  palettetemp = (short)(g.palette[j].red*1024);
 2166          putword(palettetemp,fp);
 2167       }
 2168       for(j=0;j<256;j++)
 2169       {  palettetemp = (short)(g.palette[j].green*1024);
 2170          putword(palettetemp,fp);
 2171       }
 2172       for(j=0;j<256;j++)
 2173       {  palettetemp = (short)(g.palette[j].blue*1024);
 2174          putword(palettetemp,fp);
 2175       }
 2176    }
 2177    
 2178    ////  R,G,B bits/pixel as a list of 3 or 4 short ints,
 2179    ////  only if there are 2 or more samples/pixel.        
 2180 
 2181    if(g.want_noofcolors>1)
 2182    {   for(k=0;k<samplesperpixel;k++)
 2183             putword(RGBbpp[k],fp);
 2184    }
 2185    fwrite(softwarestring,sizeof(softwarestring),1,fp);
 2186 
 2187    ////  If only 1 strip, its offset is stored in the 12-byte field.    
 2188    ////  Otherwise, store a pointer to here, and write the offsets here.
 2189          
 2190    if(noofstrips>1)
 2191    {   for(k=0;k<noofstrips;k++) putdword(bytesperstrip[k],fp);
 2192        for(k=0;k<noofstrips;k++) putdword(stripoffset[k],fp);
 2193    }
 2194 
 2195    //  End of writing information - Start writing image              
 2196    //  The first part handles special cases such as cmyk, custom     
 2197    //  bits/pixel, or 15 bpp mode. No temporary image is created.    
 2198    //  No color quantization is done.                                
 2199 
 2200 
 2201    shiftamount = max(0,g.want_bpp-g.want_redbpp-g.want_greenbpp-g.want_bluebpp);
 2202 
 2203    if( ((g.want_color_type==8)||
 2204         (g.want_color_type==3)||
 2205         (g.save_cmyk)         ||
 2206         (mbpp!=g.want_bpp && g.want_bpp!=48)    ||
 2207         (g.usegrayscale))     && (g.want_color_type>0) ) 
 2208    {  
 2209       count = 0;
 2210       for(strip=0; strip<noofstrips; strip++)      
 2211       { y = ystart + strip * rowsperstrip;  
 2212         ui=0;
 2213         ui2=0;
 2214         ui2tot=0;
 2215         dbpp  = mbpp-g.want_bpp;
 2216         for(j=y;j<=min(y+rowsperstrip-1,yend);j++)
 2217         {  getbits(0,bufr,0,RESET);  //reset bits at each scan line
 2218            for(k=xstart;k<=xend;k++)
 2219            {    if(write_all)
 2220                   value = pixelat(z[ci].image[frame][j-ystart] + 
 2221                         g.off[mbpp]*(k-xstart), mbpp);
 2222                 else
 2223                   value = readpixelonimage(k,j,mbpp,ino);
 2224                 if(k>oldxend) value=0;               
 2225                 if(g.want_noofcolors > 1)
 2226                 {  
 2227                    valuetoRGB(value,rr,gg,bb,mbpp);
 2228                    value = 0;                   
 2229                    if(g.save_cmyk && g.want_noofcolors==4) // convert to cmyk
 2230                    {   kk = min(g.maxred[mbpp]-rr, min(g.maxgreen[mbpp]-gg,
 2231                                 g.maxblue[mbpp]-bb));
 2232                        rr  = g.maxred[mbpp]  -rr-kk;       // r is now cyan
 2233                        gg  = g.maxgreen[mbpp]-gg-kk;       // g is now magenta
 2234                        bb  = g.maxblue[mbpp] -bb-kk;       // b is now yellow
 2235                        kk  = max(0,min(g.maxred[mbpp] ,kk));
 2236                        rr  = max(0,min(g.maxred[mbpp] , rr));
 2237                        gg  = max(0,min(g.maxgreen[mbpp],gg));
 2238                        bb  = max(0,min(g.maxblue[mbpp], bb));
 2239                    }
 2240                    dbpp = g.want_redbpp - g.redbpp[mbpp];
 2241                    if(dbpp>0) rr <<= ( dbpp);
 2242                    if(dbpp<0) rr >>= (-dbpp);
 2243                    value += rr << (g.want_greenbpp + g.want_bluebpp);
 2244 
 2245                    dbpp = g.want_greenbpp - g.greenbpp[mbpp];    
 2246                    if(dbpp>0) gg <<= ( dbpp);
 2247                    if(dbpp<0) gg >>= (-dbpp);
 2248                    value += gg << g.want_bluebpp;
 2249 
 2250                    dbpp = g.want_bluebpp - g.bluebpp[mbpp]; 
 2251                    if(dbpp>0) bb <<= ( dbpp);
 2252                    if(dbpp<0) bb >>= (-dbpp);
 2253                    value += bb;
 2254 
 2255                    if(g.want_noofcolors==4)
 2256                    { 
 2257                      value <<= g.want_blackbpp;                 
 2258                      if(g.save_cmyk)                     
 2259                      {  dbpp = g.want_blackbpp - g.redbpp[mbpp];                  
 2260                         if(dbpp>0) kk <<= ( dbpp);
 2261                         if(dbpp<0) kk >>= (-dbpp);
 2262 
 2263                         value = 0;                   
 2264                         value += kk << (g.want_redbpp + g.want_greenbpp + g.want_bluebpp);
 2265                         value += bb << (g.want_redbpp + g.want_greenbpp);
 2266                         value += gg << g.want_redbpp;
 2267                         value += rr;
 2268                      }   
 2269                    }
 2270                 } 
 2271                 else if(g.usegrayscale)   
 2272                 {
 2273                        // For treating the data as a deep monochrome image,
 2274                        // value is already the same as luminosity.
 2275                   dbpp = g.want_bpp - mbpp;
 2276                   if(dbpp>0) value <<= ( dbpp);
 2277                   if(dbpp<0) value >>= (-dbpp);// Shift to desired bpp
 2278                 }else
 2279                 {      // Image is rgb but want 1 color - must reduce 
 2280                        // rgb to luminosity.
 2281                     valuetoRGB(value,rr,gg,bb,mbpp);
 2282                     uir=rr;uig=gg;uib=bb;
 2283                     value = 0;
 2284                     dbpp = 30-g.redbpp[mbpp];    // Shift r,g,b to 0..2^^32
 2285                     if(dbpp>0) uir <<= ( dbpp);// (30 bits for max. precision)
 2286                     if(dbpp<0) uir >>= (-dbpp);
 2287                     dbpp = 30-g.greenbpp[mbpp];
 2288                     if(dbpp>0) uig <<= ( dbpp);
 2289                     if(dbpp<0) uig >>= (-dbpp);
 2290                     dbpp = 30-g.bluebpp[mbpp];
 2291                     if(dbpp>0) uib <<= ( dbpp);
 2292                     if(dbpp<0) uib >>= (-dbpp);
 2293                                                // Convert to luminosity
 2294                     value = (uint)(g.luminr*uir + g.luming*uig + g.luminb*uib);
 2295                     dbpp = 30-g.want_bpp;
 2296                     if(dbpp>0) value >>= ( dbpp);
 2297                     if(dbpp<0) value <<= (-dbpp);// Shift back to desired scale
 2298                 }
 2299                 putpixelbytes(bufr2+ui2,value,1,round_bpp,1);
 2300                 ui2 += intbppfac;
 2301            }   
 2302         
 2303            // ui2 counts input bytes, ui counts output (packed) bytes.
 2304            // They are not necessarily the same value.
 2305 
 2306            a = packbits(g.want_bpp, bufr2+ui2tot, bufr+ui, intbppfac*widthinpixels); 
 2307            ui += a;
 2308            ui2tot += intbppfac*(xend-xstart+1);
 2309 
 2310         }       
 2311         count = fwrite(bufr,bytesperstrip[strip],1,fp);
 2312       }  
 2313    }
 2314 
 2315    // This section handles 48 bits/pixel RGB
 2316 
 2317    else if(g.want_color_type==7)       
 2318    {  
 2319       for(strip=0; strip<noofstrips; strip++)
 2320       {   y = ystart + strip * rowsperstrip;  
 2321           ui=0;
 2322           for(j=y; j<=min(y+rowsperstrip-1,yend); j++)
 2323           { 
 2324              if(write_all)      
 2325              {  for(k=0;k<bytesperrow;k+=g.off[mbpp])
 2326                 {   RGBat(z[ci].image[frame][j-ystart]+k, mbpp, rr, gg, bb);
 2327                     setRGBbytes(bufr+ui, rr, gg, bb, 48);
 2328                     ui += intbppfac;
 2329                 }  
 2330              }else 
 2331              {
 2332                 for(k=xstart; k<=xend; k++)
 2333                 {   readRGBonimage(k,j,mbpp,ino,rr,gg,bb,-2);
 2334                     convertRGBpixel(rr,gg,bb,mbpp,g.want_bpp);
 2335                     setRGBbytes(bufr+ui, rr, gg, bb, 48);
 2336                     ui = (uint)((double)ui + bppfac);
 2337                 } 
 2338              }
 2339           }       
 2340           count = fwrite(bufr,bytesperstrip[strip],1,fp);
 2341       }  
 2342    }
 2343 
 2344 
 2345    // This section handles palette, grayscale, or RGB color.         
 2346    // The want_bpp to save image must be same as mbpp in memory.     
 2347 
 2348    else if(g.want_color_type>0)       
 2349    {  
 2350       for(strip=0;strip<noofstrips;strip++)
 2351       { y = ystart + strip * rowsperstrip;  
 2352         ui=0;
 2353         for(j=y;j<=min(y+rowsperstrip-1,yend);j++)
 2354         { 
 2355            if(write_all)      
 2356            { for(k=0;k<bytesperrow;k+=g.off[mbpp])
 2357              {  value = pixelat(z[ci].image[frame][j-ystart]+k,mbpp);
 2358                 if(samplesperpixel==4) value<<=shiftamount;
 2359                 putpixelbytes(bufr+ui,value,1,mbpp,-1);
 2360                 ui+=intbppfac;
 2361              }  
 2362            }else 
 2363            { for(k=xstart;k<=xend;k++)
 2364              {  if(g.want_color_type == g.colortype)
 2365                 {   value = readpixelonimage(k,j,mbpp,ino);
 2366                     value = convertpixel(value,mbpp,g.want_bpp,1-g.usegrayscale);
 2367                     if(samplesperpixel==4) value<<=shiftamount;                 
 2368                     putpixelbytes(bufr+ui,value,1,g.want_bpp,-1);
 2369                 }    
 2370                 ui = (uint)((double)ui + bppfac);
 2371              } 
 2372            }
 2373         }       
 2374         count = fwrite(bufr,bytesperstrip[strip],1,fp);
 2375       }  
 2376    }
 2377    
 2378    // This section handles monochrome mode only. No temporary image  
 2379    // is needed.                                                     
 2380    
 2381    else if(g.want_color_type == 0)   
 2382    {  
 2383       for(strip=0;strip<noofstrips;strip++)
 2384       { y = ystart + strip * rowsperstrip;  
 2385         ui=0;
 2386         for(j=y;j<min(y+rowsperstrip,yend);j++)
 2387              for(k=xstart;k<xend;k+=8) 
 2388                  bufr[ui++]=readbyte(k,j);
 2389         count = fwrite(bufr,bytesperstrip[strip],1,fp);
 2390       } 
 2391    }    
 2392    
 2393 wtifend:
 2394    close_file(fp, compress);
 2395    if(count!=1){ status=UNKNOWN; message("Disk error!",ERROR);}
 2396    if(bufr[size-1]!=99)message ("Internal err - bufr",ERROR);
 2397    if(bufr2[size-1]!=99)message("Internal err - bufr2",ERROR);
 2398    if(alloc1) delete[] stripoffset;
 2399    if(alloc2) delete[] bytesperstrip;
 2400    if(alloc3) delete[] bufr;
 2401    if(alloc4) delete[] bufr2;
 2402    if(alloc5) delete[] tag;
 2403    return(status); 
 2404 }
 2405 
 2406 
 2407 //--------------------------------------------------------------------------//
 2408 // nexttag                                                                  //
 2409 // Puts tag data in tag struct. (used by writetiffile)                      //
 2410 //--------------------------------------------------------------------------//
 2411 void nexttag(short int tagid, short int type,int length,int value)   
 2412 {                           
 2413    tag[totaltags].id    = tagid;
 2414    tag[totaltags].ttype = type;
 2415    tag[totaltags].count = length;
 2416    tag[totaltags].value = value;
 2417    totaltags++;
 2418    if(totaltags>99) message("Internal error at nexttag",ERROR);
 2419 }
 2420 
 2421 
 2422