home *** CD-ROM | disk | FTP | other *** search
/ Programming Tool Box / SIMS_2.iso / vb_tools / manythng / gif.c < prev    next >
C/C++ Source or Header  |  1994-07-28  |  24KB  |  1,032 lines

  1. /* $change:Code cleanup, minor fixes.$ */
  2. /*
  3. **    $id: ssvcid gif.c 1.0 08/03/92 10:01 am$
  4. **        Read a Compuserve GIF file into a DIB.
  5. **
  6. **    (C) 1992-1993    Larry Widing
  7. */
  8. #define NOCOMM
  9. #define NOKANJI
  10. #include <windows.h>
  11. #include <stdio.h>
  12. #include <string.h>
  13. #include    <malloc.h>
  14. #include    "bitmaps.h"
  15.  
  16. #define    SEG_CBUF        01
  17. #define    FASTCALLS    01
  18. #define    GET_BYTES    01
  19. #define    PAL_SHIFT    0
  20.  
  21. /*
  22. **    Local functions
  23. */
  24. static short NEAR    decoder(short linewidth);
  25. static short        init_exp(short  size);
  26. static short NEAR    get_next_code(void);
  27. static void            inittable(void);
  28. static void            close_file(void);
  29.  
  30. /*
  31. **    Local variables
  32. */
  33. static int                        rowcount;        /* row counter for screen */
  34. static int                        hin = NULL;
  35. static unsigned int            height;
  36.  
  37. static unsigned char            dacbox[256][3];            /* Video-DAC (filled in by SETVIDEO) */
  38.  
  39. static unsigned char            decoderline[2049];        /* write-line routines use this */
  40. static unsigned char            win_andmask[8];
  41. static unsigned char            win_notmask[8];
  42. static unsigned char            win_bitshift[8];
  43.  
  44. static int                        xdots, ydots, colors;
  45. static int                        win_xdots, win_ydots;
  46. static unsigned char huge    *pixels;                     /* the device-independent bitmap pixels */
  47. static int                        pixels_per_byte;        /* pixels/byte in the pixmap */
  48. static long                        pixels_per_bytem1;        /* pixels / byte - 1 (for ANDing) */
  49. static int                        pixelshift_per_byte;    /* 0, 1, 2, or 3 */
  50. static int                        bytes_per_pixelline;    /* pixels/line / pixels/byte */
  51. static long                        win_bitmapsize;            /* bitmap size, in bytes */
  52. static int                        bad_code_count = 0;        /* needed by decoder module */
  53. #if    SEG_CBUF
  54. static BYTE _seg                *cbuf = NULL;
  55. static unsigned int            gbuf = 0;
  56. #else
  57. static BYTE FAR                *cbuf = NULL;
  58. static BYTE FAR                *gbuf = NULL;
  59. #endif
  60. static HANDLE                    hcbuf = NULL;
  61. static unsigned int            gbn = 0;
  62.  
  63. #define    cbufsize    (32u * 1024u)        // (16u * 1024u)
  64.  
  65. static int NEAR
  66. get_byte(void)
  67. {
  68.     if (gbn == 0)
  69.     {
  70.         gbn = _lread(hin,cbuf,cbufsize);
  71. #if    SEG_CBUF
  72.         gbuf = 0;
  73. #else
  74.         gbuf = NULL;
  75. #endif
  76.     }
  77.  
  78.     if (gbn)
  79.     {
  80.         --gbn;
  81. #if    SEG_CBUF
  82.         return (cbuf[gbuf++]) & 0x00ff;
  83. #else
  84.         return (*gbuf++) & 0x00ff;
  85. #endif
  86.     }
  87.     else
  88.         return (-1);
  89. }
  90.  
  91. #if    GET_BYTES
  92. static int NEAR 
  93. get_bytes(unsigned int count, char *dest)
  94. {
  95.     int    count2 = count;
  96.  
  97.     if (count <= 0)
  98.     {
  99.         return count;
  100.     }
  101.  
  102.     while (count)
  103.     {
  104.         if (gbn == 0)
  105.         {
  106.             gbn = _lread(hin,cbuf,cbufsize);
  107. #if    SEG_CBUF
  108.             gbuf = NULL;
  109. #else
  110.             gbuf = cbuf;
  111. #endif
  112.  
  113.             if (!gbn)
  114.                 return -1;
  115.         }
  116.  
  117.         if (gbn >= count)
  118.         {
  119.             if (dest != NULL)
  120.             {
  121. #if    SEG_CBUF
  122.                 memcpy(dest, cbuf + gbuf, count);
  123. #else
  124.                 memcpy(dest, gbuf, count);
  125. #endif
  126.             }
  127.             gbuf += count;
  128.             gbn -= count;
  129.             count = 0;
  130.         }
  131.         else
  132.         {
  133.             if (dest != NULL)
  134.             {
  135. #if    SEG_CBUF
  136.                 memcpy(dest, cbuf + gbuf, gbn);
  137. #else
  138.                 memcpy(dest, gbuf, gbn);
  139. #endif
  140.             }
  141.             count -= gbn;
  142.             dest += gbn;
  143.             gbn = 0;
  144.         }
  145.     }
  146.  
  147.     return count2;
  148. }
  149. #endif
  150.  
  151. static void NEAR 
  152. putcolor(int x, int y, int color)
  153. {
  154.     long i;
  155.  
  156.     i = win_ydots - 1 - y;
  157.     i = (i * win_xdots) + x;
  158.  
  159.     if (x >= 0 && x < xdots && y >= 0 && y < ydots)
  160.     {
  161.         if (pixelshift_per_byte == 0)
  162.         {
  163.             pixels[i] = color % colors;
  164.         }
  165.         else
  166.         {
  167.             unsigned int j;
  168.  
  169.             j = i & (unsigned int)pixels_per_bytem1;
  170.             i = i >> pixelshift_per_byte;
  171.             pixels[i] = (pixels[i] & win_notmask[j]) + 
  172.                  (((unsigned char) (color % colors)) << win_bitshift[j]);
  173.         }
  174.     }
  175. }
  176.  
  177. static int NEAR 
  178. put_line(int rownum, int leftpt, int rightpt, unsigned char *localvalues)
  179. {
  180.     int    i, len;
  181.     long    startloc;
  182.  
  183.     len = rightpt - leftpt;
  184.     if (rightpt >= xdots)
  185.     {
  186.         len = xdots - leftpt;
  187.     }
  188.     startloc = win_ydots - 1 - rownum;
  189.     startloc = (startloc * win_xdots) + leftpt;
  190.  
  191.     if (rownum < 0 || rownum >= ydots || leftpt < 0)
  192.     {
  193.         return (0);
  194.     }
  195.  
  196.     if (pixelshift_per_byte == 0)
  197.     {
  198.         /*
  199.         **    Done this way because _fmemcpy() does not handle HUGE pointers
  200.         **    that can wrap over a selector/segment boundry.
  201.         */
  202.         unsigned char huge    *ptr = pixels + startloc;
  203.  
  204.         if (HIWORD(ptr) != HIWORD(ptr + len))
  205.         {
  206.             char    *src = (char *)localvalues;
  207.  
  208.             while (len--)
  209.                 *ptr++ = *src++;
  210.         }
  211.         else
  212.         {
  213.             _fmemcpy(ptr, localvalues, len);
  214.         }
  215.     }
  216.     else
  217.     {
  218.         unsigned int    j;
  219.         long                k;
  220.  
  221.         for (i = 0 ;  i <= len ;  i++)
  222.         {
  223.             k = startloc + i;
  224.             j = k & (unsigned int)pixels_per_bytem1;
  225.             k = k >> pixelshift_per_byte;
  226.             pixels[k] = (pixels[k] & win_notmask[j]) + 
  227.                  (((unsigned char) (localvalues[i] % colors)) << win_bitshift[j]);
  228.         }
  229.     }
  230.     putcolor(leftpt, rownum, localvalues[0]);
  231.  
  232.     return (1);
  233. }
  234.  
  235. static int NEAR 
  236. out_line(unsigned char *localvalues, int numberofdots)
  237. {
  238.     return (put_line(rowcount++, 0, numberofdots, localvalues));
  239. }
  240.  
  241.  
  242. /*
  243. **    Main entry decoder
  244. */
  245.  
  246. HDIB
  247. ReadGifFile(const char FAR *filename)
  248. {
  249.     HDIB                        dib = (HANDLE)NULL, hbiCurrent;
  250.     unsigned                    numcolors;
  251.     unsigned char            buffer[16];
  252.     unsigned                    width, finished;
  253.     LPBITMAPINFOHEADER    lpbi;
  254.     RGBQUAD FAR                *pRgb;
  255.     int                        status = 0;
  256.     int                        i, j, planes;
  257.     DWORD                        dwBits, dwLen;
  258.    OFSTRUCT                    of;
  259.  
  260.    /* initialize the row count for write-lines */
  261.     rowcount = 0;
  262.  
  263.    /* zero out the full write-line */
  264.     for (width = 0 ;  width < 2049 ;  width++)
  265.         decoderline[width] = 0;
  266.  
  267.    /* Open the file -- changed to OpenFile by mh */
  268.    hin = OpenFile ((LPSTR)filename, (LPOFSTRUCT)&of, OF_READ);
  269.     if (hin == -1)
  270.     {
  271.         return FALSE;
  272.     }
  273.  
  274.     hcbuf = GlobalAlloc(GHND,cbufsize);
  275.     cbuf = (BYTE FAR *)GlobalLock(hcbuf);
  276.     if (cbuf == NULL)
  277.     {
  278.         close_file();
  279.         return FALSE;
  280.     }
  281.     gbn = 0;
  282. #if    SEG_CBUF
  283.     gbuf = 0;
  284. #else
  285.     gbuf = NULL;
  286. #endif
  287.  
  288.    /* Get the screen description */
  289.     for (i = 0 ; i < 13 ; i++)
  290.     {
  291.         buffer[i] = (unsigned char) status = get_byte();
  292.         if (status < 0)
  293.         {
  294.             close_file();
  295.             return FALSE;
  296.         }
  297.     }
  298.  
  299.     if (strncmp((char *)buffer, "GIF87a", 3) ||     /* use updated GIF specs */
  300.          buffer[3] < '0' || buffer[3] > '9' || 
  301.          buffer[4] < '0' || buffer[4] > '9' || 
  302.          buffer[5] < 'A' || buffer[5] > 'z')
  303.     {
  304.         close_file();
  305.         return FALSE;
  306.     }
  307.  
  308.     planes = (buffer[10] & 0xF) + 1;
  309.  
  310.     if ((buffer[10] & 0x80) == 0)    /* color map (better be!) */
  311.     {
  312.         close_file();
  313.         return FALSE;
  314.     }
  315.     numcolors = 1 << planes;
  316.  
  317. #if    GET_BYTES
  318.     if (numcolors * 3 == get_bytes(numcolors * 3, dacbox))
  319.     {
  320. #if    PAL_SHIFT
  321.         for (i = 0 ; i < numcolors ; ++i)
  322.         {
  323.             for (j = 0 ; j < 3 ; ++j)
  324.             {
  325.                 dacbox[i][j] >>= 2;
  326.             }
  327.         }
  328. #endif
  329.     }
  330.     else
  331.     {
  332.         close_file();
  333.         return FALSE;
  334.     }
  335. #else
  336.     for (i = 0 ;  i < numcolors ;  i++)
  337.     {
  338.         for (j = 0 ;  j < 3 ;  j++)
  339.         {
  340.             status = get_byte();
  341.             if (status < 0)
  342.             {
  343.                 close_file();
  344.                 return FALSE;
  345.             }
  346.  
  347.             dacbox[i][j] = (status & 0x00ff) >> 2;
  348.         }
  349.     }
  350. #endif
  351.  
  352.    /* Now display one or more GIF objects */
  353.     finished = 0;
  354.     while (!finished)
  355.     {
  356.         switch (get_byte())
  357.         {
  358.             case ';':                /* End of the GIF dataset */
  359.                 finished = 1;
  360.                 status = 0;
  361.                 break;
  362.  
  363.             case '!':                /* GIF Extension Block */
  364.                 get_byte();        /* read (and ignore) the ID */
  365.                 while ((i = get_byte()) > 0)    /* get the data length */
  366. #if    GET_BYTES
  367.                     get_bytes(i, NULL);
  368. #else
  369.                     for (j = 0;  j < i;  j++)
  370.                         get_byte();    /* flush the data */
  371. #endif
  372.                 break;
  373.  
  374.             case ',':
  375.                  /*
  376.                    * Start of an image object. Read the image description.
  377.                    */
  378.  
  379. #if    GET_BYTES
  380.                 if (9 != get_bytes(9, buffer))
  381.                 {
  382.                     status = -1;
  383.                 }
  384.                 else
  385.                 {
  386.                     status = 0;
  387.                 }
  388. #else
  389.                 for (i = 0;  i < 9;  i++)
  390.                 {
  391.                     buffer[i] = (unsigned char) status = get_byte();
  392.                     if (status < 0)
  393.                     {
  394.                         status = -1;
  395.                         break;
  396.                     }
  397.                 }
  398. #endif
  399.                 if (status < 0)
  400.                 {
  401.                     finished = 1;
  402.                     break;
  403.                 }
  404.  
  405.                 width = buffer[4] | (buffer[5] << 8);
  406.                 height = buffer[6] | (buffer[7] << 8);
  407.                 // fill in DIB stuff
  408.                 xdots = width;
  409.                 ydots = height;
  410.                 colors = numcolors;
  411.                 if (colors > 16)
  412.                     colors = 256;
  413.                 if (colors > 2 && colors < 16)
  414.                     colors = 16;
  415.                 win_xdots = (xdots + 3) & 0xFFFC;
  416.                 win_ydots = ydots;
  417.                 pixelshift_per_byte = 0;
  418.                 pixels_per_byte = 1;
  419.                 pixels_per_bytem1 = 0;
  420.                 if (colors == 16)
  421.                 {
  422.                     win_xdots = (xdots + 7) & 0xFFF8;
  423.                     pixelshift_per_byte = 1;
  424.                     pixels_per_byte = 2;
  425.                     pixels_per_bytem1 = 1;
  426.                     win_andmask[0] = 0xF0;
  427.                     win_notmask[0] = 0xF;
  428.                     win_bitshift[0] = 4;
  429.                     win_andmask[1] = 0xF;
  430.                     win_notmask[1] = 0xF0;
  431.                     win_bitshift[1] = 0;
  432.                 }
  433.                 if (colors == 2)
  434.                 {
  435.                     win_xdots = (xdots + 31) & 0xFFE0;
  436.                     pixelshift_per_byte = 3;
  437.                     pixels_per_byte = 8;
  438.                     pixels_per_bytem1 = 7;
  439.                     win_andmask[0] = 0x80;
  440.                     win_notmask[0] = 0x7F;
  441.                     win_bitshift[0] = 7;
  442.                     for (i = 1 ;  i < 8 ;  i++)
  443.                     {
  444.                         win_andmask[i] = win_andmask[i - 1] >> 1;
  445.                         win_notmask[i] = (win_notmask[i - 1] >> 1) + 0x80;
  446.                         win_bitshift[i] = win_bitshift[i - 1] - 1;
  447.                     }
  448.                 }
  449.                 bytes_per_pixelline = win_xdots >> pixelshift_per_byte;
  450.  
  451.                 hbiCurrent = GlobalAlloc(GHND, (LONG) sizeof(BITMAPINFOHEADER) + 
  452.                      colors * sizeof(RGBQUAD));
  453.                 if (!hbiCurrent)
  454.                     return 0;
  455.  
  456.                 lpbi = (VOID FAR *) GlobalLock(hbiCurrent);
  457.                 lpbi->biSize = sizeof(BITMAPINFOHEADER);
  458.                 lpbi->biWidth = width;
  459.                 lpbi->biHeight = height;
  460.                 lpbi->biPlanes = 1;    //nb: NOT equal to planes from GIF
  461.                 lpbi->biBitCount = 8 / pixels_per_byte;
  462.                 lpbi->biCompression = BI_RGB;
  463.                 dwBits = 
  464.                      lpbi->biSizeImage = (DWORD) bytes_per_pixelline * win_ydots;
  465.                 lpbi->biXPelsPerMeter = 0;
  466.                 lpbi->biYPelsPerMeter = 0;
  467.                 lpbi->biClrUsed = colors;
  468.                 lpbi->biClrImportant = colors;
  469.  
  470.                 win_bitmapsize = (((long) win_xdots * (long) win_ydots) >> pixelshift_per_byte) + 1;
  471.  
  472.                     /* fill in intensities for all palette entry colors */
  473.  
  474.                 pRgb = (RGBQUAD FAR *) ((LPSTR) lpbi + (unsigned int)lpbi->biSize);
  475.                 for (i = 0;  i < colors;  i++)
  476.                 {
  477. #if    PAL_SHIFT
  478.                     pRgb[i].rgbRed = ((BYTE) dacbox[i][0]) << 2;
  479.                     pRgb[i].rgbGreen = ((BYTE) dacbox[i][1]) << 2;
  480.                     pRgb[i].rgbBlue = ((BYTE) dacbox[i][2]) << 2;
  481. #else
  482.                     pRgb[i].rgbRed = ((BYTE) dacbox[i][0]);
  483.                     pRgb[i].rgbGreen = ((BYTE) dacbox[i][1]);
  484.                     pRgb[i].rgbBlue = ((BYTE) dacbox[i][2]);
  485. #endif
  486.                 }
  487.  
  488.                 dwLen = lpbi->biSize + (DWORD) colors * sizeof(RGBQUAD) + dwBits;
  489.                 dib = GlobalAlloc(GHND, dwLen);
  490.                 if (!dib)
  491.                 {
  492.                     finished = 1;
  493.                     status = -1;
  494.                     break;
  495.                 }
  496.                 pixels = (unsigned char huge *) GlobalLock(dib);
  497.                 _fmemcpy(pixels, lpbi, (size_t) (dwLen - dwBits));
  498.                 GlobalUnlock(hbiCurrent);
  499.                 GlobalFree(hbiCurrent);
  500.                 pixels += dwLen - dwBits;
  501.  
  502.                 decoder(width);    //this does the grunt work
  503.  
  504.                 GlobalUnlock(dib);
  505.  
  506.                 status = 0;
  507.                 finished = 1;
  508.                 break;
  509.  
  510.             default:
  511.                 status = -1;
  512.                 finished = 1;
  513.                 break;
  514.         }
  515.     }
  516.  
  517.     close_file();
  518.  
  519.     return (status == 0) ? dib : 0;
  520. }
  521.  
  522. static void
  523. close_file()
  524. {
  525.     _lclose(hin);  
  526.     hin = NULL;
  527.     if (hcbuf)
  528.     {
  529.         GlobalUnlock(hcbuf);
  530.         GlobalFree(hcbuf);
  531.         cbuf = NULL;
  532.         hcbuf = NULL;
  533.     }
  534. }
  535.  
  536.  
  537. /* DECODE.C - An LZW decoder for GIF
  538.  * Copyright (C) 1987, by Steven A. Bennett
  539.  *
  540.  * Permission is given by the author to freely redistribute and include
  541.  * this code in any program as long as this credit is given where due.
  542.  *
  543.  * In accordance with the above, I want to credit Steve Wilhite who wrote
  544.  * the code which this is heavily inspired by...
  545.  *
  546.  * GIF and 'Graphics Interchange Format' are trademarks (tm) of
  547.  * Compuserve, Incorporated, an H&R Block Company.
  548.  *
  549.  * Release Notes: This file contains a decoder routine for GIF images
  550.  * which is similar, structurally, to the original routine by Steve Wilhite.
  551.  * It is, however, somewhat noticably faster in most cases.
  552.  *
  553.  == This routine was modified for use in FRACTINT in two ways.
  554.  ==
  555.  == 1) The original #includes were folded into the routine strictly to hold
  556.  ==    down the number of files we were dealing with.
  557.  ==
  558.  == 2) The 'stack', 'suffix', 'prefix', and 'buf' arrays were changed from
  559.  ==    static and 'malloc()'ed to external only so that the assembler
  560.  ==    program could use the same array space for several independent
  561.  ==    chunks of code.    Also, 'stack' was renamed to 'dstack' for TASM
  562.  ==    compatibility.
  563.  ==
  564.  == 3) The 'out_line()' external function has been changed to reference
  565.  ==    '*outln()' for flexibility (in particular, 3D transformations)
  566.  ==
  567.  == 4) A call to 'keypressed()' has been added after the 'outln()' calls
  568.  ==    to check for the presenc of a key-press as a bail-out signal
  569.  ==
  570.  == (Bert Tyler and Timothy Wegner)
  571.  */
  572. #define LOCAL static
  573. #define IMPORT extern
  574.  
  575. #define FAST register
  576.  
  577. typedef unsigned short UWORD;
  578. typedef char TEXT;
  579. typedef unsigned char UTINY;
  580. typedef unsigned long ULONG;
  581. typedef int INT;
  582.  
  583.  
  584. /* Various error codes used by decoder
  585.  * and my own routines...   It's okay
  586.  * for you to define whatever you want,
  587.  * as long as it's negative...  It will be
  588.  * returned intact up the various subroutine
  589.  * levels...
  590.  */
  591. #define OUT_OF_MEMORY -10
  592. #define BAD_CODE_SIZE -20
  593. #define READ_ERROR -1
  594. #define WRITE_ERROR -2
  595. #define OPEN_ERROR -3
  596. #define CREATE_ERROR -4
  597.  
  598.  
  599.  
  600. /* whups, here are more globals, added by PB: */
  601. static INT skipxdots; /* 0 to get every dot, 1 for every 2nd, 2 every 3rd, ... */
  602. static INT skipydots; /* ditto for rows */
  603.  
  604. #define MAX_CODES   4095
  605.  
  606. /* Static variables */
  607. LOCAL short curr_size;              /* The current code size */
  608. LOCAL short clear;              /* Value for a clear code */
  609. LOCAL short ending;              /* Value for a ending code */
  610. LOCAL short newcodes;              /* First available code */
  611. LOCAL short top_slot;              /* Highest code for current size */
  612. LOCAL short slot;              /* Last read code */
  613.  
  614. /* The following static variables are used
  615.  * for seperating out codes
  616.  */
  617. LOCAL short navail_bytes = 0;          /* # bytes left in block */
  618. LOCAL short nbits_left = 0;          /* # bits left in current byte */
  619. LOCAL UTINY b1;               /* Current byte */
  620. LOCAL UTINY byte_buff[257];          /* Current block, reuse shared mem */
  621. LOCAL UTINY *pbytes;              /* Pointer to next byte in block */
  622.  
  623. LOCAL LONG code_mask[13] = {
  624.      0,
  625.      0x0001, 0x0003,
  626.      0x0007, 0x000F,
  627.      0x001F, 0x003F,
  628.      0x007F, 0x00FF,
  629.      0x01FF, 0x03FF,
  630.      0x07FF, 0x0FFF
  631.      };
  632.  
  633.  
  634. /* This function initializes the decoder for reading a new image.
  635.  */
  636.  
  637. LOCAL short
  638. init_exp(short size)
  639. {
  640.     curr_size = size + 1;
  641.     top_slot = 1 << curr_size;
  642.     clear = 1 << size;
  643.     ending = clear + 1;
  644.     slot = newcodes = ending + 1;
  645.     navail_bytes = nbits_left = 0;
  646.  
  647.     return (0);
  648. }
  649.  
  650. #define    GET_BLOCK    01
  651.  
  652. #if    GET_BLOCK
  653. static int NEAR
  654. get_block(void)
  655. {
  656.     register int    count;
  657.     register    char    *dest = byte_buff;
  658.  
  659.     count = get_byte();
  660.     if (count < 0)
  661.     {
  662.         return count;
  663.     }
  664.     navail_bytes = count;
  665.  
  666.     while (count)
  667.     {
  668.         if (gbn == 0)
  669.         {
  670.             gbn = _lread(hin,cbuf,cbufsize);
  671. #if    SEG_CBUF
  672.             gbuf = NULL;
  673. #else
  674.             gbuf = cbuf;
  675. #endif
  676.  
  677.             if (!gbn)
  678.                 return -1;
  679.         }
  680.  
  681.         if (gbn >= count)
  682.         {
  683. #if    SEG_CBUF
  684.             memcpy(dest, cbuf + gbuf, count);
  685. #else
  686.             memcpy(dest, gbuf, count);
  687. #endif
  688.             gbuf += count;
  689.             gbn -= count;
  690.             count = 0;
  691.         }
  692.         else
  693.         {
  694. #if    SEG_CBUF
  695.             memcpy(dest, cbuf + gbuf, gbn);
  696. #else
  697.             memcpy(dest, gbuf, gbn);
  698. #endif
  699.             count -= gbn;
  700.             dest += gbn;
  701.             gbn = 0;
  702.         }
  703.     }
  704.  
  705.     return navail_bytes;
  706. }
  707. #endif
  708.  
  709. /* get_next_code()
  710.  * - gets the next code from the GIF file.  Returns the code, or else
  711.  * a negative number in case of file errors...
  712.  */
  713.  
  714. LOCAL short NEAR
  715. get_next_code(void)
  716. {
  717.     short    i, x;
  718.     ULONG    ret;
  719.  
  720.     if (nbits_left == 0)
  721.     {
  722.         if (navail_bytes <= 0)
  723.         {
  724.              /*
  725.             **    Out of bytes in current block, so read next block
  726.               */
  727.             pbytes = byte_buff;
  728. #if GET_BLOCK
  729.             if ((navail_bytes = get_block()) < 0)
  730.                 return (navail_bytes);
  731. #else
  732.             if ((navail_bytes = get_byte()) < 0)
  733.                 return (navail_bytes);
  734.             else if (navail_bytes)
  735.             {
  736.                 for (i = 0 ; i < navail_bytes ; ++i)
  737.                 {
  738.                     if ((x = get_byte()) < 0)
  739.                         return (x);
  740.                     byte_buff[i] = x;
  741.                 }
  742.             }
  743. #endif
  744.         }
  745.         b1 = *pbytes++;
  746.         nbits_left = 8;
  747.         --navail_bytes;
  748.     }
  749.  
  750.     ret = b1 >> (8 - nbits_left);
  751.     while (curr_size > nbits_left)
  752.     {
  753.         if (navail_bytes <= 0)
  754.         {
  755.              /*
  756.             **    Out of bytes in current block, so read next block
  757.               */
  758.             pbytes = byte_buff;
  759. #if    GET_BLOCK
  760.             if ((navail_bytes = get_block()) < 0)
  761.                 return (navail_bytes);
  762. #else
  763.             if ((navail_bytes = get_byte()) < 0)
  764.                 return (navail_bytes);
  765.             else if (navail_bytes)
  766.             {
  767.                 for (i = 0 ; i < navail_bytes ; ++i)
  768.                 {
  769.                     if ((x = get_byte()) < 0)
  770.                         return (x);
  771.                     byte_buff[i] = x;
  772.                 }
  773.             }
  774. #endif
  775.         }
  776.         b1 = *pbytes++;
  777.         ret |= b1 << nbits_left;
  778.         nbits_left += 8;
  779.         --navail_bytes;
  780.     }
  781.     nbits_left -= curr_size;
  782.     ret &= code_mask[curr_size];
  783.     return ((short) (ret));
  784. }
  785.  
  786.  
  787. /* The reason we have these seperated like this instead of using
  788.  * a structure like the original Wilhite code did, is because this
  789.  * stuff generally produces significantly faster code when compiled...
  790.  * This code is full of similar speedups...  (For a good book on writing
  791.  * C for speed or for space optomisation, see Efficient C by Tom Plum,
  792.  * published by Plum-Hall Associates...)
  793.  */
  794.  
  795. #define    NEAR_STACK    01
  796. #define    ALLOC_STACK    0
  797.  
  798. #if    !ALLOC_STACK    /* Moved into decoder() - lw */
  799. /*
  800. I removed the LOCAL identifiers in the arrays below and replaced them
  801. with 'extern's so as to declare (and re-use) the space elsewhere.
  802. The arrays are actually declared in the assembler source.
  803.                         Bert Tyler
  804.  
  805. I put them back -- m heller
  806. */
  807.  
  808. LOCAL UTINY dstack[MAX_CODES + 1];          /* Stack for storing pixels */
  809. LOCAL UTINY suffix[MAX_CODES + 1];          /* Suffix table */
  810. LOCAL UWORD prefix[MAX_CODES + 1];          /* Prefix linked list */
  811. #endif
  812.  
  813. /* short decoder(linewidth)
  814.  *    short linewidth;            * Pixels per line of image *
  815.  *
  816.  * - This function decodes an LZW image, according to the method used
  817.  * in the GIF spec.  Every *linewidth* "characters" (ie. pixels) decoded
  818.  * will generate a call to out_line(), which is a user specific function
  819.  * to display a line of pixels.  The function gets its codes from
  820.  * get_next_code() which is responsible for reading blocks of data and
  821.  * seperating them into the proper size codes.    Finally, get_byte() is
  822.  * the global routine to read the next byte from the GIF file.
  823.  *
  824.  * It is generally a good idea to have linewidth correspond to the actual
  825.  * width of a line (as specified in the Image header) to make your own
  826.  * code a bit simpler, but it isn't absolutely necessary.
  827.  *
  828.  * Returns: 0 if successful, else negative.  (See ERRS.H)
  829.  *
  830.  */
  831.  
  832. static short NEAR
  833. decoder(short linewidth)
  834. {
  835. #if    NEAR_STACK
  836.     FAST UTINY    _ds *sp;
  837.     FAST UTINY    _ds *bufptr;
  838.     UTINY            _ds *buf;
  839. #else
  840.     FAST UTINY    *sp;
  841.     FAST UTINY    *bufptr;
  842.     UTINY            *buf;
  843. #endif
  844.     FAST short    code, fc, oc, bufcnt;
  845.     short            c, size, ret;
  846.     short            xskip, yskip;
  847. #if    ALLOC_STACK
  848.     UTINY            *dstack;          /* Stack for storing pixels */
  849.     UTINY            *suffix;          /* Suffix table */
  850.     UWORD            *prefix;          /* Prefix linked list */
  851. #endif
  852.  
  853.    /* Initialize for decoding a new image...
  854.     */
  855.     if ((size = get_byte()) < 0)
  856.         return (size);
  857.     if (size < 2 || 9 < size)
  858.         return (BAD_CODE_SIZE);
  859.     init_exp(size);
  860.     xskip = yskip = 0;
  861.  
  862. #if    ALLOC_STACK
  863.     /*
  864.     **    Allocate space for tables and stack
  865.     */
  866.     dstack = (UTINY *)malloc((2 * sizeof(UTINY) + sizeof(UWORD)) * (MAX_CODES + 1));
  867.     suffix = (UTINY *)(((char *)dstack) + sizeof(UTINY) * (MAX_CODES + 1));
  868.     prefix = (UWORD *)(((char *)suffix) + sizeof(UTINY) * (MAX_CODES + 1));
  869. #endif
  870.  
  871.    /* Initialize in case they forgot to put in a clear code.
  872.     * (This shouldn't happen, but we'll try and decode it anyway...)
  873.     */
  874.     oc = fc = 0;
  875.  
  876.     buf = decoderline;
  877.  
  878.    /* Set up the stack pointer and decode buffer pointer
  879.     */
  880.     sp = dstack;
  881.     bufptr = buf;
  882.     bufcnt = linewidth;
  883.  
  884.    /* This is the main loop.  For each code we get we pass through the
  885.     * linked list of prefix codes, pushing the corresponding "character" for
  886.     * each code onto the stack.  When the list reaches a single "character"
  887.     * we push that on the stack too, and then start unstacking each
  888.     * character for output in the correct order.  Special handling is
  889.     * included for the clear code, and the whole thing ends when we get
  890.     * an ending code.
  891.     */
  892.  
  893.     while ((c = get_next_code()) != ending)
  894.     {
  895.  
  896.       /* If we had a file error, return without completing the decode
  897.        */
  898.         if (c < 0)
  899.         {
  900. #if    ALLOC_STACK
  901.             free(dstack);
  902. #endif
  903.             return (0);
  904.         }
  905.  
  906.       /* If the code is a clear code, reinitialize all necessary items.
  907.        */
  908.         if (c == clear)
  909.         {
  910.             curr_size = size + 1;
  911.             slot = newcodes;
  912.             top_slot = 1 << curr_size;
  913.  
  914.      /* Continue reading codes until we get a non-clear code
  915.       * (Another unlikely, but possible case...)
  916.       */
  917.             while ((c = get_next_code()) == clear)
  918.                 ;
  919.  
  920.      /* If we get an ending code immediately after a clear code
  921.       * (Yet another unlikely case), then break out of the loop.
  922.       */
  923.             if (c == ending)
  924.                 break;
  925.  
  926.      /* Finally, if the code is beyond the range of already set codes,
  927.       * (This one had better NOT happen...    I have no idea what will
  928.       * result from this, but I doubt it will look good...) then set it
  929.       * to color zero.
  930.       */
  931.             if (c >= slot)
  932.                 c = 0;
  933.  
  934.             oc = fc = c;
  935.  
  936.      /* And let us not forget to put the char into the buffer... */
  937.             *sp++ = c;        /* let the common code outside the if else stuff it */
  938.         }
  939.         else 
  940.         {
  941.  
  942.      /* In this case, it's not a clear code or an ending code, so
  943.       * it must be a code code...  So we can now decode the code into
  944.       * a stack of character codes. (Clear as mud, right?)
  945.       */
  946.             code = c;
  947.  
  948.      /* Here we go again with one of those off chances...  If, on the
  949.       * off chance, the code we got is beyond the range of those already
  950.       * set up (Another thing which had better NOT happen...) we trick
  951.       * the decoder into thinking it actually got the last code read.
  952.       * (Hmmn... I'm not sure why this works...  But it does...)
  953.       */
  954.             if (code >= slot)
  955.             {
  956.                 if (code > slot)
  957.                     ++bad_code_count;
  958.                 code = oc;
  959.                 *sp++ = fc;
  960.             }
  961.  
  962.      /* Here we scan back along the linked list of prefixes, pushing
  963.       * helpless characters (ie. suffixes) onto the stack as we do so.
  964.       */
  965.             while (code >= newcodes)
  966.             {
  967.                 *sp++ = suffix[code];
  968.                 code = prefix[code];
  969.             }
  970.  
  971.      /* Push the last character on the stack, and set up the new
  972.       * prefix and suffix, and if the required slot number is greater
  973.       * than that allowed by the current bit size, increase the bit
  974.       * size.  (NOTE - If we are all full, we *don't* save the new
  975.       * suffix and prefix...  I'm not certain if this is correct...
  976.       * it might be more proper to overwrite the last code...
  977.       */
  978.             *sp++ = code;
  979.             if (slot < top_slot)
  980.             {
  981.                 suffix[slot] = fc = code;
  982.                 prefix[slot++] = oc;
  983.                 oc = c;
  984.             }
  985.             if (slot >= top_slot)
  986.                 if (curr_size < 12)
  987.                 {
  988.                     top_slot <<= 1;
  989.                     ++curr_size;
  990.                 }
  991.         }
  992.  
  993.       /* Now that we've pushed the decoded string (in reverse order)
  994.        * onto the stack, lets pop it off and put it into our decode
  995.        * buffer...  And when the decode buffer is full, write another
  996.        * line...
  997.        */
  998.         while (sp > dstack)
  999.         {
  1000.             --sp;
  1001.             if (--xskip < 0)
  1002.             {
  1003.                 xskip = skipxdots;
  1004.                 *bufptr++ = *sp;
  1005.             }
  1006.             if (--bufcnt == 0)    /* finished an input row? */
  1007.             {
  1008.                 if (--yskip < 0)
  1009.                 {
  1010. //                    if ((ret = (*outln)(buf, bufptr - buf)) < 0)
  1011. //                    if ((ret = out_line(buf, bufptr - buf)) < 0)
  1012.                     if ((ret = put_line(rowcount++, 0, bufptr - buf, buf)) < 0)
  1013.                         return (ret);
  1014.                     yskip = skipydots;
  1015.                 }
  1016.                 bufptr = buf;
  1017.                 bufcnt = linewidth;
  1018.                 xskip = 0;
  1019.             }
  1020.         }
  1021.     }
  1022.  
  1023. #if    ALLOC_STACK
  1024.     free(dstack);
  1025. #endif
  1026.  
  1027.    /* PB note that if last line is incomplete, we're not going to try
  1028.       to emit it;  original code did, but did so via out_line and therefore
  1029.       couldn't have worked well in all cases... */
  1030.     return (0);
  1031. }
  1032.