/* bandnormal.c
 *                *
 *              Emilio          4/1/99
 *                Updated program.
 *              Emilio          11/25/98
 *                Wrote program. Compiled without bugs. Ran well, no apparent errors.
 *                *
 * COMPILE AS: gccemu bandnormal
 * RUN AS: bandnormal
 ******************************************************************************/

#include "emu.h"

const char * cpszUsage = {"usage: bandnormal \n\
.\n\
"};

int main(int argc, char *argv[])
{
  FILE *fnorm;
  int v, i, undercount, overcount, nElements;   int bug=0;
  float *oldval;
  BYTE *newval;
  float oldlow, oldhigh, oldrange, temp;
  float newlow, newhigh, newrange;
  char outfilename[FILENAMELEN];


  Initialize(&argc, argv, NOMASK);

  newlow  = P[0];
  newhigh = P[1];
  newrange = newhigh - newlow;


  for (v = 0; v < nVars; v++)   {
    nElements = pstVars[v].nRows * pstVars[v].nCols;

    oldlow  = pstVars[v].P[0];
    oldhigh = pstVars[v].P[1];
    oldrange = oldhigh - oldlow;

    undercount = 0;
    overcount  = 0;

    oldval = alloc1d_f(0, nElements-1);
    newval = alloc1d_uc(0, nElements-1);

    ReadXY(oldval, pstVars[v], NONE, NONE);

    for (i = 0; i < nElements; i++)
    {
      /* temp = (oldval[i] - oldlow) / oldrange * newrange + newlow; */
      temp = (oldval[i] - oldlow) * (newrange / oldrange) + newlow;

      if (temp > 255.0)
      {
        newval[i] = 255;
        overcount++;
      }
      else if (temp < 0.0)
      {
        newval[i] = 0;
        undercount++;
      }
      else
        newval[i] = (BYTE) floor(temp + 0.5);
    }

    (void) printf("New values (oldlow=%.2f) less than 0:  %d\n", oldlow, undercount);
    (void) printf("New values (oldhigh=%.2f) greater than 255:  %d\n\n", oldhigh,overcount);


    /* write normalized data */
    strcpy(outfilename, pstVars[v].param);
    fnorm = OUTPUTfile(outfilename, ".n");
    fwrite(newval, sizeof(BYTE), nElements, fnorm);
    fclose(fnorm);

    free1d_f(oldval,0,nElements-1);
    free1d_uc(newval,0,nElements-1);

    } /* END v FOR-LOOP (loop thru each variable) */


  /* ========================================================= */
  CleanUp();

  return(0);
}

/* ================================================================= */
void ProcessCommandLineArgs(int * pArgc, char * argv[])
{
}
/* ================================================================= */
void LocalCleanUp(void)
{
}