 /*
  * Khoros: $Id: lverrdif.c,v 1.1 1991/05/10 15:41:54 khoros Exp $
  */

#if !defined(lint) && !defined(SABER)
static char rcsid[] = "Khoros: $Id: lverrdif.c,v 1.1 1991/05/10 15:41:54 khoros Exp $";
#endif

 /*
  * $Log: lverrdif.c,v $
 * Revision 1.1  1991/05/10  15:41:54  khoros
 * Initial revision
 *
  */ 

/*
 *----------------------------------------------------------------------
 *
 * Copyright 1991, University of New Mexico.  All rights reserved.
 * Permission to copy and modify this software and its documen-
 * tation only for internal use in your organization is hereby
 * granted, provided that this notice is retained thereon and
 * on all copies.  UNM makes no representations as too the sui-
 * tability and operability of this software for any purpose.
 * It is provided "as is" without express or implied warranty.
 * 
 * UNM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FIT-
 * NESS.  IN NO EVENT SHALL UNM BE LIABLE FOR ANY SPECIAL,
 * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY OTHER DAMAGES WHAT-
 * SOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PER-
 * FORMANCE OF THIS SOFTWARE.
 * 
 * No other rights, including for example, the right to redis-
 * tribute this software and its documentation or the right to
 * prepare derivative works, are granted unless specifically
 * provided in a separate license agreement.
 *---------------------------------------------------------------------
 */

#include "unmcopyright.h"        /* Copyright 1991 by UNM */

/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
 >>>>
 >>>>         File Name: lverrdif.c
 >>>>
 >>>>      Program Name: verrdif
 >>>>
 >>>> Date Last Updated: Thu Mar 28 00:08:44 1991 
 >>>>
 >>>>          Routines: lverrdif - the library call for verrdif
 >>>>
 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/


#include "vinclude.h"


/* -library_includes */
/* Definition of min,max finders */
#define min2(x,y)       (((x) < (y)) ? (x) : (y))
#define max2(x,y)       (((x) > (y)) ? (x) : (y))
#define min3(a,b,c)     (min2(a,min2(b,c)))
#define max3(a,b,c)     (max2(a,max2(b,c)))
#define min5(a,b,c,d,e) (min2(min3(a,b,c),min2(d,e)))
#define max5(a,b,c,d,e) (max2(max3(a,b,c),max2(d,e)))
/* -library_includes_end */


/****************************************************************
*
* Routine Name: lverrdif - library call for verrdif
*
* Purpose:
*    
*    Perform dithering by four-direction error diffusion.
*    
*    
* Input:
*    
*    image          xvimage structure of the  character  image  to  be
*                   dithered by error diffusion.
*    
*    
* Output:
*    
*    image          holds the result of the dithered image.
*    
*    Return Value:  1 on success, 0 on failure.
*    
*    
*
* Written By: Scott Wilson
*    
*    Marcelo Teran, Mark Young
*    
*    
****************************************************************/


/* -library_def */
int
lverrdif(image)
struct xvimage *image;
/* -library_def_end */

/* -library_code */
{
    int  i,j,nr,nc,k,bmsize,err,x,backoff,minimum,maximum,diff;
    unsigned char *r1,*r2,*bptr,*b,bit,*p, minx, minz, maxx, maxz;

    if (image->data_storage_type != VFF_TYP_1_BYTE)
    {
       (void) fprintf(stderr,"lverrdif: ");
       (void) fprintf(stderr,"sorry can only dither byte images.\n");
       return(0);
    }

    nr = image->col_size;                     /* Get size of image */
    nc = image->row_size;

    r1 = (unsigned char *)malloc(nc+1);
    r2 = (unsigned char *)malloc(nc+1);
    if (r1 == NULL || r2 == NULL)
    {
        fprintf(stderr,"lverrdif: unable to allocate enough memory!\n");
        return(0);
    }

    p = (unsigned char *)image->imagedata;    /* Find the image data*/

    for(i=0; i<nc; i++)  r1[i] = p[i];        /* Get first row */

    for(j=1; j<nr; j++)                       /* Process remaining rows */
      {
        for(i=0; i<nc; i++) r2[i] = p[j*nc+i]; /* Suck in a row */
        for(i=0; i<nc; i++)
          {
            if (i && i < (nc-1))
              {
                /*
                 *  These lines are commented out and replaced with the
                 *  following if/else(s).  This was done since Ultrix 2.2
                 *  kept crashing at compile time with "out of tree space".
                 */
/* minimum = min5(r1[i],r2[i],r2[i+1],r1[i+1],r2[i-1]); */
/* maximum = max5(r1[i],r2[i],r2[i+1],r1[i+1],r2[i-1]); */

                minx = min2(r1[i],r2[i]);
                minz = min3(r2[i+1],r1[i+1],r2[i-1]);
                if (minx < minz)
                   minimum = min2(r1[i],r2[i]);
                else
                   minimum = min3(r2[i+1],r1[i+1],r2[i-1]);

                maxx = max2(r1[i],r2[i]);
                maxz = max3(r2[i+1],r1[i+1],r2[i-1]);
                if (maxx > maxz)
                   maximum = max2(r1[i],r2[i]);
                else
                   maximum = max3(r2[i+1],r1[i+1],r2[i-1]);

                diff = maximum - minimum;
              }
            else diff = 0;

            if (diff >= 0 && diff < 20) backoff = diff/2;
            else if (diff >= 20 && diff < 50) backoff = 5*diff/6 - 7;
            else if (diff >= 50 && diff < 100) backoff = 3*diff/10 + 20;
            else if (diff >= 100) backoff = 50;

            if (r1[i] > 128) 
              {
                p[j*nc+i] = 255;
                x = 255-backoff; 
              }
            else
              {
                p[j*nc+i] = 0;
                x = backoff; 
              }
            err = r1[i]-x;

            if (i < (nc-1)) r1[i+1] += (7*err) >> 4; /* Spread east */
            if (i < (nc-1)) r2[i+1] += (1*err) >> 4; /* Spread southeast */
            if (i) r2[i-1] += (3*err) >> 4;          /* Spread southwest */
            r2[i] += (5*err) >> 4;                   /* Spread south */
          }
        for(i=0; i<nc; i++) r1[i] = r2[i];    /* Save current row */
      }
    bmsize = ((image->row_size + 7)/8)*image->col_size;
    bptr = (unsigned char *)malloc(bmsize);
    if (bptr == NULL ) 
    {
        fprintf(stderr,"lverrdif: unable to allocate enough memory!\n");
        return(0);
    }
    b = bptr;
    p = (unsigned char *)(image->imagedata);
    for (i=0; i<image->col_size; i++)
      {
        k = 0;
        for (j=0; j<image->row_size; j++)
          {
            bit = 1 << k;      /* Bit to set or clear */
            if (*p++ > 128) *b = *b | bit;
            else *b = *b & ~bit;
            if (k == 7)
              {
                k = 0;
                b++;
              }
            else k++;
          }
        if (k != 0)
          {
            for (j=k; j<8; j++) *b = *b & (~(1 << j));
            b++;
          }
      }
    image->imagedata = (char *)bptr;
    image->data_storage_type =  VFF_TYP_BIT;

    return(1);   /* Successful return */
}
/* -library_code_end */
