/*
%Z% File name: %M%  Release: %I%  Date: %G%, %U%
*/

/*******************************************************************
*                                                                  *
*FILE: fci1srb_read                                                *
*                                                                  *
*AUTHOR: Mandira Mukherjee                                         *
*EXTERNAL ROUTINES AUTHOR: Meng-chun Lin                           *
*                                                                  *
*PURPOSE/DESCRIPTION:                                              *
*                 fsdf_read_srb is a read and verify program that  *
*                 can be used with FIRE I Cirrus (SRB) data experi *
*                 ments. This program reads the non standard (SDF) *
*                 data files. This program reads the OBSERVATION   *
*                 file , Ancillary file and prints out the ERROR   *
*                 file.The data file is the OBSERVATION file which *
*                 contains 24 parameters. There are N number of    *
*                 matrices in an observation file and each matrice *
*                 represent number of record (NREC) X parameter(24)*
*                 First 24 bytes indicate prefix which provides the*
*                 information on the particular matrice. In each   *
*                 prefix is a value which provides the total sum of*
*                 the matrice. The code checks the total value for *
*                 each matrice. The ancillary file contains N numbe*
*                 r of matrices which should be eqivalent to the   *
*                 observation file. The lat/lon values per record  *
*                 are stored in this file. The remaining 20 bytes  *
*                 are empty in ancillary file. First 24 bytes per  *
*                 matrice indicate prefix. In prefix is the total  *
*                 value of the matrice. The code checks the total  *
*                 value for each matrice in ancillary file.        *
*                                                                  *
*INVOCATION:                                                       *
*           fsdf_read_srb fullpath filename                        *
*     WHERE                                                        *
*         <fullpath>                                               *
*           is the variable which contains full path of the data   *
*           location.                                              *
*         <filename>                                               *
*          is the variable which contains the name of the data file*
*                                                                  *
*INTERNAL ROUTINES:                                                *
*          Check_min_max - verifies that all data values fall in   *
*          the range of the assigned minimum and maximum values    *
*          that were passed in from OBSERVATION segment by the     *
*          fsdf_header routine.                                    *
*          ACheck_min_max - verifies that all data values fall in  *
*          the range of the assigned minimum and maximum values    *
*          that were passed in from ANCILLARY segment by the fsdf_ *
*          header routine.                                         *
*          Certain comment statements when removed prints all header*
*          information that is read in from the header file.        *
*                                                                   *
*EXTERNAL ROUTINES:                                                 *
*          fsdf_lib - has a collection of library routines that are *
*          used by the read program.                                *
*          fsdf_header - reads in all header information from the   *
*          first file in the experiment. All of the information is  *
*          stored dynamically in memory.                            *
*          fsdf_vtoc - reads in all table of contents information   *
*          from the second file in the experiment. All of the infor *
*          mation is stored dynmically in memory.                   *
*                                                                   *
* SRB DIRECTORY:                                                    *
*                                                                   *
*FIRE_CI1_SRB_SOPOLE (p0105 - p0110) (SRB_SOUTH POLE)               *
*          These are directories with single ancillary files. The   *
*          ancillary filename is Au.NOA.S. Several files were tested*
*          on each directory. Ascii hexadecimal dump files were cre *
*          ated for both Observation and Ancillary files and also   *  
*          ERROR file was created. The values and data checked in   *
*          Observation and Ancillary files are error free.          *
*                                                                    *
*FIRE_CI1_SRB_ALASKA (p0111) (SRB_ALASKA)                            *
*          This directory has a single ancillary file Au.NOA.N. The  *
*          code was tested on several files in this directory. Ascii *
*          hexadecimal dump for the Observation and Ancillary file was*
*          created. The data values look good agianst the checksum    *
*          provided in the prefix.                                    *
*                                                                     *
*FIRE_CI1_SRB_CANADA (p0112-p0113) (SRB_CANADA)                          *
*          The above directories have multiple ancillary files Au.NOA.N  *
*          and Au.NOA.M. The ascii hexadecimal dump was created for the  *
*          binary files which reffered to the first ancillary file.      *
*          The hexadecimal values from the files                         *
*                                                                        *
*FIRE_CI1_SRB_SWITZ (p0114-p0115)(SRB_SWITZERLAND)                       *
*          The above directories have multiple ancillary files Au.NOA.N  *
*          and Au.NOA.M. The ascii hexadecimal file was created for the  *
*          binary files which reffered to the first ancillary file. The  *
*          values were added and compared against the checksum value in  *
*          prefix of the data file. The values looked error free.        *
*                                                                        *
**************************************************************************
#ifdef sccs
static char sccsid[] = "File: %M%  Release: %I%  Date: %G%, %U%"
#endif

	/* System include files. */
