 /*
  * Khoros: $Id: lvdyth.c,v 1.3 1992/03/20 23:05:14 dkhoros Exp $
  */

#if !defined(lint) && !defined(SABER)
static char rcsid[] = "Khoros: $Id: lvdyth.c,v 1.3 1992/03/20 23:05:14 dkhoros Exp $";
#endif

 /*
  * $Log: lvdyth.c,v $
 * Revision 1.3  1992/03/20  23:05:14  dkhoros
 * VirtualPatch5
 *
  */

/*
 *----------------------------------------------------------------------
 *
 * Copyright 1992, 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 to 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 1992 by UNM */

/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
 >>>>
 >>>>         File Name: lvdyth.c
 >>>>
 >>>>      Program Name: vdyth
 >>>>
 >>>> Date Last Updated: Fri Feb 28 18:42:00 1992 
 >>>>
 >>>>          Routines: lvdyth - the library call for vdyth
 >>>>
 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/


#include "vinclude.h"


/* -library_includes */
/* -library_includes_end */


/****************************************************************
*
* Routine Name: lvdyth - library call for vdyth
*
* Purpose:
*    
*    Perform dynamic thresholding on an image.
*    
*    

* Input:
*    
*         image -- xvimage structure
*         wsize -- window width argument
*         hsize -- window height argument
*         type  -- type of thresholding  (0=median, 1=mean)
*         value -- non zero output pixel value
*    
*    

* Output:
*    
*         image -- holds the result of the thresholded
*                image
*    
*         image is used for both the input xvimage structure  and  the
*         output  result  xvimage  structure.   This  is  done to save
*         space, but you must be careful not  to  overwrite  important
*         data.
*    
*         lvdyth returns 1 on success and 0 on failure.
*    
*    

*
* Written By: Marcelo Teran, Ramiro Jordan
*    
*    John Rasure on Fri Feb 28 18:41:18 MST  1992  fixed  several
*    indexing bugs and array bound problems.
*    
*    

****************************************************************/


/* -library_def */
int
lvdyth(img,wsize,hsize,type,value)
struct xvimage *img;
int wsize, hsize, type, value;
/* -library_def_end */

