home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / x / volume10 / xv / part06 < prev    next >
Encoding:
Text File  |  1990-12-09  |  54.5 KB  |  2,096 lines

  1. Path: wuarchive!cs.utexas.edu!sun-barr!newstop!exodus!appserv!halibut.cis.upenn.edu
  2. From: bradley@halibut.cis.upenn.edu (John Bradley)
  3. Newsgroups: comp.sources.x
  4. Subject: v10i084: xv - display and manipulate images, Part06/10
  5. Message-ID: <322@appserv.Eng.Sun.COM>
  6. Date: 27 Nov 90 20:08:27 GMT
  7. References: <csx-10i079:xv@uunet.UU.NET>
  8. Sender: news@exodus.Eng.Sun.COM
  9. Lines: 2079
  10. Approved: argv@sun.com
  11.  
  12. Submitted-by: bradley@halibut.cis.upenn.edu (John Bradley)
  13. Posting-number: Volume 10, Issue 84
  14. Archive-name: xv/part06
  15.  
  16. #!/bin/sh
  17. # to extract, remove the header and type "sh filename"
  18. if `test ! -s ./xvfish.c`
  19. then
  20. echo "writting ./xvfish.c"
  21. cat > ./xvfish.c << '\BARFOO\'
  22. /*
  23.  * xvfish.c  -  the required-by-law 'fish' portion of 'xv' 
  24.  *
  25.  * StartFish();
  26.  * StopFish();
  27.  */
  28.  
  29. /*
  30.  * Copyright 1989, 1990 by the University of Pennsylvania
  31.  *
  32.  * Permission to use, copy, and distribute for non-commercial purposes,
  33.  * is hereby granted without fee, providing that the above copyright
  34.  * notice appear in all copies and that both the copyright notice and this
  35.  * permission notice appear in supporting documentation.
  36.  *
  37.  * The software may be modified for your own purposes, but modified versions
  38.  * may not be distributed.
  39.  *
  40.  * This software is provided "as is" without any express or implied warranty.
  41.  */
  42.  
  43.  
  44. #define DELAY 200000L   /* delay between fish increments, in microseconds */
  45. #define NEEDSTIME
  46.  
  47. #include "xv.h"
  48.      
  49. /* size of fish */
  50. #define fwide 32
  51. #define fhigh 16
  52.      
  53.  
  54. static char lfish_bits[] = {
  55.    0x00, 0xc0, 0x07, 0x00, 0x00, 0xb0, 0x06, 0x00, 0x80, 0x7f, 0x03, 0xe0,
  56.    0x60, 0x82, 0x03, 0xb0, 0x18, 0x00, 0x0c, 0x68, 0x64, 0x02, 0xf0, 0x37,
  57.    0x62, 0x00, 0x00, 0x28, 0x01, 0xaa, 0xaa, 0x36, 0x46, 0x00, 0x00, 0x28,
  58.    0x38, 0x03, 0xc0, 0x5f, 0xb0, 0x28, 0x30, 0xb0, 0xc0, 0x39, 0x0e, 0xe0,
  59.    0x00, 0xee, 0x01, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0xa0, 0x00, 0x00,
  60.    0x00, 0xc0, 0x00, 0x00};
  61.      
  62. static char rfish_bits[] = {
  63.    0x00, 0xe0, 0x03, 0x00, 0x00, 0x60, 0x0d, 0x00, 0x07, 0xc0, 0xfe, 0x01,
  64.    0x0d, 0xc0, 0x41, 0x06, 0x12, 0x30, 0x00, 0x18, 0xec, 0x0f, 0x40, 0x26,
  65.    0x14, 0x00, 0x00, 0x46, 0xac, 0xaa, 0x4a, 0x80, 0x14, 0x00, 0x00, 0x62,
  66.    0xfa, 0x03, 0xc0, 0x1c, 0x0d, 0x0c, 0x14, 0x0d, 0x07, 0x70, 0x9c, 0x03,
  67.    0x00, 0x80, 0x77, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x05, 0x00,
  68.    0x00, 0x00, 0x03, 0x00};
  69.      
  70.      
  71. typedef struct fishstr { short x,y,dx,dy; } FISH;
  72.      
  73.  
  74. #define MAXFISH 100
  75. FISH fishdat[MAXFISH];
  76.  
  77. Pixmap lfishP, rfishP;
  78. int numfish=7;
  79. int w,h;
  80. static int firsttime=1;
  81.  
  82.  
  83. static void dofish(), setfishtimer();
  84.  
  85.      
  86. /**************/
  87. StartFish()
  88. /**************/
  89. {
  90.   int i;
  91.  
  92.   if (!fish) return;
  93.  
  94. #if defined(NOTIMER) || defined(USLEEP)
  95.   /* MUST have 'setitimer()' for fish to work */
  96.   return;
  97. #endif
  98.  
  99.   if (useroot || fishrunning || !mainW) return;
  100.   w = eWIDE;  h = eHIGH;
  101.  
  102.   if (firsttime) {
  103.     lfishP=XCreateBitmapFromData(theDisp,mainW,lfish_bits,fwide,fhigh);
  104.     rfishP=XCreateBitmapFromData(theDisp,mainW,rfish_bits,fwide,fhigh);
  105.  
  106.     for (i=0; i<numfish; i++) {
  107.       fishdat[i].x  = rand()%w;
  108.       fishdat[i].y  = rand()%h;
  109.       fishdat[i].dx = (abs(rand()%3)+4);
  110.       
  111.       if (rand()&0x10) fishdat[i].dx = -fishdat[i].dx;
  112.      
  113.       fishdat[i].dy=rand()%7-3;  if (fishdat[i].dy==0) fishdat[i].dy=1;
  114.     }
  115.     firsttime = 0;
  116.   }
  117.  
  118.   fishrunning = 1;
  119.   setfishtimer();
  120. }   
  121.  
  122.  
  123. /**************/
  124. StopFish()
  125. /**************/
  126. {
  127.   struct itimerval it;
  128. #ifdef POSIX
  129.   struct sigaction act;
  130. #endif
  131.  
  132.   if (!fish) return;
  133.   if (!fishrunning) return;
  134.  
  135. #if defined(NOTIMER) || defined(USLEEP)
  136.   /* MUST have setitimer() for fish to work */
  137.   return;
  138. #endif
  139.  
  140. #ifndef POSIX
  141.   HOLD_SIG;              /* block ALRM signal while we turn everything off */
  142. #endif
  143.  
  144.  
  145.   bzero(&it, sizeof(it));
  146.   it.it_interval.tv_usec = 0L;
  147.   it.it_value.tv_usec = 0L;
  148.  
  149.   setitimer(ITIMER_REAL, &it, (struct itimerval *)0);
  150.  
  151. #ifdef POSIX
  152.   act.sa_handler=SIG_DFL;
  153.   sigaction(SIGALRM,&act,NULL);
  154. #else
  155.   signal(SIGALRM,SIG_DFL);
  156.   RELEASE_SIG;          /* allow ALRM signals to happen (we don't get them) */
  157.   fishrunning = 0;
  158. #endif /* POSIX */  
  159. }
  160.  
  161.  
  162.  
  163. /*******************************/
  164. static void dofish()
  165. {
  166.   int i;
  167.   FISH *fp;
  168.  
  169.   XSetForeground(theDisp, theGC, infofg);
  170.   XSetBackground(theDisp, theGC, infobg);
  171.  
  172.   for (i=0; i<numfish; i++) {
  173.     fp = &fishdat[i];    
  174.     XClearArea(theDisp, mainW, fp->x, fp->y, fwide, fhigh, True);
  175.  
  176.     fp->x += fp->dx;
  177.     fp->y += fp->dy;
  178.     if (fp->x < -50)    fp->dx = abs(fp->dx);
  179.     if (fp->x > (w+50)) fp->dx = -abs(fp->dx);
  180.  
  181.     if (fp->y < 10)     fp->dy = abs(fp->dy);
  182.     if (fp->y > (h-20)) fp->dy = -abs(fp->dy);
  183.      
  184.     if (fp->dx<0)
  185.       XCopyPlane(theDisp,lfishP,mainW,theGC,0,0,fwide,fhigh,fp->x,fp->y,1L);
  186.     else
  187.       XCopyPlane(theDisp,rfishP,mainW,theGC,0,0,fwide,fhigh,fp->x,fp->y,1L);
  188.   }
  189.  
  190.   XFlush(theDisp);
  191.   setfishtimer();
  192. }
  193.      
  194.  
  195.      
  196.      
  197. /*******/
  198. static void setfishtimer()
  199. /*******/
  200. {
  201.   struct itimerval it;
  202. #ifdef POSIX
  203.   struct sigaction act;
  204. #endif
  205.      
  206.   bzero(&it, sizeof(it));
  207.   it.it_value.tv_usec = DELAY;
  208.  
  209. #ifdef POSIX
  210.   act.sa_handler=dofish;
  211.   sigaction(SIGALRM,&act,NULL);
  212. #else
  213.   signal(SIGALRM,dofish);
  214.   RELEASE_SIG;               /* enable ALRM signals */
  215.   setitimer(ITIMER_REAL, &it, (struct itimerval *)0);
  216. #endif /* POSIX */
  217. }
  218.  
  219.  
  220.  
  221.  
  222.  
  223.  
  224. \BARFOO\
  225. else
  226.   echo "will not over write ./xvfish.c"
  227. fi
  228. if `test ! -s ./xvgam.c`
  229. then
  230. echo "writting ./xvgam.c"
  231. cat > ./xvgam.c << '\BARFOO\'
  232. /* 
  233.  * xvgam.c - Gamma Correction box handling functions
  234.  *
  235.  * callable functions:
  236.  *
  237.  *   CreateGam(geom)        -  creates the ctrlW window.  Doesn't map it.
  238.  *   GamBox(vis)            -  random processing based on value of 'vis'
  239.  *                             maps/unmaps window, etc.
  240.  *   RedrawGam(x,y,w,h)     -  called by 'expose' events
  241.  *   RedrawGraph(x,y,w,h)   -  called by 'expose' events
  242.  *   ClickGam(x,y)          -  called when B1 clicked in gamW 
  243.  *   TrackGraph(x,y)        -  called when B1 clicked in graphW
  244.  *   GenerateGamma()        -  called to generate/error-check 'ghand'
  245.  *   GenerateFSGamma()      -  called to generate floyd steinberg correction
  246.  *   GammifyColors()        -  does gamma correction of r[],g[],b[] arrays
  247.  *   SetGPreset()           -  sets preset #n to supplied values
  248.  */
  249.  
  250. /*
  251.  * Copyright 1989, 1990 by the University of Pennsylvania
  252.  *
  253.  * Permission to use, copy, and distribute for non-commercial purposes,
  254.  * is hereby granted without fee, providing that the above copyright
  255.  * notice appear in all copies and that both the copyright notice and this
  256.  * permission notice appear in supporting documentation.
  257.  *
  258.  * The software may be modified for your own purposes, but modified versions
  259.  * may not be distributed.
  260.  *
  261.  * This software is provided "as is" without any express or implied warranty.
  262.  */
  263.  
  264.  
  265. #include "xv.h"
  266.  
  267. #define MAXUNDO 8
  268.  
  269. #define BUTTW   80
  270. #define BUTTW2 100
  271. #define BUTTH   19
  272.  
  273. #define LINESTR "Lines"
  274. #define CURVSTR "Spline"
  275. #define HSVSTR  "HSV Mode"
  276. #define RGBSTR  "RGB Mode"
  277.  
  278.  
  279. XPoint presets[4][NUMHANDS];
  280. XPoint undo[MAXUNDO][NUMHANDS];
  281. XPoint defgam[NUMHANDS];
  282. static int firsttime=1;
  283.  
  284.  
  285. #ifdef __STDC__
  286. static void DrawGVals(void);
  287. static void DoGamCommand(int);
  288. static void DoGammaApply(int);
  289. static void SaveUndoState(void);
  290. static void HSVgamma(void);
  291. static void spline(int *, int *, int, float *);
  292. #else
  293. static void DoGamCommand(), DoGammaApply(), HSVgamma(), spline();
  294. static void DrawGVals(), SaveUndoState();
  295. #endif
  296.  
  297.  
  298. /***************************************************/
  299. void CreateGam(geom)
  300. char *geom;
  301. {
  302.   int i,ptop;
  303.  
  304.   gamW = CreateWindow("xv gamma", geom, GAMWIDE,GAMHIGH,infofg,infobg);
  305.   if (!gamW) FatalError("can't create gamma window!");
  306.  
  307.   graphW = XCreateSimpleWindow(theDisp,gamW, 10,40, 256,256, 1, infofg,infobg);
  308.   if (!graphW) FatalError("can't create graph window!");
  309.   XSelectInput(theDisp, graphW, ExposureMask | ButtonPressMask);
  310.  
  311.   /* call CreateCtrl first to create grayTile */
  312.   XSetWindowBackgroundPixmap(theDisp, gamW, grayTile);
  313.  
  314.   BTCreate(&gbut[G_BUP_BR], gamW, 276, 40,
  315.        BUTTW, BUTTH, "Brighter", infofg, infobg);
  316.   BTCreate(&gbut[G_BDN_BR], gamW, 276, 40 + BUTTH + 4,
  317.        BUTTW, BUTTH, "Dimmer", infofg, infobg);
  318.   BTCreate(&gbut[G_BUP_CN], gamW, 276, 40 + 2*BUTTH + 8 + 16,
  319.        BUTTW, BUTTH, "Sharper", infofg, infobg);
  320.   BTCreate(&gbut[G_BDN_CN], gamW, 276, 40 + 3*BUTTH+12 + 16,
  321.        BUTTW, BUTTH, "Duller", infofg, infobg);
  322.  
  323.   BTCreate(&gbut[G_BHSVRGB], gamW, 276, 40 + 4*BUTTH+16+32,
  324.        BUTTW, BUTTH, HSVSTR, infofg, infobg);
  325.  
  326.   BTCreate(&gbut[G_B1], gamW, 276, 40 + 5*BUTTH+20+48,
  327.        17, BUTTH, "1", infofg, infobg);
  328.   BTCreate(&gbut[G_B2], gamW, 276 + ((BUTTW-17)*1)/3, 40 + 5*BUTTH+20+48,
  329.        17, BUTTH, "2", infofg, infobg);
  330.   BTCreate(&gbut[G_B3], gamW, 276 + ((BUTTW-17)*2)/3, 40 + 5*BUTTH+20+48,
  331.        17, BUTTH, "3", infofg, infobg);
  332.   BTCreate(&gbut[G_B4], gamW, 276 + ((BUTTW-17)*3/3), 40 + 5*BUTTH+20+48,
  333.        17, BUTTH, "4", infofg, infobg);
  334.  
  335.   BTCreate(&gbut[G_BSET], gamW, 276, 40 + 6*BUTTH+24+48,
  336.        38, BUTTH, "Set", infofg, infobg);
  337.   gbut[G_BSET].toggle = 1;
  338.  
  339.   BTCreate(&gbut[G_BUNDO], gamW, 276 + 42, 40 + 6*BUTTH+24+48,
  340.        38, BUTTH, "Undo", infofg, infobg);
  341.  
  342.   ptop = GAMHIGH - (2*BUTTH + 3*8);
  343.   BTCreate(&gbut[G_BAPPLY], gamW, 10, ptop+8, BUTTW2, BUTTH, 
  344.        "Apply", infofg, infobg);
  345.   BTCreate(&gbut[G_BNOGAM],  gamW, 10, ptop + BUTTH + 2*8, BUTTW2, BUTTH,
  346.        "No Gamma", infofg, infobg);
  347.  
  348.   BTCreate(&gbut[G_BRESET], gamW, 10+(GAMWIDE-20-BUTTW2)/2, ptop+8, 
  349.        BUTTW2, BUTTH, "Linear", infofg, infobg);
  350.   BTCreate(&gbut[G_BDEF],  gamW, 10+(GAMWIDE-20-BUTTW2)/2, ptop + BUTTH + 2*8,
  351.        BUTTW2, BUTTH, "Default", infofg, infobg);
  352.  
  353.   BTCreate(&gbut[G_BGTYPE], gamW, 10+(2*(GAMWIDE-20-BUTTW2))/2, ptop+8, 
  354.        BUTTW2, BUTTH, CURVSTR, infofg, infobg);
  355.   BTCreate(&gbut[G_BCLOSE],gamW, 10+(2*(GAMWIDE-20-BUTTW2))/2, ptop+BUTTH+2*8,
  356.        BUTTW2, BUTTH, "Close", infofg, infobg);
  357.  
  358.   XMapSubwindows(theDisp, gamW);
  359.  
  360.   /* fill up the undo stack */
  361.   for (i=0; i<MAXUNDO; i++)
  362.     memcpy(undo[i], ghand, sizeof(ghand));
  363. }
  364.   
  365.  
  366. /***************************************************/
  367. void GamBox(vis)
  368. int vis;
  369. {
  370.   if (vis) XMapRaised(theDisp, gamW);
  371.   else     XUnmapWindow(theDisp, gamW);
  372.  
  373.   gamUp = vis;
  374. }
  375.  
  376.  
  377. /***************************************************/
  378. void RedrawGam(x,y,w,h)
  379. int x,y,w,h;
  380. {
  381.   int i;
  382.   XRectangle xr;
  383.  
  384.   xr.x = x;  xr.y = y;  xr.width = w;  xr.height = h;
  385.   XSetClipRectangles(theDisp, theGC, 0,0, &xr, 1, Unsorted);
  386.  
  387.   XSetBackground(theDisp, theGC, infobg);
  388.  
  389.   XSetForeground(theDisp, theGC, infobg);
  390.   XFillRectangle(theDisp,gamW, theGC, 10+1,10+1,256,19);
  391.   XSetForeground(theDisp,theGC,infofg);
  392.   XDrawRectangle(theDisp,gamW, theGC, 10,10,257,20);
  393.   DrawGVals();
  394.  
  395.   for (i=0; i<G_NBUTTS; i++)
  396.     BTRedraw(&gbut[i]);
  397.  
  398.   XSetClipMask(theDisp, theGC, None);
  399. }
  400.  
  401.  
  402. /***************************************************/
  403. static void DrawGVals()
  404. {
  405.   int  w;
  406.   char foo[40];
  407.  
  408.   XSetForeground(theDisp, theGC, infofg);
  409.   XSetBackground(theDisp, theGC, infobg);
  410.  
  411.   sprintf(foo,"%3d   %3d %3d   %3d %3d   %3d", ghand[0].y, ghand[1].x,
  412.       ghand[1].y, ghand[2].x, ghand[2].y, ghand[3].y);
  413.  
  414.   w = XTextWidth(monofinfo, foo, strlen(foo));
  415.   XSetFont(theDisp, theGC, monofont);
  416.   XDrawImageString(theDisp, gamW, theGC, 10 + (256-w)/2, 
  417.           11+(20-(monofinfo->ascent+monofinfo->descent))/2
  418.           + monofinfo->ascent, foo, strlen(foo));
  419.   XSetFont(theDisp, theGC, mfont);
  420. }
  421.  
  422. /***************************************************/
  423. void RedrawGraph(x,y,w,h)
  424. int x,y,w,h;
  425. {
  426.   int i;
  427.   XRectangle xr;
  428.   XPoint  pts[256], *pt;
  429.  
  430.   xr.x = x;  xr.y = y;  xr.width = w;  xr.height = h;
  431.   XSetClipRectangles(theDisp, theGC, 0,0, &xr, 1, Unsorted);
  432.  
  433.   XSetForeground(theDisp, theGC, infofg);
  434.   XSetBackground(theDisp, theGC, infobg);
  435.  
  436.   XClearArea(theDisp, graphW, x,y,w,h, False);
  437.  
  438.   for (i=0, pt=pts; i<256; i++,pt++) {
  439.     pt->x = i;  pt->y = 255-gamcr[i];
  440.   }
  441.   XDrawLines(theDisp, graphW, theGC, pts, 256, CoordModeOrigin);
  442.  
  443.   for (i=0; i<NUMHANDS; i++) {
  444.     XSetForeground(theDisp, theGC, infobg);
  445.     XFillRectangle(theDisp, graphW, theGC, 
  446.            ghand[i].x-2, 255-ghand[i].y-2,5,5);
  447.     XSetForeground(theDisp,theGC,infofg);
  448.     XDrawRectangle(theDisp, graphW, theGC,
  449.            ghand[i].x-3, 255-ghand[i].y-3,6,6);
  450.     XDrawPoint(theDisp, graphW, theGC, ghand[i].x, 255-ghand[i].y);
  451.   }
  452.  
  453.   XSetClipMask(theDisp, theGC, None);
  454. }
  455.  
  456.  
  457. /***************************************************/
  458. void ClickGam(x,y)
  459. int x,y;
  460. {
  461.   int i;
  462.   BUTT *bp;
  463.  
  464.   for (i=0; i<G_NBUTTS; i++) {
  465.     bp = &gbut[i];
  466.     if (PTINRECT(x, y, bp->x, bp->y, bp->w, bp->h)) break;
  467.   }
  468.  
  469.   /* if 'Set' is lit, and we didn't click 'set' or '1'..'4', turn it off */
  470.   if (i!=G_BSET && i!=G_B1 && i!=G_B2 && i!=G_B3 && i!=G_B4 
  471.       && gbut[G_BSET].lit) 
  472.     { gbut[G_BSET].lit = 0;  BTRedraw(&gbut[G_BSET]); }
  473.  
  474.   if (i==G_NBUTTS) return;  /* didn't find one */
  475.  
  476.   if (BTTrack(bp)) DoGamCommand(i);
  477. }
  478.  
  479.  
  480.  
  481. /**********************************************/
  482. void TrackGraph(mx,my)
  483. int mx,my;
  484. {
  485.   /* called when we've gotten a click inside graph window */
  486.  
  487.   Window       rW, cW;
  488.   int          x, y, rx, ry;
  489.   unsigned int mask;
  490.   int          h, vertonly, offx, offy;
  491.  
  492.   if (gbut[G_BSET].lit) 
  493.     { gbut[G_BSET].lit = 0;  BTRedraw(&gbut[G_BSET]); }
  494.  
  495.   my = 255 - my;   /* flip y axis */
  496.  
  497.   /* see if x,y is within any of the handles */
  498.   for (h=0; h<NUMHANDS; h++) {
  499.     if (PTINRECT(mx, my, ghand[h].x-5, ghand[h].y-5, 11,11)) break;
  500.   }
  501.   if (h==NUMHANDS) return;   /* didn't find one */
  502.  
  503.   offx = ghand[h].x - mx;  offy = ghand[h].y - my;
  504.  
  505.   vertonly = (h==0 || h==(NUMHANDS-1));
  506.  
  507.   SaveUndoState();
  508.  
  509.   while (XQueryPointer(theDisp,graphW,&rW,&cW,&rx,&ry,&x,&y,&mask)) {
  510.     if (!(mask & Button1Mask)) break;    /* button released */
  511.     y = 255 - y;   /* flip y-axis */
  512.  
  513.     /* keep this handle between other handles (x-axis) if nec. */
  514.     if (!vertonly) {
  515.       if (x+offx <= ghand[h-1].x) x = (ghand[h-1].x+1)-offx;
  516.       if (x+offx >= ghand[h+1].x) x = (ghand[h+1].x-1)-offx;
  517.     }
  518.     else x = mx;   /* if vert only, ignore sidewards motion */
  519.  
  520.     if (mx != x || my != y) {   /* this handle has moved... */
  521.       ghand[h].x = x+offx;  ghand[h].y = y+offy;
  522.       RANGE(ghand[h].y,0,255);
  523.       GenerateGamma();
  524.       RedrawGraph(0,0,256,256);  /* open to better ideas... */
  525.     }
  526.     mx = x;  my = y;
  527.   }
  528.  
  529.   if ((rwcolor && rwthistime)) DoGammaApply(1);
  530. }
  531.  
  532.  
  533. /*********************/
  534. void GenerateGamma()
  535. {
  536.   /* this function generates a gamma correction curve (gamcr)
  537.  
  538.      This function generates a 4 point spline curve to be used as a 
  539.      non-linear grey 'colormap'.  Two of the points are nailed down at 0,0
  540.      and 255,255, and can't be changed.  You specify the other two.  If
  541.      you specify points on the line (0,0 - 255,255), you'll get the normal
  542.      linear reponse curve.  If you specify points of 50,0 and 200,255, you'll
  543.      get grey values of 0-50 to map to black (0), and grey values of 200-255
  544.      to map to white (255) (roughly).  Values between 50 and 200 will cover
  545.      the output range 0-255.  The reponse curve will be slightly 's' shaped. */
  546.  
  547.   int i,j,k;
  548.   static int x[NUMHANDS], y[NUMHANDS];
  549.   float yf[NUMHANDS];
  550.   static float splint();
  551.  
  552.   /* do some idiot-proofing (x-coords must be monotonically increasing)  */
  553.  
  554.   for (i=0; i<4; i++) { 
  555.     RANGE(ghand[i].x, 0, 255); 
  556.     RANGE(ghand[i].y, 0, 255);
  557.   }
  558.  
  559.   ghand[0].x = 0;  ghand[3].x = 255;
  560.   if (ghand[1].x < 1)  ghand[1].x = 1;
  561.   if (ghand[1].x >253) ghand[1].x = 253;
  562.   if (ghand[2].x < ghand[1].x) ghand[2].x = ghand[1].x + 1;
  563.   if (ghand[2].x >254) ghand[2].x = 254;
  564.  
  565.   if (firsttime) {   /* if this is the first 'generate' save as 'default' */
  566.     memcpy(defgam, ghand, sizeof(ghand));
  567.     firsttime=0;
  568.   }
  569.  
  570.   DrawGVals();
  571.  
  572.   if (!strcmp(gbut[G_BGTYPE].str,LINESTR)) {
  573.     /* do linear interpolation */
  574.     for (i=0; i<NUMHANDS-1; i++) {
  575.       for (j=ghand[i].x,k=0; j<=ghand[i+1].x; j++,k++) {
  576.     gamcr[j] = ghand[i].y + (k * (ghand[i+1].y - ghand[i].y)) / 
  577.                             (ghand[i+1].x - ghand[i].x);
  578.       }
  579.     }
  580.     return;
  581.   }
  582.  
  583.  
  584.  
  585.   for (i=0; i<NUMHANDS; i++) { x[i] = ghand[i].x;  y[i] = ghand[i].y; }
  586.   spline(x, y, NUMHANDS, yf);
  587.   
  588.   for (i=0; i<256; i++) {
  589.     j = (int) splint(x, y, yf, NUMHANDS, (float) i);
  590.     if (j<0) j=0;
  591.     else if (j>255) j=255;
  592.     gamcr[i] = j;
  593.   }
  594. }
  595.  
  596.  
  597. /*********************/
  598. void GenerateFSGamma()
  599. {
  600.   /* this function generates the Floyd-Steinberg gamma curve (fsgamcr)
  601.  
  602.      This function generates a 4 point spline curve to be used as a 
  603.      non-linear grey 'colormap'.  Two of the points are nailed down at 0,0
  604.      and 255,255, and can't be changed.  You specify the other two.  If
  605.      you specify points on the line (0,0 - 255,255), you'll get the normal
  606.      linear reponse curve.  If you specify points of 50,0 and 200,255, you'll
  607.      get grey values of 0-50 to map to black (0), and grey values of 200-255
  608.      to map to white (255) (roughly).  Values between 50 and 200 will cover
  609.      the output range 0-255.  The reponse curve will be slightly 's' shaped. */
  610.  
  611.   int i,j;
  612.   static int x[4] = {0,32,224,255};
  613.   static int y[4] = {0, 0,255,255};
  614.   float yf[4];
  615.   static float splint();
  616.  
  617.   spline(x, y, 4, yf);
  618.   
  619.   for (i=0; i<256; i++) {
  620.     j = (int) splint(x, y, yf, 4, (float) i);
  621.     if (j<0) j=0;
  622.     else if (j>255) j=255;
  623.     fsgamcr[i] = j;
  624.   }
  625. }
  626.  
  627.  
  628. /*********************/
  629. static void spline(x,y,n,y2)
  630.      int *x, *y, n;
  631.      float *y2;
  632. {
  633.   /* given arrays of data points x[0..n-1] and y[0..n-1], computes the
  634.      values of the second derivative at each of the data points
  635.      y2[0..n-1] for use in the splint function */
  636.  
  637.   int i,k;
  638.   float p,qn,sig,un,u[NUMHANDS];
  639.  
  640.   y2[0] = u[0] = 0.0;
  641.  
  642.   for (i=1; i<n-1; i++) {
  643.     sig = ((float) x[i]-x[i-1]) / ((float) x[i+1] - x[i-1]);
  644.     p = sig * y2[i-1] + 2.0;
  645.     y2[i] = (sig-1.0) / p;
  646.     u[i] = (((float) y[i+1]-y[i]) / (x[i+1]-x[i])) - 
  647.            (((float) y[i]-y[i-1]) / (x[i]-x[i-1]));
  648.     u[i] = (6.0 * u[i]/(x[i+1]-x[i-1]) - sig*u[i-1]) / p;
  649.   }
  650.   qn = un = 0.0;
  651.  
  652.   y2[n-1] = (un-qn*u[n-2]) / (qn*y2[n-2]+1.0);
  653.   for (k=n-2; k>=0; k--)
  654.     y2[k] = y2[k]*y2[k+1]+u[k];
  655. }
  656.  
  657.  
  658.  
  659. /*********************/
  660. static float splint(xa,ya,y2a,n,x)
  661. float y2a[],x;
  662. int n,xa[],ya[];
  663. {
  664.   int klo,khi,k;
  665.   float h,b,a;
  666.  
  667.   klo = 0;
  668.   khi = n-1;
  669.   while (khi-klo > 1) {
  670.     k = (khi+klo) >> 1;
  671.     if (xa[k] > x) khi = k;
  672.     else klo = k;
  673.   }
  674.   h = xa[khi] - xa[klo];
  675.   if (h==0.0) FatalError("bad xvalues in splint\n");
  676.   a = (xa[khi]-x)/h;
  677.   b = (x-xa[klo])/h;
  678.   return (a*ya[klo] + b*ya[khi] + ((a*a*a-a)*y2a[klo] +(b*b*b-b)*y2a[khi]) 
  679.       * (h*h) / 6.0);
  680. }
  681.     
  682.  
  683. /*********************/
  684. static void DoGamCommand(cmd)
  685. int cmd;
  686. {
  687.   int i,p, app;
  688.  
  689.   app = 1;  p=0;
  690.  
  691.   switch (cmd) {
  692.   case G_BAPPLY: DoGammaApply(1);  app = 0;  break;
  693.   case G_BNOGAM: DoGammaApply(0);  app = 0;  break;
  694.  
  695.   case G_BRESET: SaveUndoState();
  696.                  ghand[0].x =   0; ghand[0].y =   0;
  697.                  ghand[1].x =  64; ghand[1].y =  64;
  698.                  ghand[2].x = 192; ghand[2].y = 192;
  699.                  ghand[3].x = 255; ghand[3].y = 255;
  700.  
  701.                  GenerateGamma();
  702.                  RedrawGraph(0,0,256,256);
  703.                  break;
  704.  
  705.  
  706.  
  707.   case G_BDEF:   SaveUndoState();
  708.                  memcpy(ghand, defgam, sizeof(ghand));
  709.  
  710.                  GenerateGamma();
  711.                  RedrawGraph(0,0,256,256);
  712.                  break;
  713.  
  714.   case G_BGTYPE: if (!strcmp(gbut[G_BGTYPE].str, LINESTR))
  715.                       gbut[G_BGTYPE].str = CURVSTR;
  716.                  else gbut[G_BGTYPE].str = LINESTR;
  717.                  BTRedraw(&gbut[G_BGTYPE]);
  718.                  GenerateGamma();
  719.                  RedrawGraph(0,0,256,256);
  720.                  break;
  721.  
  722.   case G_BCLOSE: GamBox(0);  app=0;  break;
  723.  
  724.   case G_BUP_BR: SaveUndoState();
  725.                  for (i=0; i<NUMHANDS; i++) {
  726.                    ghand[i].y += 10;
  727.            RANGE(ghand[i].y,0,255);
  728.          }
  729.                  
  730.                  GenerateGamma();
  731.                  RedrawGraph(0,0,256,256);
  732.                  break;
  733.  
  734.   case G_BDN_BR: SaveUndoState();
  735.                  for (i=0; i<NUMHANDS; i++) {
  736.                    ghand[i].y -= 10;
  737.            RANGE(ghand[i].y,0,255);
  738.          }
  739.                  
  740.                  GenerateGamma();
  741.                  RedrawGraph(0,0,256,256);
  742.                  break;
  743.  
  744.   case G_BUP_CN: SaveUndoState();
  745.                  ghand[0].y -= 10;  
  746.                  ghand[1].y -= 10;  ghand[1].x += 5;
  747.                  ghand[2].y += 10;  ghand[2].x -= 5;
  748.                  ghand[3].y += 10;
  749.                  if (ghand[1].x > 127) ghand[1].x = 127;
  750.                  if (ghand[2].x <= ghand[1].x) ghand[2].x = ghand[1].x+1;
  751.                  for (i=0; i<NUMHANDS; i++) RANGE(ghand[i].y,0,255);
  752.                  
  753.                  GenerateGamma();
  754.                  RedrawGraph(0,0,256,256);
  755.                  break;
  756.  
  757.   case G_BDN_CN: SaveUndoState();
  758.                  if (abs(ghand[0].y - 127) < 10) ghand[0].y = 127;
  759.                  else ghand[0].y += ((ghand[0].y>127) ? -10 : 10);
  760.  
  761.                  if (abs(ghand[1].y - 127) < 10) ghand[1].y = 127;
  762.                  else ghand[1].y += ((ghand[1].y>127) ? -10 : 10);
  763.  
  764.                  if (abs(ghand[2].y - 127) < 10) ghand[2].y = 127;
  765.                  else ghand[2].y += ((ghand[2].y>127) ? -10 : 10);
  766.  
  767.                  if (abs(ghand[3].y - 127) < 10) ghand[3].y = 127;
  768.                  else ghand[3].y += ((ghand[3].y>127) ? -10 : 10);
  769.  
  770.                  for (i=0; i<NUMHANDS; i++) RANGE(ghand[i].y,0,255);
  771.                  
  772.                  GenerateGamma();
  773.                  RedrawGraph(0,0,256,256);
  774.                  break;
  775.  
  776.   case G_BHSVRGB:if (!strcmp(gbut[G_BHSVRGB].str, HSVSTR))
  777.                       gbut[G_BHSVRGB].str = RGBSTR;
  778.                  else gbut[G_BHSVRGB].str = HSVSTR;
  779.                  BTRedraw(&gbut[G_BHSVRGB]);
  780.                  break;
  781.  
  782.   case G_B1:
  783.   case G_B2:
  784.   case G_B3:
  785.   case G_B4:     if      (cmd==G_B1) p = 0;
  786.                  else if (cmd==G_B2) p = 1;
  787.                  else if (cmd==G_B3) p = 2;
  788.                  else if (cmd==G_B4) p = 3;
  789.                 
  790.                  if (gbut[G_BSET].lit) {
  791.                    memcpy(presets[p], ghand, sizeof(ghand));
  792.            gbut[G_BSET].lit = 0;
  793.            BTRedraw(&gbut[G_BSET]);
  794.            app=0;
  795.          }
  796.                  else {
  797.                    SaveUndoState();
  798.            memcpy(ghand, presets[p], sizeof(ghand));
  799.            GenerateGamma();
  800.                    RedrawGraph(0,0,256,256);
  801.          }
  802.                  break;
  803.  
  804.   case G_BSET:   app=0;  break;
  805.  
  806.   case G_BUNDO:  bcopy(undo[0], ghand, sizeof(ghand));
  807.                  bcopy(undo[1], undo[0], (MAXUNDO-1)*sizeof(ghand));
  808.                  GenerateGamma();
  809.                  RedrawGraph(0,0,256,256);
  810.                  break;
  811.   }
  812.   
  813.   if (app && rwcolor && rwthistime) DoGammaApply(1);
  814. }
  815.  
  816.  
  817. /*********************/
  818. static void DoGammaApply(app)
  819. int app;
  820. {
  821.   int i,j;
  822.  
  823.   DoMonoAndRV();
  824.  
  825.   if (app) GammifyColors();
  826.  
  827.   /* special case: if using R/W color, just modify the colors and leave */
  828.   if (rwcolor && rwthistime) {
  829.     XColor ctab[256];
  830.     for (i=0; i<nfcols; i++) {
  831.       j = fc2pcol[i];
  832.       ctab[i].pixel = freecols[i];
  833.       ctab[i].red   = r[j]<<8;
  834.       ctab[i].green = g[j]<<8;
  835.       ctab[i].blue  = b[j]<<8;
  836.       ctab[i].flags = DoRed | DoGreen | DoBlue;
  837.       XStoreColor(theDisp, LocalCmap ? LocalCmap : theCmap, &ctab[i]);
  838.     }
  839.     return;
  840.   }
  841.     
  842.  
  843.   if (useroot && (LocalCmap || nfcols)) {
  844.     XSetWindowBackgroundPixmap(theDisp, rootW, None);
  845.   }
  846.  
  847.  
  848.   if (LocalCmap) {
  849.     XClearWindow(theDisp,mainW);
  850.     XFreeColormap(theDisp,LocalCmap);
  851.     LocalCmap = 0;
  852.   }
  853.   else {
  854.     if (!brokeFreeCols) {
  855.       for (i=0; i<nfcols; i++) 
  856.     XFreeColors(theDisp, theCmap, &freecols[i], 1, 0L);
  857.     }
  858.     else {
  859.       for (i=0; i<nfcols; i++) {
  860.     int j;
  861.     for (j=0; j<i; j++) {
  862.       if (freecols[i] == freecols[j])   /* already been freed once */
  863.         break;
  864.     }
  865.     if (j==i)      /* wasn't found in already-freed list */
  866.       XFreeColors(theDisp, theCmap, &freecols[i], 1, 0L);
  867.       }
  868.     }
  869.  
  870.     if (nfcols) {
  871.       XFlush(theDisp);  /* just to make sure they're all freed right now... */
  872.  
  873.       /* clear window if we're on a non-static display */
  874.       if (theVisual->class & 1 && ncols>0) XClearWindow(theDisp,mainW);
  875.     }
  876.   }
  877.  
  878.  
  879.   AllocColors();
  880.   CreateXImage();
  881.  
  882.   if (useroot) MakeRootPic();
  883.           else DrawWindow(0,0,eWIDE,eHIGH);
  884.   if (but[BCROP].active) InvCropRect();
  885.   SetCursors(-1);
  886. }
  887.  
  888.  
  889. /*********************/
  890. void GammifyColors()
  891. {
  892.   int i;
  893.  
  894.   if (!strcmp(gbut[G_BHSVRGB].str,RGBSTR)) {
  895.     for (i=0; i<numcols; i++) {
  896.       r[i] = gamcr[r[i]];
  897.       g[i] = gamcr[g[i]];
  898.       b[i] = gamcr[b[i]];
  899.     }
  900.   }
  901.   else HSVgamma();
  902. }
  903.  
  904.  
  905. /*********************/
  906. void SetGPreset(n,y0,x1,y1,x2,y2,y3)
  907. int n,y0,x1,y1,x2,y2,y3;
  908. {
  909.   if (n<0 || n>3) return;
  910.   
  911.   presets[n][0].x = 0;     presets[n][0].y = y0;
  912.   presets[n][1].x = x1;    presets[n][1].y = y1;
  913.   presets[n][2].x = x2;    presets[n][2].y = y2;
  914.   presets[n][3].x = 255;   presets[n][3].y = y3;
  915. }
  916.  
  917.   
  918. #define NOHUE -1
  919.  
  920. /*********************/
  921. static void HSVgamma()
  922. {
  923.   int    i, vi, j;
  924.   double rd, gd, bd, h, s, v, max, min, del, rc, gc, bc;
  925.   double f, p, q, t;
  926.  
  927.   for (i=0; i<numcols; i++) {
  928.     /* convert RGB to HSV */
  929.     rd = r[i] / 255.0;            /* rd,gd,bd range 0-1 instead of 0-255 */
  930.     gd = g[i] / 255.0;
  931.     bd = b[i] / 255.0;
  932.  
  933.     /* compute maximum of rd,gd,bd */
  934.     if (rd>=gd) { if (rd>=bd) max = rd;  else max = bd; }
  935.            else { if (gd>=bd) max = gd;  else max = bd; }
  936.  
  937.     /* compute minimum of rd,gd,bd */
  938.     if (rd<=gd) { if (rd<=bd) min = rd;  else min = bd; }
  939.            else { if (gd<=bd) min = gd;  else min = bd; }
  940.  
  941.     del = max - min;
  942.     v = max;
  943.     if (max != 0.0) s = (del) / max;
  944.                else s = 0.0;
  945.  
  946.     h = NOHUE;
  947.     if (s != 0.0) {
  948.       rc = (max - rd) / del;
  949.       gc = (max - gd) / del;
  950.       bc = (max - bd) / del;
  951.  
  952.       if      (rd==max) h = bc - gc;
  953.       else if (gd==max) h = 2 + rc - bc;
  954.       else if (bd==max) h = 4 + gc - rc;
  955.  
  956.       h = h * 60;
  957.       if (h<0) h += 360;
  958.     }
  959.  
  960.     /* map near-black to black to avoid weird effects */
  961.     if (v <= .0625) s = 0.0;
  962.  
  963.     /* apply gamcr[] function to 'v' (the intensity) */
  964.     vi = (int) floor(v * 255);
  965.     v = gamcr[vi] / 255.0;
  966.  
  967.     /* convert HSV back to RGB */
  968.     if (s==0.0) { rd = v;  gd = v;  bd = v; }
  969.     else {
  970.       if (h==360.0) h = 0.0;
  971.       h = h / 60.0;
  972.       j = (int) floor(h);
  973.       f = h - j;
  974.       p = v * (1-s);
  975.       q = v * (1 - (s*f));
  976.       t = v * (1 - (s*(1 - f)));
  977.  
  978.       switch (j) {
  979.       case 0:  rd = v;  gd = t;  bd = p;  break;
  980.       case 1:  rd = q;  gd = v;  bd = p;  break;
  981.       case 2:  rd = p;  gd = v;  bd = t;  break;
  982.       case 3:  rd = p;  gd = q;  bd = v;  break;
  983.       case 4:  rd = t;  gd = p;  bd = v;  break;
  984.       case 5:  rd = v;  gd = p;  bd = q;  break;
  985.       }
  986.     }
  987.  
  988.     r[i] = (int) floor(rd * 255);
  989.     g[i] = (int) floor(gd * 255);
  990.     b[i] = (int) floor(bd * 255);
  991.   }
  992. }
  993.  
  994.  
  995.   
  996.  
  997. /*********************/
  998. static void SaveUndoState()
  999. {
  1000.   /* pushes the current 'ghand' values onto the undo stack */
  1001.  
  1002.   /* use bcopy 'cause it knows how to do overlapped copies */
  1003.   bcopy(undo[0], undo[1], (MAXUNDO-1) * sizeof(ghand));
  1004.   
  1005.   /* and put 'ghand' on the top of the stack */
  1006.   bcopy(ghand, undo[0], sizeof(ghand));
  1007. }
  1008. \BARFOO\
  1009. else
  1010.   echo "will not over write ./xvgam.c"
  1011. fi
  1012. if `test ! -s ./xvgif.c`
  1013. then
  1014. echo "writting ./xvgif.c"
  1015. cat > ./xvgif.c << '\BARFOO\'
  1016. /*
  1017.  * xvgif.c  -  GIF loading code for 'xv'.  Based strongly on...
  1018.  *
  1019.  * gif2ras.c - Converts from a Compuserve GIF (tm) image to a Sun Raster image.
  1020.  *
  1021.  * Copyright (c) 1988, 1989 by Patrick J. Naughton
  1022.  *
  1023.  * Author: Patrick J. Naughton
  1024.  * naughton@wind.sun.com
  1025.  *
  1026.  * Permission to use, copy, modify, and distribute this software and its
  1027.  * documentation for any purpose and without fee is hereby granted,
  1028.  * provided that the above copyright notice appear in all copies and that
  1029.  * both that copyright notice and this permission notice appear in
  1030.  * supporting documentation.
  1031.  *
  1032.  * This file is provided AS IS with no warranties of any kind.  The author
  1033.  * shall have no liability with respect to the infringement of copyrights,
  1034.  * trade secrets or any patents by this file or any part thereof.  In no
  1035.  * event will the author be liable for any lost revenue or profits or
  1036.  * other special, indirect and consequential damages.
  1037.  *
  1038.  */
  1039.  
  1040. /*
  1041.  * Copyright 1989, 1990 by the University of Pennsylvania
  1042.  *
  1043.  * Permission to use, copy, and distribute for non-commercial purposes,
  1044.  * is hereby granted without fee, providing that the above copyright
  1045.  * notice appear in all copies and that both the copyright notice and this
  1046.  * permission notice appear in supporting documentation.
  1047.  *
  1048.  * The software may be modified for your own purposes, but modified versions
  1049.  * may not be distributed.
  1050.  *
  1051.  * This software is provided "as is" without any express or implied warranty.
  1052.  */
  1053.  
  1054. #include "xv.h"
  1055.  
  1056. typedef int boolean;
  1057.  
  1058. #define NEXTBYTE (*ptr++)
  1059. #define IMAGESEP 0x2c
  1060. #define EXTENSION 0x21
  1061. #define INTERLACEMASK 0x40
  1062. #define COLORMAPMASK 0x80
  1063.  
  1064.   
  1065.  
  1066. FILE *fp;
  1067.  
  1068. int BitOffset = 0,        /* Bit Offset of next code */
  1069.     XC = 0, YC = 0,        /* Output X and Y coords of current pixel */
  1070.     Pass = 0,            /* Used by output routine if interlaced pic */
  1071.     OutCount = 0,        /* Decompressor output 'stack count' */
  1072.     RWidth, RHeight,        /* screen dimensions */
  1073.     Width, Height,        /* image dimensions */
  1074.     LeftOfs, TopOfs,        /* image offset */
  1075.     BitsPerPixel,        /* Bits per pixel, read from GIF header */
  1076.     BytesPerScanline,        /* bytes per scanline in output raster */
  1077.     ColorMapSize,        /* number of colors */
  1078.     Background,            /* background color */
  1079.     CodeSize,            /* Code size, read from GIF header */
  1080.     InitCodeSize,        /* Starting code size, used during Clear */
  1081.     Code,            /* Value returned by ReadCode */
  1082.     MaxCode,            /* limiting value for current code size */
  1083.     ClearCode,            /* GIF clear code */
  1084.     EOFCode,            /* GIF end-of-information code */
  1085.     CurCode, OldCode, InCode,    /* Decompressor variables */
  1086.     FirstFree,            /* First free code, generated per GIF spec */
  1087.     FreeCode,            /* Decompressor,next free slot in hash table */
  1088.     FinChar,            /* Decompressor variable */
  1089.     BitMask,            /* AND mask for data size */
  1090.     ReadMask,            /* Code AND mask for current code size */
  1091.     Misc;                       /* miscellaneous bits (interlace, local cmap)*/
  1092.  
  1093.  
  1094. boolean Interlace, HasColormap;
  1095.  
  1096. byte *RawGIF;            /* The heap array to hold it, raw */
  1097. byte *Raster;            /* The raster data stream, unblocked */
  1098.  
  1099.     /* The hash table used by the decompressor */
  1100. int Prefix[4096];
  1101. int Suffix[4096];
  1102.  
  1103.     /* An output array used by the decompressor */
  1104. int OutCode[1025];
  1105.  
  1106. char *id = "GIF87a";
  1107.  
  1108. static int EGApalette[16][3] = {
  1109.   {0,0,0},       {0,0,128},     {0,128,0},     {0,128,128}, 
  1110.   {128,0,0},     {128,0,128},   {128,128,0},   {200,200,200},
  1111.   {100,100,100}, {100,100,255}, {100,255,100}, {100,255,255},
  1112.   {255,100,100}, {255,100,255}, {255,255,100}, {255,255,255} };
  1113.   
  1114.  
  1115. static int  ReadCode();
  1116. static void DoInterlace();
  1117. static int  GifError();
  1118.  
  1119. int filesize;
  1120.  
  1121. /*****************************/
  1122. int LoadGIF(fname,nc)
  1123.   char *fname;
  1124.   int   nc;
  1125. /*****************************/
  1126. {
  1127.   register byte  ch, ch1;
  1128.   register byte *ptr, *ptr1, *picptr;
  1129.   register int   i;
  1130.   int            npixels, maxpixels;
  1131.  
  1132.   /* initialize variables */
  1133.   BitOffset = XC = YC = Pass = OutCount = npixels = maxpixels = 0;
  1134.   RawGIF = Raster = pic = NULL;
  1135.   
  1136.   fp = fopen(fname,"r");
  1137.   if (!fp) {
  1138.     fprintf(stderr,"%s: LoadGIF() - unable to open file '%s'\n",cmd,fname);
  1139.     return 1;
  1140.   }
  1141.   
  1142.   /* find the size of the file */
  1143.   fseek(fp, 0L, 2);
  1144.   filesize = ftell(fp);
  1145.   fseek(fp, 0L, 0);
  1146.   
  1147.   /* the +256's are so we can read truncated GIF files without fear of 
  1148.      segmentation violation */
  1149.   if (!(ptr = RawGIF = (byte *) malloc(filesize+256)))
  1150.     return( GifError("not enough memory to read gif file") );
  1151.   
  1152.   if (!(Raster = (byte *) malloc(filesize+256)))    
  1153.     return( GifError("not enough memory to read gif file") );
  1154.   
  1155.   if (fread(ptr, filesize, 1, fp) != 1) 
  1156.     return( GifError("GIF data read failed") );
  1157.   
  1158.   if (strncmp(ptr, id, 6)) 
  1159.     return( GifError("not a GIF file"));
  1160.   
  1161.   ptr += 6;
  1162.   
  1163.   /* Get variables from the GIF screen descriptor */
  1164.   
  1165.   ch = NEXTBYTE;
  1166.   RWidth = ch + 0x100 * NEXTBYTE;    /* screen dimensions... not used. */
  1167.   ch = NEXTBYTE;
  1168.   RHeight = ch + 0x100 * NEXTBYTE;
  1169.   
  1170.   ch = NEXTBYTE;
  1171.   HasColormap = ((ch & COLORMAPMASK) ? True : False);
  1172.   
  1173.   BitsPerPixel = (ch & 7) + 1;
  1174.   numcols = ColorMapSize = 1 << BitsPerPixel;
  1175.   BitMask = ColorMapSize - 1;
  1176.   
  1177.   Background = NEXTBYTE;        /* background color... not used. */
  1178.   
  1179.   if (NEXTBYTE)        /* supposed to be NULL */
  1180.     return( GifError("corrupt GIF file (screen descriptor)") );
  1181.   
  1182.   
  1183.   /* Read in global colormap. */
  1184.   
  1185.   if (HasColormap)
  1186.     for (i=0; i<ColorMapSize; i++) {
  1187.       r[i] = NEXTBYTE;
  1188.       g[i] = NEXTBYTE;
  1189.       b[i] = NEXTBYTE;
  1190.     }
  1191.   else {  /* no colormap in GIF file */
  1192.     /* put std EGA palette (repeated 16 times) into colormap, for lack of
  1193.        anything better to do */
  1194.  
  1195.     for (i=0; i<256; i++) {
  1196.       r[i] = EGApalette[i&15][0];
  1197.       g[i] = EGApalette[i&15][1];
  1198.       b[i] = EGApalette[i&15][2];
  1199.     }
  1200.   }
  1201.  
  1202.  
  1203.   while ( (i=NEXTBYTE) == EXTENSION) {  /* parse extension blocks */
  1204.     int i, fn, blocksize, aspnum, aspden;
  1205.  
  1206.     /* read extension block */
  1207.     fn = NEXTBYTE;
  1208.  
  1209.     do {
  1210.       i = 0;  blocksize = NEXTBYTE;
  1211.       while (i<blocksize) {
  1212.     if (fn == 'R' && blocksize == 2) {   /* aspect ratio extension */
  1213.       aspnum = NEXTBYTE;  i++;
  1214.       aspden = NEXTBYTE;  i++;
  1215.       if (aspden>0 && aspnum>0) 
  1216.         normaspect = (float) aspnum / (float) aspden;
  1217.       else { normaspect = 1.0;  aspnum = aspden = 1; }
  1218.  
  1219.           /* fprintf(stderr,"aspect extension: %d:%d = %f\n", 
  1220.           aspnum, aspden,normaspect); */
  1221.     }
  1222.     else { NEXTBYTE;  i++; }
  1223.       }
  1224.     } while (blocksize);
  1225.   }
  1226.  
  1227.  
  1228.   /* Check for image seperator */
  1229.   if (i != IMAGESEP) 
  1230.     return( GifError("corrupt GIF file (no image separator)") );
  1231.   
  1232.   /* Now read in values from the image descriptor */
  1233.   
  1234.   ch = NEXTBYTE;
  1235.   LeftOfs = ch + 0x100 * NEXTBYTE;
  1236.   ch = NEXTBYTE;
  1237.   TopOfs = ch + 0x100 * NEXTBYTE;
  1238.   ch = NEXTBYTE;
  1239.   Width = ch + 0x100 * NEXTBYTE;
  1240.   ch = NEXTBYTE;
  1241.   Height = ch + 0x100 * NEXTBYTE;
  1242.  
  1243.   Misc = NEXTBYTE;
  1244.   Interlace = ((Misc & INTERLACEMASK) ? True : False);
  1245.  
  1246.   if (Misc & 0x80) {
  1247.     for (i=0; i< 1 << ((Misc&7)+1); i++) {
  1248.       r[i] = NEXTBYTE;
  1249.       g[i] = NEXTBYTE;
  1250.       b[i] = NEXTBYTE;
  1251.     }
  1252.   }
  1253.  
  1254.  
  1255.   if (!HasColormap && !(Misc&0x80)) {
  1256.     /* no global or local colormap */
  1257.     SetISTR(ISTR_WARNING,
  1258.         "No colormap in this GIF file.  Assuming EGA colors.");
  1259.   }
  1260.     
  1261.  
  1262.   
  1263.   /* Start reading the raster data. First we get the intial code size
  1264.    * and compute decompressor constant values, based on this code size.
  1265.    */
  1266.   
  1267.   CodeSize = NEXTBYTE;
  1268.   ClearCode = (1 << CodeSize);
  1269.   EOFCode = ClearCode + 1;
  1270.   FreeCode = FirstFree = ClearCode + 2;
  1271.   
  1272.   /* The GIF spec has it that the code size is the code size used to
  1273.    * compute the above values is the code size given in the file, but the
  1274.    * code size used in compression/decompression is the code size given in
  1275.    * the file plus one. (thus the ++).
  1276.    */
  1277.   
  1278.   CodeSize++;
  1279.   InitCodeSize = CodeSize;
  1280.   MaxCode = (1 << CodeSize);
  1281.   ReadMask = MaxCode - 1;
  1282.   
  1283.  
  1284.  
  1285.   /* UNBLOCK:
  1286.    * Read the raster data.  Here we just transpose it from the GIF array
  1287.    * to the Raster array, turning it from a series of blocks into one long
  1288.    * data stream, which makes life much easier for ReadCode().
  1289.    */
  1290.   
  1291.   ptr1 = Raster;
  1292.   do {
  1293.     ch = ch1 = NEXTBYTE;
  1294.     while (ch--) { *ptr1 = NEXTBYTE; ptr1++; }
  1295.     if ((ptr - RawGIF) > filesize) {
  1296.       SetISTR(ISTR_WARNING,
  1297.           "This GIF file seems to be truncated.  Winging it.");
  1298.       break;
  1299.     }
  1300.   } while(ch1);
  1301.   free(RawGIF);     RawGIF = NULL;     /* We're done with the raw data now */
  1302.  
  1303.  
  1304.  
  1305.   if (DEBUG) {
  1306.     fprintf(stderr,"xv: LoadGIF() - picture is %dx%d, %d bits, %sinterlaced\n",
  1307.         Width, Height, BitsPerPixel, Interlace ? "" : "non-");
  1308.   }
  1309.   
  1310.   SetISTR(ISTR_FORMAT, "GIF, %d bits per pixel, %sinterlaced.  (%d bytes)",
  1311.       BitsPerPixel, Interlace ? "" : "non-", filesize);
  1312.  
  1313.  
  1314.  
  1315.   /* Allocate the 'pic' */
  1316.   pWIDE = Width;  pHIGH = Height;
  1317.   maxpixels = Width*Height;
  1318.   picptr = pic = (byte *) malloc(maxpixels);
  1319.   if (!pic) 
  1320.     return( GifError("not enough memory for 'pic'") );
  1321.  
  1322.   
  1323.   /* Decompress the file, continuing until you see the GIF EOF code.
  1324.    * One obvious enhancement is to add checking for corrupt files here.
  1325.    */
  1326.   
  1327.   Code = ReadCode();
  1328.   while (Code != EOFCode) {
  1329.     /* Clear code sets everything back to its initial value, then reads the
  1330.      * immediately subsequent code as uncompressed data.
  1331.      */
  1332.  
  1333.     if (Code == ClearCode) {
  1334.       CodeSize = InitCodeSize;
  1335.       MaxCode = (1 << CodeSize);
  1336.       ReadMask = MaxCode - 1;
  1337.       FreeCode = FirstFree;
  1338.       Code = ReadCode();
  1339.       CurCode = OldCode = Code;
  1340.       FinChar = CurCode & BitMask;
  1341.       if (!Interlace) *picptr++ = FinChar;
  1342.          else DoInterlace(FinChar);
  1343.       npixels++;
  1344.     }
  1345.     else {
  1346.       /* If not a clear code, must be data: save same as CurCode and InCode */
  1347.  
  1348.       /* if we're at maxcode and didn't get a clear, stop loading */
  1349.       if (FreeCode>=4096) { /* printf("freecode blew up\n"); */
  1350.                 break; }
  1351.  
  1352.       CurCode = InCode = Code;
  1353.       
  1354.       /* If greater or equal to FreeCode, not in the hash table yet;
  1355.        * repeat the last character decoded
  1356.        */
  1357.       
  1358.       if (CurCode >= FreeCode) {
  1359.     CurCode = OldCode;
  1360.     if (OutCount > 1024) {  /* printf("outcount1 blew up\n"); */ break; }
  1361.     OutCode[OutCount++] = FinChar;
  1362.       }
  1363.       
  1364.       /* Unless this code is raw data, pursue the chain pointed to by CurCode
  1365.        * through the hash table to its end; each code in the chain puts its
  1366.        * associated output code on the output queue.
  1367.        */
  1368.       
  1369.       while (CurCode > BitMask) {
  1370.     if (OutCount > 1024) break;   /* corrupt file */
  1371.     OutCode[OutCount++] = Suffix[CurCode];
  1372.     CurCode = Prefix[CurCode];
  1373.       }
  1374.       
  1375.       if (OutCount > 1024) { /* printf("outcount blew up\n"); */ break; }
  1376.       
  1377.       /* The last code in the chain is treated as raw data. */
  1378.       
  1379.       FinChar = CurCode & BitMask;
  1380.       OutCode[OutCount++] = FinChar;
  1381.       
  1382.       /* Now we put the data out to the Output routine.
  1383.        * It's been stacked LIFO, so deal with it that way...
  1384.        */
  1385.  
  1386.       /* safety thing:  prevent exceeding range of 'pic' */
  1387.       if (npixels + OutCount > maxpixels) OutCount = maxpixels-npixels;
  1388.     
  1389.       npixels += OutCount;
  1390.       if (!Interlace) for (i=OutCount-1; i>=0; i--) *picptr++ = OutCode[i];
  1391.                 else  for (i=OutCount-1; i>=0; i--) DoInterlace(OutCode[i]);
  1392.       OutCount = 0;
  1393.  
  1394.       /* Build the hash table on-the-fly. No table is stored in the file. */
  1395.       
  1396.       Prefix[FreeCode] = OldCode;
  1397.       Suffix[FreeCode] = FinChar;
  1398.       OldCode = InCode;
  1399.       
  1400.       /* Point to the next slot in the table.  If we exceed the current
  1401.        * MaxCode value, increment the code size unless it's already 12.  If it
  1402.        * is, do nothing: the next code decompressed better be CLEAR
  1403.        */
  1404.       
  1405.       FreeCode++;
  1406.       if (FreeCode >= MaxCode) {
  1407.     if (CodeSize < 12) {
  1408.       CodeSize++;
  1409.       MaxCode *= 2;
  1410.       ReadMask = (1 << CodeSize) - 1;
  1411.     }
  1412.       }
  1413.     }
  1414.     Code = ReadCode();
  1415.     if (npixels >= maxpixels) break;
  1416.   }
  1417.   free(Raster);  Raster = NULL;
  1418.   
  1419.   if (npixels != maxpixels) {
  1420.     SetISTR(ISTR_WARNING,"This GIF file seems to be truncated.  Winging it.");
  1421.     memset(pic+npixels, 0, maxpixels-npixels);  /* clear to EOBuffer */
  1422.   }
  1423.  
  1424.   if (fp != stdin) fclose(fp);
  1425.  
  1426.   return 0;
  1427. }
  1428.  
  1429.  
  1430. /* Fetch the next code from the raster data stream.  The codes can be
  1431.  * any length from 3 to 12 bits, packed into 8-bit bytes, so we have to
  1432.  * maintain our location in the Raster array as a BIT Offset.  We compute
  1433.  * the byte Offset into the raster array by dividing this by 8, pick up
  1434.  * three bytes, compute the bit Offset into our 24-bit chunk, shift to
  1435.  * bring the desired code to the bottom, then mask it off and return it. 
  1436.  */
  1437.  
  1438. static int ReadCode()
  1439. {
  1440.   int RawCode, ByteOffset;
  1441.   
  1442.   ByteOffset = BitOffset / 8;
  1443.   RawCode = Raster[ByteOffset] + (Raster[ByteOffset + 1] << 8);
  1444.   if (CodeSize >= 8)
  1445.     RawCode += (Raster[ByteOffset + 2] << 16);
  1446.   RawCode >>= (BitOffset % 8);
  1447.   BitOffset += CodeSize;
  1448.  
  1449.   return(RawCode & ReadMask);
  1450. }
  1451.  
  1452.  
  1453. /***************************/
  1454. static void DoInterlace(Index)
  1455.      byte Index;
  1456. {
  1457.   static byte *ptr = NULL;
  1458.   static int   oldYC = -1;
  1459.   
  1460.   if (oldYC != YC) {  ptr = pic + YC * Width;  oldYC = YC; }
  1461.   
  1462.   if (YC<Height)
  1463.     *ptr++ = Index;
  1464.   
  1465.   /* Update the X-coordinate, and if it overflows, update the Y-coordinate */
  1466.   
  1467.   if (++XC == Width) {
  1468.     
  1469.     /* deal with the interlace as described in the GIF
  1470.      * spec.  Put the decoded scan line out to the screen if we haven't gone
  1471.      * past the bottom of it
  1472.      */
  1473.     
  1474.     XC = 0;
  1475.     
  1476.     switch (Pass) {
  1477.     case 0:
  1478.       YC += 8;
  1479.       if (YC >= Height) { Pass++; YC = 4; }
  1480.       break;
  1481.       
  1482.     case 1:
  1483.       YC += 8;
  1484.       if (YC >= Height) { Pass++; YC = 2; }
  1485.       break;
  1486.       
  1487.     case 2:
  1488.       YC += 4;
  1489.       if (YC >= Height) { Pass++; YC = 1; }
  1490.       break;
  1491.       
  1492.     case 3:
  1493.       YC += 2;  break;
  1494.       
  1495.     default:
  1496.       break;
  1497.     }
  1498.   }
  1499. }
  1500.  
  1501.  
  1502.       
  1503. /*****************************/
  1504. static int GifError(st)
  1505.      char *st;
  1506. {
  1507.   fprintf(stderr,"%s: LoadGIF() - %s\n",cmd,st);
  1508.   
  1509.   if (RawGIF != NULL) free(RawGIF);
  1510.   if (Raster != NULL) free(Raster);
  1511.   if (pic    != NULL) free(pic);
  1512.   
  1513.   return -1;
  1514. }
  1515.  
  1516. \BARFOO\
  1517. else
  1518.   echo "will not over write ./xvgif.c"
  1519. fi
  1520. if `test ! -s ./xvgifwr.c`
  1521. then
  1522. echo "writting ./xvgifwr.c"
  1523. cat > ./xvgifwr.c << '\BARFOO\'
  1524. /*
  1525.  * xvgifwr.c  -  handles writing of GIF files.  based on flgife.c and
  1526.  *               flgifc.c from the FBM Library, by Michael Maudlin
  1527.  *
  1528.  * Contains: 
  1529.  *   WriteGIF(fp, pic, w, h, rmap, gmap, bmap, numcols, colorstyle)
  1530.  *
  1531.  * Note: slightly brain-damaged, in that it'll only write non-interlaced 
  1532.  *       GIF files (in the interests of speed, or something)
  1533.  *
  1534.  */
  1535.  
  1536.  
  1537.  
  1538. /*****************************************************************
  1539.  * Portions of this code Copyright (C) 1989 by Michael Mauldin.
  1540.  * Permission is granted to use this file in whole or in part provided
  1541.  * that you do not sell it for profit and that this copyright notice
  1542.  * and the names of all authors are retained unchanged.
  1543.  *
  1544.  * Authors:  Michael Mauldin (mlm@cs.cmu.edu)
  1545.  *           David Rowley (mgardi@watdcsu.waterloo.edu)
  1546.  *
  1547.  * Based on: compress.c - File compression ala IEEE Computer, June 1984.
  1548.  *
  1549.  *    Spencer W. Thomas       (decvax!harpo!utah-cs!utah-gr!thomas)
  1550.  *    Jim McKie               (decvax!mcvax!jim)
  1551.  *    Steve Davies            (decvax!vax135!petsd!peora!srd)
  1552.  *    Ken Turkowski           (decvax!decwrl!turtlevax!ken)
  1553.  *    James A. Woods          (decvax!ihnp4!ames!jaw)
  1554.  *    Joe Orost               (decvax!vax135!petsd!joe)
  1555.  *****************************************************************/
  1556.  
  1557. /*
  1558.  * Copyright 1989, 1990 by the University of Pennsylvania
  1559.  *
  1560.  * Permission to use, copy, and distribute for non-commercial purposes,
  1561.  * is hereby granted without fee, providing that the above copyright
  1562.  * notice appear in all copies and that both the copyright notice and this
  1563.  * permission notice appear in supporting documentation.
  1564.  *
  1565.  * The software may be modified for your own purposes, but modified versions
  1566.  * may not be distributed.
  1567.  *
  1568.  * This software is provided "as is" without any express or implied warranty.
  1569.  */
  1570.  
  1571.  
  1572. #include "xv.h"
  1573.  
  1574. typedef long int        count_int;
  1575.  
  1576. static int  Width, Height;
  1577. static int  curx, cury;
  1578. static long CountDown;
  1579. static int  Interlace;
  1580. static byte bw[2] = {0, 0xff};
  1581.  
  1582. #ifdef __STDC__
  1583. static void putword(int, FILE *);
  1584. static void compress(int, FILE *, byte *, int);
  1585. static void output(int);
  1586. static void cl_block(void);
  1587. static void cl_hash(count_int);
  1588. static void char_init(void);
  1589. static void char_out(int);
  1590. static void flush_char(void);
  1591. #else
  1592. static void putword(), compress(), output(), cl_block(), cl_hash();
  1593. static void char_init(), char_out(), flush_char();
  1594. #endif
  1595.  
  1596. /*************************************************************/
  1597. int WriteGIF(fp, pic, w, h, rmap, gmap, bmap, numcols, colorstyle)
  1598. FILE *fp;
  1599. byte *pic;
  1600. int   w,h;
  1601. byte *rmap, *gmap, *bmap;
  1602. int   numcols, colorstyle;
  1603. {
  1604.   int RWidth, RHeight;
  1605.   int LeftOfs, TopOfs;
  1606.   int Resolution, ColorMapSize, InitCodeSize, Background, BitsPerPixel;
  1607.   int i,j;
  1608.  
  1609.  
  1610.   /* if writing B/W stipple... */
  1611.   if (colorstyle==2) {
  1612.     rmap = gmap = bmap = bw;
  1613.     numcols = 2;
  1614.   }
  1615.  
  1616.   Interlace = 0;
  1617.   Background = 0;
  1618.  
  1619.   /* figure out 'BitsPerPixel' */
  1620.   for (i=1; i<8; i++)
  1621.     if ( (1<<i) >= numcols) break;
  1622.   
  1623.   BitsPerPixel = i;
  1624.  
  1625.   ColorMapSize = 1 << BitsPerPixel;
  1626.     
  1627.   RWidth  = Width  = w;
  1628.   RHeight = Height = h;
  1629.   LeftOfs = TopOfs = 0;
  1630.     
  1631.   Resolution = BitsPerPixel;
  1632.  
  1633.   CountDown = w * h;    /* # of pixels we'll be doing */
  1634.  
  1635.   if (BitsPerPixel <= 1) InitCodeSize = 2;
  1636.                     else InitCodeSize = BitsPerPixel;
  1637.  
  1638.   curx = cury = 0;
  1639.  
  1640.   if (!fp) {
  1641.     fprintf(stderr,  "WriteGIF: file not open for writing\n" );
  1642.     return (1);
  1643.   }
  1644.  
  1645.   if (DEBUG) 
  1646.     fprintf(stderr,"WrGIF: pic=%lx, w,h=%dx%d, numcols=%d, Bits%d,Cmap=%d\n",
  1647.         pic, w,h,numcols,BitsPerPixel,ColorMapSize);
  1648.  
  1649.   fwrite("GIF87a", 1, 6, fp);    /* the GIF magic number */
  1650.  
  1651.   putword(RWidth, fp);           /* screen descriptor */
  1652.   putword(RHeight, fp);
  1653.  
  1654.   i = 0x80;                     /* Yes, there is a color map */
  1655.   i |= (8-1)<<4;                 /* OR in the color resolution (hardwired 8) */
  1656.   i |= (BitsPerPixel - 1);       /* OR in the # of bits per pixel */
  1657.   fputc(i,fp);          
  1658.  
  1659.   fputc(Background, fp);         /* background color */
  1660.  
  1661.   fputc(0, fp);                  /* future expansion byte */
  1662.  
  1663.  
  1664.   if (colorstyle == 1) {         /* greyscale */
  1665.     for (i=0; i<ColorMapSize; i++) {
  1666.       j = MONO(rmap[i], gmap[i], bmap[i]);
  1667.       fputc(j, fp);
  1668.       fputc(j, fp);
  1669.       fputc(j, fp);
  1670.     }
  1671.   }
  1672.   else {
  1673.     for (i=0; i<ColorMapSize; i++) {       /* write out Global colormap */
  1674.       fputc(rmap[i], fp);
  1675.       fputc(gmap[i], fp);
  1676.       fputc(bmap[i], fp);
  1677.     }
  1678.   }
  1679.  
  1680.   fputc( ',', fp );              /* image separator */
  1681.  
  1682.   /* Write the Image header */
  1683.   putword(LeftOfs, fp);
  1684.   putword(TopOfs,  fp);
  1685.   putword(Width,   fp);
  1686.   putword(Height,  fp);
  1687.   if (Interlace) fputc(0x40, fp);   /* Use Global Colormap, maybe Interlace */
  1688.             else fputc(0x00, fp);
  1689.  
  1690.   fputc(InitCodeSize, fp);
  1691.   compress(InitCodeSize+1, fp, pic, w*h);
  1692.  
  1693.   fputc(0,fp);                      /* Write out a Zero-length packet (EOF) */
  1694.   fputc(';',fp);                    /* Write GIF file terminator */
  1695.  
  1696.   return (0);
  1697. }
  1698.  
  1699.  
  1700.  
  1701.  
  1702. /******************************/
  1703. static void putword(w, fp)
  1704. int w;
  1705. FILE *fp;
  1706. {
  1707.   /* writes a 16-bit integer in GIF order (LSB first) */
  1708.   fputc(w & 0xff, fp);
  1709.   fputc((w>>8)&0xff, fp);
  1710. }
  1711.  
  1712.  
  1713.  
  1714.  
  1715. /***********************************************************************/
  1716.  
  1717.  
  1718. static unsigned long cur_accum = 0;
  1719. static int           cur_bits = 0;
  1720.  
  1721.  
  1722.  
  1723.  
  1724. #define min(a,b)        ((a>b) ? b : a)
  1725.  
  1726. #define BITS    12
  1727. #define MSDOS    1
  1728.  
  1729. #define HSIZE  5003            /* 80% occupancy */
  1730.  
  1731. typedef unsigned char   char_type;
  1732.  
  1733.  
  1734. static int n_bits;                   /* number of bits/code */
  1735. static int maxbits = BITS;           /* user settable max # bits/code */
  1736. static int maxcode;                  /* maximum code, given n_bits */
  1737. static int maxmaxcode = 1 << BITS;   /* NEVER generate this */
  1738.  
  1739. #define MAXCODE(n_bits)     ( (1 << (n_bits)) - 1)
  1740.  
  1741. static  count_int      htab [HSIZE];
  1742. static  unsigned short codetab [HSIZE];
  1743. #define HashTabOf(i)   htab[i]
  1744. #define CodeTabOf(i)   codetab[i]
  1745.  
  1746. static int hsize = HSIZE;            /* for dynamic table sizing */
  1747.  
  1748. /*
  1749.  * To save much memory, we overlay the table used by compress() with those
  1750.  * used by decompress().  The tab_prefix table is the same size and type
  1751.  * as the codetab.  The tab_suffix table needs 2**BITS characters.  We
  1752.  * get this from the beginning of htab.  The output stack uses the rest
  1753.  * of htab, and contains characters.  There is plenty of room for any
  1754.  * possible stack (stack used to be 8000 characters).
  1755.  */
  1756.  
  1757. #define tab_prefixof(i) CodeTabOf(i)
  1758. #define tab_suffixof(i)        ((char_type *)(htab))[i]
  1759. #define de_stack               ((char_type *)&tab_suffixof(1<<BITS))
  1760.  
  1761. static int free_ent = 0;                  /* first unused entry */
  1762.  
  1763. /*
  1764.  * block compression parameters -- after all codes are used up,
  1765.  * and compression rate changes, start over.
  1766.  */
  1767. static int clear_flg = 0;
  1768.  
  1769. static long int in_count = 1;            /* length of input */
  1770. static long int out_count = 0;           /* # of codes output (for debugging) */
  1771.  
  1772. /*
  1773.  * compress stdin to stdout
  1774.  *
  1775.  * Algorithm:  use open addressing double hashing (no chaining) on the 
  1776.  * prefix code / next character combination.  We do a variant of Knuth's
  1777.  * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
  1778.  * secondary probe.  Here, the modular division first probe is gives way
  1779.  * to a faster exclusive-or manipulation.  Also do block compression with
  1780.  * an adaptive reset, whereby the code table is cleared when the compression
  1781.  * ratio decreases, but after the table fills.  The variable-length output
  1782.  * codes are re-sized at this point, and a special CLEAR code is generated
  1783.  * for the decompressor.  Late addition:  construct the table according to
  1784.  * file size for noticeable speed improvement on small files.  Please direct
  1785.  * questions about this implementation to ames!jaw.
  1786.  */
  1787.  
  1788. static int g_init_bits;
  1789. static FILE *g_outfile;
  1790.  
  1791. static int ClearCode;
  1792. static int EOFCode;
  1793.  
  1794.  
  1795. /********************************************************/
  1796. static void compress(init_bits, outfile, data, len)
  1797. int   init_bits;
  1798. FILE *outfile;
  1799. byte *data;
  1800. int   len;
  1801. {
  1802.   register long fcode;
  1803.   register int i = 0;
  1804.   register int c;
  1805.   register int ent;
  1806.   register int disp;
  1807.   register int hsize_reg;
  1808.   register int hshift;
  1809.  
  1810.   /*
  1811.    * Set up the globals:  g_init_bits - initial number of bits
  1812.    *                      g_outfile   - pointer to output file
  1813.    */
  1814.   g_init_bits = init_bits;
  1815.   g_outfile   = outfile;
  1816.  
  1817.   /* initialize 'compress' globals */
  1818.   maxbits = BITS;
  1819.   maxmaxcode = 1<<BITS;
  1820.   memset((char *) htab, 0, sizeof(htab));
  1821.   memset((char *) codetab, 0, sizeof(codetab));
  1822.   hsize = HSIZE;
  1823.   free_ent = 0;
  1824.   clear_flg = 0;
  1825.   in_count = 1;
  1826.   out_count = 0;
  1827.   cur_accum = 0;
  1828.   cur_bits = 0;
  1829.  
  1830.  
  1831.   /*
  1832.    * Set up the necessary values
  1833.    */
  1834.   out_count = 0;
  1835.   clear_flg = 0;
  1836.   in_count = 1;
  1837.   maxcode = MAXCODE(n_bits = g_init_bits);
  1838.  
  1839.   ClearCode = (1 << (init_bits - 1));
  1840.   EOFCode = ClearCode + 1;
  1841.   free_ent = ClearCode + 2;
  1842.  
  1843.   char_init();
  1844.   ent = *data++;  len--;
  1845.  
  1846.   hshift = 0;
  1847.   for ( fcode = (long) hsize;  fcode < 65536L; fcode *= 2L )
  1848.     hshift++;
  1849.   hshift = 8 - hshift;                /* set hash code range bound */
  1850.  
  1851.   hsize_reg = hsize;
  1852.   cl_hash( (count_int) hsize_reg);            /* clear hash table */
  1853.  
  1854.   output(ClearCode);
  1855.     
  1856.   while (len) {
  1857.     c = *data++;  len--;
  1858.     in_count++;
  1859.  
  1860.     fcode = (long) ( ( (long) c << maxbits) + ent);
  1861.     i = (((int) c << hshift) ^ ent);    /* xor hashing */
  1862.  
  1863.     if ( HashTabOf (i) == fcode ) {
  1864.       ent = CodeTabOf (i);
  1865.       continue;
  1866.     }
  1867.  
  1868.     else if ( (long)HashTabOf (i) < 0 )      /* empty slot */
  1869.       goto nomatch;
  1870.  
  1871.     disp = hsize_reg - i;           /* secondary hash (after G. Knott) */
  1872.     if ( i == 0 )
  1873.       disp = 1;
  1874.  
  1875. probe:
  1876.     if ( (i -= disp) < 0 )
  1877.       i += hsize_reg;
  1878.  
  1879.     if ( HashTabOf (i) == fcode ) {
  1880.       ent = CodeTabOf (i);
  1881.       continue;
  1882.     }
  1883.  
  1884.     if ( (long)HashTabOf (i) > 0 ) 
  1885.       goto probe;
  1886.  
  1887. nomatch:
  1888.     output(ent);
  1889.     out_count++;
  1890.     ent = c;
  1891.  
  1892.     if ( free_ent < maxmaxcode ) {
  1893.       CodeTabOf (i) = free_ent++; /* code -> hashtable */
  1894.       HashTabOf (i) = fcode;
  1895.     }
  1896.     else
  1897.       cl_block();
  1898.   }
  1899.  
  1900.   /* Put out the final code */
  1901.   output(ent);
  1902.   out_count++;
  1903.   output(EOFCode);
  1904. }
  1905.  
  1906.  
  1907. /*****************************************************************
  1908.  * TAG( output )
  1909.  *
  1910.  * Output the given code.
  1911.  * Inputs:
  1912.  *      code:   A n_bits-bit integer.  If == -1, then EOF.  This assumes
  1913.  *              that n_bits =< (long)wordsize - 1.
  1914.  * Outputs:
  1915.  *      Outputs code to the file.
  1916.  * Assumptions:
  1917.  *      Chars are 8 bits long.
  1918.  * Algorithm:
  1919.  *      Maintain a BITS character long buffer (so that 8 codes will
  1920.  * fit in it exactly).  Use the VAX insv instruction to insert each
  1921.  * code in turn.  When the buffer fills up empty it and start over.
  1922.  */
  1923.  
  1924. static
  1925. unsigned long masks[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F,
  1926.                                   0x001F, 0x003F, 0x007F, 0x00FF,
  1927.                                   0x01FF, 0x03FF, 0x07FF, 0x0FFF,
  1928.                                   0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF };
  1929.  
  1930. static void output(code)
  1931. int code;
  1932. {
  1933.   cur_accum &= masks[cur_bits];
  1934.  
  1935.   if (cur_bits > 0)
  1936.     cur_accum |= ((long)code << cur_bits);
  1937.   else
  1938.     cur_accum = code;
  1939.     
  1940.   cur_bits += n_bits;
  1941.  
  1942.   while( cur_bits >= 8 ) {
  1943.     char_out( (unsigned int) (cur_accum & 0xff) );
  1944.     cur_accum >>= 8;
  1945.     cur_bits -= 8;
  1946.   }
  1947.  
  1948.   /*
  1949.    * If the next entry is going to be too big for the code size,
  1950.    * then increase it, if possible.
  1951.    */
  1952.  
  1953.   if (free_ent > maxcode || clear_flg) {
  1954.  
  1955.     if( clear_flg ) {
  1956.       maxcode = MAXCODE (n_bits = g_init_bits);
  1957.       clear_flg = 0;
  1958.     }
  1959.     else {
  1960.       n_bits++;
  1961.       if ( n_bits == maxbits )
  1962.     maxcode = maxmaxcode;
  1963.       else
  1964.     maxcode = MAXCODE(n_bits);
  1965.     }
  1966.   }
  1967.     
  1968.   if( code == EOFCode ) {
  1969.     /* At EOF, write the rest of the buffer */
  1970.     while( cur_bits > 0 ) {
  1971.       char_out( (unsigned int)(cur_accum & 0xff) );
  1972.       cur_accum >>= 8;
  1973.       cur_bits -= 8;
  1974.     }
  1975.  
  1976.     flush_char();
  1977.     
  1978.     fflush( g_outfile );
  1979.  
  1980.     if( ferror( g_outfile ) )
  1981.       FatalError("unable to write GIF file");
  1982.   }
  1983. }
  1984.  
  1985.  
  1986. /********************************/
  1987. static void cl_block ()             /* table clear for block compress */
  1988. {
  1989.   /* Clear out the hash table */
  1990.  
  1991.   cl_hash ( (count_int) hsize );
  1992.   free_ent = ClearCode + 2;
  1993.   clear_flg = 1;
  1994.  
  1995.   output(ClearCode);
  1996. }
  1997.  
  1998.  
  1999. /********************************/
  2000. static void cl_hash(hsize)          /* reset code table */
  2001. register count_int hsize;
  2002. {
  2003.   register count_int *htab_p = htab+hsize;
  2004.   register long i;
  2005.   register long m1 = -1;
  2006.  
  2007.   i = hsize - 16;
  2008.   do {                            /* might use Sys V memset(3) here */
  2009.     *(htab_p-16) = m1;
  2010.     *(htab_p-15) = m1;
  2011.     *(htab_p-14) = m1;
  2012.     *(htab_p-13) = m1;
  2013.     *(htab_p-12) = m1;
  2014.     *(htab_p-11) = m1;
  2015.     *(htab_p-10) = m1;
  2016.     *(htab_p-9) = m1;
  2017.     *(htab_p-8) = m1;
  2018.     *(htab_p-7) = m1;
  2019.     *(htab_p-6) = m1;
  2020.     *(htab_p-5) = m1;
  2021.     *(htab_p-4) = m1;
  2022.     *(htab_p-3) = m1;
  2023.     *(htab_p-2) = m1;
  2024.     *(htab_p-1) = m1;
  2025.     htab_p -= 16;
  2026.   } while ((i -= 16) >= 0);
  2027.  
  2028.   for ( i += 16; i > 0; i-- )
  2029.     *--htab_p = m1;
  2030. }
  2031.  
  2032.  
  2033. /******************************************************************************
  2034.  *
  2035.  * GIF Specific routines
  2036.  *
  2037.  ******************************************************************************/
  2038.  
  2039. /*
  2040.  * Number of characters so far in this 'packet'
  2041.  */
  2042. static int a_count;
  2043.  
  2044. /*
  2045.  * Set up the 'byte output' routine
  2046.  */
  2047. static void char_init()
  2048. {
  2049.     a_count = 0;
  2050. }
  2051.  
  2052. /*
  2053.  * Define the storage for the packet accumulator
  2054.  */
  2055. static char accum[ 256 ];
  2056.  
  2057. /*
  2058.  * Add a character to the end of the current packet, and if it is 254
  2059.  * characters, flush the packet to disk.
  2060.  */
  2061. static void char_out(c)
  2062. int c;
  2063. {
  2064.   accum[ a_count++ ] = c;
  2065.   if( a_count >= 254 ) 
  2066.     flush_char();
  2067. }
  2068.  
  2069. /*
  2070.  * Flush the packet to disk, and reset the accumulator
  2071.  */
  2072. static void flush_char()
  2073. {
  2074.   if( a_count > 0 ) {
  2075.     fputc( a_count, g_outfile );
  2076.     fwrite( accum, 1, a_count, g_outfile );
  2077.     a_count = 0;
  2078.   }
  2079. }    
  2080. \BARFOO\
  2081. else
  2082.   echo "will not over write ./xvgifwr.c"
  2083. fi
  2084. echo "Finished archive 6 of 10"
  2085. exit
  2086.  
  2087. dan
  2088. ----------------------------------------------------
  2089. O'Reilly && Associates   argv@sun.com / argv@ora.com
  2090. Opinions expressed reflect those of the author only.
  2091. --
  2092. dan
  2093. ----------------------------------------------------
  2094. O'Reilly && Associates   argv@sun.com / argv@ora.com
  2095. Opinions expressed reflect those of the author only.
  2096.