#include <stdio.h>
#include <malloc.h>
#include <sys/types.h>
#include <sys/param.h>		/* Constant MAXPATHLEN is defined here. */
#include <string.h> 
#include <limits.h>
#include <math.h>

#define  HEAD_STR    160

extern char  *optarg;	/* Set by GETOPT for options expecting arguments */
extern int  optind;	/* Set by GETOPT - index of next ARGV to be processed */

	/* Local C include file. */
#include "fire_sdf.h"

	/* Global variable. */
extern void  interrupt_cat();
extern int  str_trim();
extern double pow();

main (argc, argv)
int argc;
char *argv[];
{

    void Check_min_max();
     void ACheck_min_max();

    char           filename1[30],     /* VTOC file name */
		   filename2[30],     /* Assign VTOC file */
                   filename3[30],     /* Assign DATA  file */
		   filename4[30],      /*Assign ancillary file */
                   OBSERVATION[30],   /* Output observation data file */
                   ANCILLARY[30];     /* Output ancillary data file  */
    FILE           *fptr,             /* File pointer to read header file */
		   *Afptr,            /* File pointer to read Ancillary file */
		   *data_fptr,        /* File pointer writes the output observation file */
		   *ancil_fptr;       /* File pointer writes the output ancillary file */
    int            len=0,             /* counter */
		   i=0,               /* counter */
		   j,                 /* counter */
		   k,                 /* counter */
		   nrec,              /* number of records */
		   naux,              /* number of ancillary files */
		   swap_flag;         /* Flag for bytes to be swaped or not */
    header         *obs,              /* Number of parameters in record */
                   *aux,              /* Number of auxillary files */
		   *ap,               /* HEADER Data type for ancillary file */
		   *p;	              /* HEADER Data type defined in local include file. */
    prefix         dpfx,              /* Record for prefix area in observation file */
		   Adpfx;             /* Record for prefix area in ancillary file */ 
    ddr_var        *vp,               /* Pointer to each variable in record */
		   *Avp;              /* Pointer to ancillary record */

    int            found=0, 
                   Afound=0,
		   fnum,              /* File number */
                     c,               /* counter */
                   rnum,              /* Record number */
                   year,              /* Retreaved year */
                   month,             /* Retreaved month */
		   day,               /* Retreaved day */
                   byear,             /* Begin year */
                   bmonth,            /* Begin month */
                   eyear,             /* End year */
                   emonth,            /* End month */
	           vtoc_bgmt,vtoc_egmt,vtoc_fnum; /* Vtoc begin gmt,end gmt,file number */
    int            Abyear,Abmonth,Aeyear,Aemonth,Avtoc_fnum; /* Ancillary begin year,month,end year month*/
    unsigned char  by[5],ey[5],fseq[5],dseq[7],nlat[7],
		   slat[7],wlon[8],elon[8]; /* values from observation files */
    unsigned char  Aby[5],Aey[5],Afseq[5],Adseq[7],Anlat[7],
		   Aslat[7],Awlon[8],Aelon[8]; /* values from ancillary file */
    int            beggmt,endgmt,Abeggmt,Aendgmt,value,value2,
		   Avalue2,Avalue,latval,lonval;
    float          north_lat, south_lat, west_lon, east_lon;/* values retreaved from observation file */
    float          Anorth_lat, Asouth_lat, Awest_lon, Aeast_lon; /* values retreaved from ancillary file */
    unsigned char  buffer[4], buf[HEAD_STR],Abuf[HEAD_STR],Abuffer[4]; /* Observation buffer/Ancillary buffer*/
    int            extra,numparms,dfnum,drnum,dcksum,drsize,
		   dnrec,drpfx,blk_size,dat_eof;
    int            Adfnum,Adrnum,Adcksum,Adrsize,Adnrec,
		   Adrpfx,countlat,countlon; /* values from ancillary file */
    short          *pvalue; /* pointer to read lat/lon value from ancillary file */
    int            j1,an,m,n,l,eof,ndx,pnrec,log_size;
    char           rname[9],Arname[9],tapename[5];
    char           Mname[9]; /* Mnemonic  */
    char           AMname[9]; /* mnemonic from ancillary file */
    char           auxname0[8]; /* ancillary file name from file.004 */
    char           auxname1[9]; /* ancillary file name from file.005 */
    vtoc_data      vtoc; /* contains information from vtoc file */
    double         Areal_val; /* Ancillary real values */
    double         real_val; /* Ancillary real value */
    float          min, max; /* min max value from observation file */
    float          Amin,Amax; /* min max value from ancillary file (lat/lon)*/
    float          Alatval,Alonval; /* Ancillary longitude/latitude value */
     char          buff[150] ;

/***************************************ASSIGN HEADER FILE************************/
    strcpy(filename1,argv[1]);
    printf("FIRE_CI1 HEADER FILENAME.... %s\n\n",filename1);

    if ((fptr = fopen (filename1, "r")) == NULL)
    {
        printf ("******************************************\n");
        printf ("* ERROR - Unable to open the header file *\n");
        printf ("*         for this data set.             *\n");
        printf ("*         Program has terminated.        *\n");
        printf ("******************************************\n");
        exit ( -1 );
    }

    naux = sdf_header (filename1, &obs, &aux, &swap_flag, &nrec);

 /*   for (i=0, p = obs; i < nrec; i++, p++)
    {
       printf ("Record: (%s) has a total of %d variables\n", p->rec_name, p->nvars);
       for (j= 0, vp = p->vd_ptr; j < p->nvars; j++, vp++)
       {
          printf ("%s (%i), format = %s", vp->mnemonic, vp->size, vp->disp_form);
          printf (" scaling constants N = %d, A = %d, b = %d\n", vp->N, vp->A, vp->b);
          if (vp->b == 0)    printf (vp->disp_form, (int) vp->min);
          else
          {
              if (strchr (vp->disp_form, 'X') != NULL)
                 printf (vp->disp_form, (int)vp->min);
              else
                 printf (vp->disp_form, vp->min);
          }
          printf ("\t");
          if (vp->b == 0)    printf (vp->disp_form, (int) vp->max);
          else
          {
             if (strchr (vp->disp_form, 'X') != NULL)
                printf (vp->disp_form, (int)vp->max);
             else
                printf (vp->disp_form, vp->max);
          }
          printf ("\n");

        }
    }

#ifdef  SRB
    printf ("Ancillary File = %s, Prefix = %d bytes, Logical rec. size = %d, Block size = %d.\n",
            aux->rec_name, aux->npfx, aux->lrsiz, aux->blksiz);
    for (i=0, p = aux; i < naux; i++, p++)
    {
       printf ("(%s) has a total of %d vars\n", p->rec_name, p->nvars);
       for (j= 0, vp = p->vd_ptr; j < p->nvars; j++, vp++)
       {
          printf ("%s (%i), format = %s", vp->mnemonic, vp->size, vp->disp_form);
          printf (" scaling constants N = %d, A = %d, b = %d\n", vp->N, vp->A, vp->b);
          if (vp->b == 0)    printf (vp->disp_form, (int) vp->min);
          else
          {
             if (strchr (vp->disp_form, 'X') != NULL)
                printf (vp->disp_form, (int)vp->min);
             else
                printf (vp->disp_form, vp->min);
          }
          printf ("\t");
          if (vp->b == 0)    printf (vp->disp_form, (int) vp->max);
          else
          {
             if (strchr (vp->disp_form, 'X') != NULL)
                printf (vp->disp_form, (int)vp->max);
             else
                printf (vp->disp_form, vp->max);
          }
          printf ("\n");

      }
    }
#endif 

fclose (fptr);  */ /* close header file */

/********************************ASSIGN VTOC FILE**************************************/

    strcpy(filename2,argv[2]);
    printf("FIRE_CI1 VTOC FILENAME.... %s\n\n",filename2);

    if ((fptr = fopen (filename2, "r")) == NULL)
    {
      printf ("****************************************\n");
      printf ("* ERROR - Unable to open the VTOC file *\n");
      printf ("*         for this data set.           *\n");
      printf ("*         Program has terminated.      *\n");
      printf ("****************************************\n");
      exit ( -1 );
    }
    for (i = 0; ; )
    {
       if ((len = VTOC_read (fptr, HEAD_STR, &vtoc)) == -1)
          break;
       if (len > 0)    i++;
    }
    printf ("NUMBER OF VTOC ENTRIES = %d\n\n", i);

    fclose (fptr); /**Close the VTOC FILE**/

/****************************CREATE DATA FILE***************************************/


    strcpy(OBSERVATION,argv[3]);
    strcat(OBSERVATION,".OBS");

    printf("OUTPUT OBSERVATION FILENAME.... %s\n\n",OBSERVATION);

      if ((data_fptr = fopen (OBSERVATION,"wt"))== NULL)
         {
           printf ("ERROR CREATING OUTPUT DATAFILE.PROGRAM TERMINATED\n");
           exit(-1);
         }

/**************************CREATE ANCILLARY OUTPUT FILE*****************************/

 /*  strcpy(ANCILLARY,argv[3]);
   strcat(ANCILLARY,".ANC");

   if ((ancil_fptr = fopen (ANCILLARY,"wt"))== NULL)
       {
         printf ("ERROR CREATING OUTPUT ANCILLARY FILE.PROGRAM TERMINATED\n");
         exit(-1);
       }*/

/***********************************ASSIGN DATA FILE*********************************/

    strcpy(filename3,argv[3]);  

    if ((fptr = fopen (filename3, "r")) == NULL)
    {
        printf ("*********************************************\n");
        printf ("* ERROR - Unable to open the data set file. *\n");
        printf ("*         Program has terminated.           *\n");
        printf ("*********************************************\n");
        exit ( -1 );
    }

    printf("\n\n");

    fread((char *) &buf[0],sizeof(unsigned char),HEAD_STR,fptr);

    printf("\n");

    sscanf((char *)buf,"%4s %6s %8s %4d%2d%8d %4d%2d%8d %6s %6s %7s %7s %7s %8s",
    fseq,dseq,rname,&byear,&bmonth,&beggmt,&eyear,&emonth,&endgmt,nlat,slat,wlon,elon,auxname0,auxname1);

    fprintf(data_fptr,"%4s %6s %8s %4d%2d%8d %4d%2d%8d %6s %6s %7s %7s %7s %8s\n",
    fseq,dseq,rname,byear,bmonth,beggmt,eyear,emonth,endgmt,nlat,slat,wlon,elon,auxname0,auxname1);

    /* CONVERT CHARACTERS TO INTEGERS OR FLOAT */

    vtoc_fnum = atoi(fseq);
    north_lat = atof((char *)&(nlat[0]));
    south_lat = atof((char *)&(slat[0]));
    west_lon = atof((char *)&(wlon[0]));
    east_lon = atof((char *)&(elon[0]));
    printf("\n");
   fprintf(data_fptr,"ancillary filename reffered by the  observation file is %s\n",auxname1);
   printf ("OBSERVATION FILENAME OPENED IS..... %s\n",rname);
   printf("ANCILLARY FILENAME REFFERED BY THE OBSERVATION FILE IS...... %s\n",auxname1);
   printf("VTOC FILENUMBER...... %d\n",vtoc_fnum);

/***************ASSIGN RIGHT ANCILLARY FILE****************************************/

     strcpy(filename4,argv[4]);

     printf(" ANCILLARY FILENAME.... %s\n",filename4);

   if ((Afptr = fopen (filename4, "r")) == NULL)
     {
      printf("****************************************\n");
      printf("*ERROR OPENING ANCILLARY FILE          *\n");
      printf ("******************************************\n");
       exit ( -1 );
     }

  printf("\n");

  fread ((char *) &Abuf[0],sizeof(unsigned char),HEAD_STR,Afptr);
  printf("\n");

  sscanf((char *)&(Abuf[0]),"%4s %6s %8s %4d%2d%8d %4d%2d%8d %6s %6s %7s %7s",
Afseq,Adseq,Arname,&Abyear,&Abmonth,&Abeggmt,&Aeyear,&Aemonth,&Aendgmt,Anlat,Aslat,Awlon,Aelon);

 /* fprintf(ancil_fptr,"%4s %6s %8s %4d%2d%8d %4d%2d%8d %6s %6s %7s %7s\n",
  Afseq,Adseq,Arname,Abyear,Abmonth,Abeggmt,Aeyear,Aemonth,Aendgmt,Anlat,Aslat,Awlon,Aelon);*/

  Avtoc_fnum = atoi(Afseq);
  Anorth_lat = atof((char *)&(Anlat[0]));
  Asouth_lat = atof((char *)&(Aslat[0]));
  Awest_lon = atof((char *)&(Awlon[0]));
  Aeast_lon = atof((char *)&(Aelon[0]));
  printf("\n");
 /* fprintf(ancil_fptr,"ancillary filename opened is %s\n",Arname);*/
 /* printf("ancillary filename opened is %s\n",Arname);*/

  if ((strcmp(auxname1,Arname)== 0))
   {
     printf("**************************************\n");
     printf("OPENED RIGHT ANCILLARY FILE         ***\n");
     printf("***************************************\n");
   }
   else
      {
        printf("*******************************************************\n");
        printf("THIS IS NOT THE RIGHT ANCILLARY FILE *\n");
        printf("*PLEASE USE DATAFILENAME.005 AS THE FOURTH ARGUMENT*\n");
        printf("*THIS DIRECTORY CONTAINS MULTIPLE ANCILLARY FILE*\n");
        printf("*******************************************************\n");
        exit(-1);
      }


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

    printf(" THE NUMBER OF RECORDS ARE =  %d\n",nrec);
    j = 0;
    if (nrec != 0)
    {
      p=obs; 
      while ( (j <= nrec) && (found != 1) ) 
      {
         if (strncmp(rname,p->rec_name, 8) != 0)
         {
            p++;
            j++;
         }
         else
            found++;
      }
     /* printf("%s DATA FILE RECORD NAME found with pointer\n",p->rec_name);*/
    }
    else
    {
       printf("********************************************\n");
       printf("*           NOTE to the USER!              *\n");
       printf("* There were no data records listed in the *\n");
       printf("* header file.  Please review your data.   *\n");
       printf("* Program has terminated.                  *\n");
       printf("********************************************\n");
       exit( -1 );
    }
/****************************************************************************/

 /* printf("THE NUMBER OF ANCILLARY FILES ARE = %d\n",naux);*/
  k = 0;
   if (naux != 0)
    {
      ap = aux;
      while ((k <= naux) && (Afound !=1))
        {
          if (strncmp(Arname,ap->rec_name,8) != 0)
             {
                 ap++;
                 k++;
             }
           else
               Afound++;
    }
     /* printf("%s ANCILLARY FILE NAME found with pointer\n",ap->rec_name);*/
  } 
  else
    {
       printf("********************************************\n");
        printf("*           NOTE to the USER!              *\n");
       printf("* There were no aux file  name listed in the *\n");
       printf("* header file.  Please review your data.   *\n");
       printf("* Program has terminated.                  *\n");
       printf("********************************************\n");
       exit(-1);
    }
/**************************************************************************/


   blk_size = ap->blksiz;
   extra = blk_size - TOCSIZE;
   log_size= ap->lrsiz;
   pnrec =(blk_size/log_size)-1;
  /* printf ("prefix nrec======%d\n",pnrec);
   printf ("extra=======%d\n",extra);*/
   if (extra != 0)
      {
      /* printf ("now extra=======%d\n",extra);*/
	   for (j = 0; j< extra;j++)
	     {
		 c= getc(fptr);
		 c=getc(Afptr);
             }
	 /*printf ("c pointer obptr%ld \n",ftell(fptr));
	  printf ("c pointer anptr%ld \n",ftell(Afptr));*/
      }



/******************************READ PREFIX AND DATA******************/
vp =p->vd_ptr;
Avp=ap->vd_ptr;
while (((feof(fptr)) == 0)&&((feof(Afptr)== 0)))
{
value2 = 0;
Avalue2=0;

/***********************READ PREFIX FOR OBSERVATION FILE***************/

  fread ((char *) &dpfx,sizeof (prefix),1,fptr);
  dfnum = dpfx.fnum;
  drnum = dpfx.rnum;
  dcksum = dpfx.cksm;
  drsize = dpfx.rsiz;
  dnrec = dpfx.nrec;
  drpfx = dpfx.pfx;

 fprintf (data_fptr,"OBSERVATION data prefix = %d, %d, %d, %d, %d, %d\n",dfnum,drnum,dcksum,
	  drsize,dnrec,drpfx);
  /*fprintf (ancil_fptr,"OBSERVATION data prefix = %d, %d, %d, %d, %d, %d\n",dfnum,drnum,dcksum,
  drsize,dnrec,drpfx);*/

/*****************************READ PREFIX FOR ANCILLARY FILE********************/

fread ((char *) &Adpfx,sizeof (prefix),1,Afptr);
    Adfnum = Adpfx.fnum;
    Adrnum = Adpfx.rnum;
    Adcksum = Adpfx.cksm;
    Adrsize = Adpfx.rsiz;
    Adnrec = Adpfx.nrec;
    Adrpfx = Adpfx.pfx;

  fprintf (data_fptr,"ANCILLARY data prefix = %d, %d, %d, %d, %d, %d\n",Adfnum,Adrnum,Adcksum,
	    Adrsize,Adnrec,Adrpfx);
  /*fprintf (ancil_fptr,"ANCILLARY data prefix = %d, %d, %d, %d, %d, %d\n",Adfnum,Adrnum,Adcksum,
  Adrsize,Adnrec,Adrpfx);*/

/*********CHECK PREFIX SYNCHRONIZATION****************************************/

if ((drnum != Adrnum) || ( drsize != Adrsize) || (dnrec != Adnrec) ||(drpfx != Adrpfx)
    || ( (drsize * dnrec + drpfx) != blk_size) || ((Adrsize*Adnrec + Adrpfx)!= blk_size))
       {
	printf("ERROR IN PREFIX SYNCHRONIZATION\n");
	exit (-1);
	}

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


for (n = 0;(n < dnrec);n++)

  {                           /*****begining of increament parameter******/

    {
    j = 0;
    while (j++ < p->nvars)
    { 
      fread ((char *) &buffer[0],sizeof(unsigned char),vp->size,fptr);
    if ((feof(fptr) != 0)&&(feof(Afptr)!=0))
      {
	printf("\n\n\n");
	printf("---------------------------------------------------\n");
	printf("THE END OF FILE HAS BEEN REACHED                   \n");
	printf("THIS IS A NORMAL TERMINATION                       \n");
	printf("----------------------------------------------------\n");
	exit (0);
     }

 

 /*************************RETRIEVE DATA************************/

 value = buffer[0];
 value2 = value+value2;
 if (vp->b != 0)
        {
          real_val = pow(2.0,((double)vp->N)-((double)vp->b));
          real_val = (((double)value)*real_val) + (vp->A *1.0);
          fprintf (data_fptr,vp->disp_form,real_val);
        }
  else
        {
           real_val = (double)value;
           fprintf (data_fptr," % 2X",value);
        }

          min = vp->min;
          max = vp->max;

    strcpy(Mname,vp->mnemonic);

    (void)Check_min_max(real_val,min,max,Mname);


           vp++;         /****increament data pointer*****/

       }
           vp = p->vd_ptr; /******move pointer beginning to********/
     }    
  }         /*******check prefix********/


       fprintf(data_fptr," %d ",dcksum);

       fprintf(data_fptr," %d\n",value2);

       if (dcksum != value2)
	 {
	   printf ("ERROR IN OBSERVATION FILE CHECKSUM\n");
	   exit(-1);
         }

/********READ THE ANCILLARY DATA FILE***************************/

for (an=0;(an < Adnrec);an++)

{           /*initialize the begining parameter**********/
  {
     j1=0;
     while(j1++ < ap->nvars)
       {
	fread ((char *) &Abuffer[0],sizeof(unsigned char),Avp->size,Afptr);

/*************************ADD CHECKSUM****************************/

     if (j1 == 1 || j1 == 2)
      Avalue2 = Avalue2 + Abuffer[0] + Abuffer [1];
     else
       Avalue2= Avalue2 + Abuffer[0];
      /* printf ("Avalue2=%2X",Avalue2);*/

/**********************END OF CHECKSUM*****************************/
  if (j1 == 1)
    {
      pvalue = (short *)&Abuffer[0];
      latval = *pvalue;
       if ((latval != NULL_VAL)&&(Avp->b!=0))
	  {
	     Avalue = latval;
	     Areal_val = pow(2.0,((double)Avp->N)-((double)Avp->b));
	     Areal_val = (((double)Avalue)*Areal_val) + (Avp->A*1.0);
	     Alatval = Areal_val;
	       
       	    /* fprintf(ancil_fptr,Avp->disp_form,Areal_val);*/
           }
          
        else
	  {
	     Avalue = NULL_VAL;
	     Areal_val = (double)Avalue;
           /*fprintf (ancil_fptr," % 2X",Avalue);*/
          }
     }
   else if (j1 == 2)
      {
       pvalue = (short *)&Abuffer[0];
       lonval = *pvalue;
	  if ((lonval != NULL_VAL)&&(Avp->b!= 0))
	     {
	       Avalue = lonval;
	       Areal_val = pow(2.0,((double)Avp->N)-((double)Avp->b));
	       Areal_val = (((double)Avalue)*Areal_val) + (Avp->A*1.0);
	       Alonval = Areal_val;

	     /*fprintf(ancil_fptr,Avp->disp_form,Areal_val);*/

             }
          else
	     {
	       Avalue = NULL_VAL;
	       Areal_val = (double)Avalue;
              /*fprintf (ancil_fptr," % 2X",Avalue);*/
             }
       }
   else if (j1 > 2)
	  {

                    Avalue = Abuffer[0];
                /* printf(" % 2X",Avalue);*/
                   if  (Avp->b != 0)
	       {
	          Areal_val = pow(2.0,((double)Avp->N)-((double)Avp->b));
	   	  Areal_val = (((double)Avalue)*Areal_val) + (Avp->A*1.0);
		 /* fprintf(ancil_fptr,Avp->disp_form,Areal_val);*/
                }
            else
	        {
	 	   Areal_val = (double)Avalue;
		  /*fprintf (ancil_fptr," % 2X",Avalue);*/
                }
          }



/************************MAX AND MIN ********************************/

       Amin = Avp->min;
       Amax = Avp->max;

      strcpy (AMname,Avp->mnemonic);

      (void)ACheck_min_max(Areal_val,Amin,Amax,AMname); 


            Avp++;  /******increament ancillary data pointer********/
          }
            Avp = ap->vd_ptr;   /*****pointer back to beginning parameter***/
        }  

     }       /******initialize value and reads next prefix********/

/*********************COMPARE CHECKSUM AND TOTAL VALUE*****************/

  /* fprintf(ancil_fptr," %d",Adcksum);*/
   /*fprintf(ancil_fptr," %d\n",Avalue2);*/
     if (Adcksum != Avalue2)
       {
	  printf("ERROR ON CHECKSUM OF ANCILLARY FILE");
	  exit (-1);
       }
  
 }

/*************CLOSE ALL FILE POINTERS*******************************/

  free ((char *)obs);
  free ((char *)aux);
  fclose(Afptr);
  fclose (fptr);
  fclose(data_fptr);
 /* fclose(ancil_fptr); */
  exit(0);

}