/* -library_code */
{

    int row,                            /* points image row */ 
        col,                            /* points image col */ 
        th,                             /* gives the mediun of the wind. */
        tmdn,                           /* numb of pixels <= median */ 
        g1,                             /* auxiliar variable */
        xoff,                           /* horiz. offset in the img */
        yoff,                           /* vertic. offset in the img */
        xend,                           /* step in img up to here */
        yend,                           /* step in img up to here */
        mdn,                            /* this is the median value */
        nc,                             /* column size of image */
        nr,                             /* row size of image */
        index,                          /* window counter */
        i, j;                           /* general counters */

    unsigned int hist[256];             /* holds histogram of window */

    unsigned char *ptr,                 /* pointer to the image data char */
                  *result;              /* pointer to resulting image char */

    char  *program;                     /* contains the name of the library */

    program = "lvdyth";

    propertype(program,img,VFF_TYP_1_BYTE,1);         /* check img. type */     

    th = wsize * hsize / 2;

    nr = img->col_size;
    nc = img->row_size;

    xend = nc / wsize;
    yend = nr / hsize;
    tmdn = 0; mdn = 0;

   /* Zero histogram */
    bzero((char *) hist, 256 * sizeof(unsigned int));

   /* Allocate space for resulting image */ 
    result = (unsigned char *)malloc((unsigned int)nc*nr*sizeof(unsigned char));
    if(result == NULL) {
        (void) fprintf(stderr,"lvhmed: insufficient memory available\n");
        return(0);
    }

   /* Assign image data address to ptr */
    ptr = (unsigned char *)img->imagedata;

   /* perform dynamic thresholding on an image */
    for (row = 0 ; row < yend; row++){

       /* step along the image rows */
        for(col = 0; col < xend; col++){ 

            for(i = 0; i < hsize; i++){
                for(j = 0; j < wsize; j++){
                    index = row*hsize*nc + col*wsize + i*nc + j;
                    if(type == 0){
                        g1 = ptr[index];
                        hist[g1]++;
                    } else {
                        g1 += ptr[index];
                    }
                }
            }
            if(type == 0){
               /* get the median value */
                if(tmdn > th){
                    do {
                        mdn = mdn - 1;
                        tmdn = tmdn - hist[mdn];
                    } while(tmdn > th && mdn > 0);
                } else {
                    while( mdn < 256 && (tmdn + hist[mdn] <= th) ){
                        tmdn = tmdn + hist[mdn];
                        mdn = mdn + 1;
                    }
                }
               /* Reset histogram and variables */
                bzero((char *) hist, 256 * sizeof(unsigned int));
                tmdn = 0;
            } else {
                mdn = g1 / (wsize * hsize);
            }

           /* write the new values for the image */
            for(i = 0; i < hsize; i++){
                for(j = 0; j < wsize; j++){
                    index = row*hsize*nc + col*wsize + i*nc + j;
                    if(ptr[index] > mdn)
                        result[index] = value;
                }
            }
            mdn = 0; g1 = 0;
        }
    }

    if(nc != wsize*xend){
       /* step thru the lateral remaining side */
        yoff = nc - wsize;
        for(row = 0; row < yend; row++){
            for(i = 0; i < hsize; i++){
                for(j = 0; j < wsize; j++){
                    index = yoff + row*hsize*nc + i*nc + j;
                    if(type == 0){
                        g1 = ptr[index];
                        hist[g1]++;
                    } else {
                        g1 += ptr[index];
                    }
                }
            }

            if(type == 0){
           /* get the median value */
                if(tmdn > th){
                    do {
                        mdn = mdn - 1;
                        tmdn = tmdn - hist[mdn];
                    } while(tmdn > th && mdn > 0);
                } else {
                    while( mdn < 256 && (tmdn + hist[mdn] <= th) ){
                        tmdn = tmdn + hist[mdn];
                        mdn = mdn + 1;
                    }
                }
               /* Reset histogram and variables */
                bzero((char *) hist, 256 * sizeof(unsigned int));
                tmdn = 0;
            } else {
           /* get the mean value */
                mdn = g1 / (wsize * hsize);
            }

           /* write the new values for the image */
            for(i = 0; i < hsize; i++){
                for(j = 0; j < wsize; j++){
                    index = yoff + row*hsize*nc + i*nc + j;
                    if(ptr[index] > mdn)
                        result[index] = value;
                }
            }
        }
    }

    if(nr != yend*hsize){
       /* step thru the bottom remaining part */
        xoff = (nr - hsize) * nc;
        for(col = 0; col < xend; col++){
            /* xoff = (nr - hsize) * nr;  Rasure */
            for(i = 0; i < hsize; i++){
                for(j = 0; j < wsize; j++){
                    index = xoff + col*wsize + i*nc + j;
                    if(type == 0){
                        g1 = ptr[index];
                        hist[g1]++;
                    } else {
                        g1 += ptr[index];
                    }
                }
            }

            if(type == 0){
               /* get the median value */
                if(tmdn > th){
                    do {
                        mdn = mdn - 1;
                        tmdn = tmdn - hist[mdn];
                    } while(tmdn > th && mdn >0);
                } else {
                    while( mdn < 256 && (tmdn + hist[mdn] <= th) ){
                        tmdn = tmdn + hist[mdn];
                        mdn = mdn + 1;
                    }
                }
               /* Reset histogram and variables */
                bzero((char *) hist, 256 * sizeof(unsigned int));
                tmdn = 0;
            } else {
               /* get the mean value */
                mdn = g1 / (wsize * hsize);
            }

       /* write the new values for the image */
            for(i = 0; i < hsize; i++){
                for(j = 0; j < wsize; j++){
                    /* index = xoff + row*hsize*nc + i*nc + j; 
                        seemed like Marcelo yanked the
                        wrong piece of code - John Rasure */
                    index = xoff + col*wsize + i*nc + j;
                    if(ptr[index] > mdn)
                        result[index] = value;
                }
            }
        }
    }

    free(img->imagedata);
    img->imagedata = (char *) result;

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