/*******************************************************************
* FILE: Check_min_max                                              *
*                                                                  *
* AUTHOR: Mandira Mukherjee                                        *
*                                                                  *
*PURPOSE/DESCRIPTION:                                              *
*         This routine verifies that the data values obtained from *
*         the OBSERVATION file fall in the range of the minimum    *
*          and maximum values assigned to each parameter from the  *
*         header file. If a value is out of range this value is    *
*          written out to the ERROR file.                          *
*                                                                  *
* INVOCATION:                                                      *
*     (void)Check_min_max (real_val,min,max,Mname,out_fptr);       *
*    WHERE                                                         *
*      <real_val>                                                  *
*        is the variable which contains the full path of the data  * 
*      <min>                                                       *
*        is the variable which contains the assigned minimum value *
*        for the particular data value/parameter.                  *
*      <max>                                                       *
*        is the variable which contains the assigned minimum value *
*        for the particular data value/parameter.                  *
*      <Mname>                                                     *
*        is the name of the parameter for current real_val.        *
*      <out_fptr>                                                  *
*        is the file pointer to error file.                        *
*                                                                  *
* INTERNAL ROUTINES:                                               *
*    None.                                                         *
*                                                                  *
* EXTERNAL ROUTINES:                                               *
*    None.                                                         *
* NOTES: None.                                                     *
********************************************************************/

void Check_min_max (real_val,min,max,Mname)
double real_val;
float min,max;
char *Mname;


{
   /*printf("THIS IS A TEST FOR DATA ERROR FILE");*/
   if ((float)real_val < min)
   {
    printf("ERROR-Label : %s\n",Mname);
    printf("      Current Value: %8.1f\n",real_val);
    printf("      Defined Min  : %8.1f\n",min);
    }

    else 
      if ((float)real_val > max)
      {
       printf("ERROR - Label : %s\n",Mname);
       printf("        Current Value : %8.1f\n",real_val);
       printf("        Defined Max   : %8.1f\n",max);     
      }
 }

/*******************************************************************
*                                                                  *
* FILE:  ACheck_min_max                                            *
*                                                                  *
* AUTHOR: Mandira Mukherjee                                        *
*                                                                  *
* PURPOSE/DESCRIPTION:                                             *
*         This routine verifies that the data values from Ancillary*
*         file fall in the range of the minimum and maximum values *
*         assigned to each parameter from the header file. If the  *
*         value is out of range this value is written to the ERROR *
*         file.                                                    *
*                                                                  *
* INVOCATION:                                                      *
*     (void) ACheck_min_max (Areal_val,Amin,Amax,AMname,out_fptr); *
*     WHERE                                                        *
*      <Areal_val>                                                 * 
*        is the Ancillary variable which contains the full path of *
*        the ancillary data.                                       *
*      <Amin>                                                      *
*        is the variable which contains the assigned minimum value *
*        from the ancillary file for the particular data/value     *
*        parameter.                                                *
*      <Amax>                                                      *
*        is the variable which contains the assigned maximum value *
*        from the ancillary file for the particular data/value     *
*        parameter.                                                *
*      <AMname>                                                    *
*        is the parameter's name for current real_val from ancillary*
*        file.                                                      *
* INTERNAL ROUTINES:                                                *
*   NONE.                                                           *
*                                                                   *
* EXTERNAL ROUTINES:                                                *
*   NONE.                                                           *
*                                                                   *
* NOTES: None.                                                      *
*********************************************************************/

      

 void ACheck_min_max (Areal_val,Amin,Amax,AMname)
 double Areal_val;
 float Amin,Amax;
 char *AMname;

 {
   /*printf("THIS IS A TEST FOR ANCILLARY ERROR FILE");*/
   
    if (((float)Areal_val != 32767.0)&& ((float)Areal_val < Amin))
     {
       printf("ERROR-Label : %s\n",AMname);
       printf("      Current Value: %8.1f\n",Areal_val);
       printf("      Defined Min  : %8.1f\n",Amin);
     }

     else

       if (((float)Areal_val != 32767.0)&& ((float)Areal_val > Amax)) 
	{
	  printf("ERROR - Label : %s\n",AMname);
	  printf("        Current Value : %8.1f\n",Areal_val);
	  printf("        Defined Max   : %8.1f\n",Amax);
        }
 }

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

