/*************************************************
            
           U.S. Bureau of Land Management
                 Spatial Data Transfer Standard (SDTS)
                      SDTS to DEM optional format  
             program:         stds2dem.c
                 author:          Sol Katz  (skatz@blm.gov)
                 date:            Mar 23, 1998
                 language:        C
  
       This program dumps SDTS DEM modules to a data file which is
         supposed to reconstruct the original dem source file
 
       
  To compile and link under DOS using Microsoft C:
          
       CL /AH STDS2dem.C fip123.LIB
         
Revisions
     
    =========
.006  corrected writing to quad to new file
.007  corrected calculation for xmin, ymin to work on east of meridian.
      set profiles x,y to be multiples of height and width.  
.008  printed maxvalue and minvalue in header correctly.
*****************************************************/
#include <stdio.h>
#include <string.h>
#include "fips123/f123inc/stc123.h"
#define null 0
FILE *fpin;
FILE *fpdem;

FILE *fpran;

long  reclen = 9;   /* record length for random access file with cr/lf */
/*long  reclen = 6;*/   /* record length for random access file w/o cr/lf*/

int             idem[1700];
long            nrows,row,ncols,col;
long            izone;
/*double          minval,maxval;*/
double          height,width;
char            short_buff[200];
char            buffer[1025];
long int_level;
double sfax, sfay, xorg, yorg;  /* Internal Spatial Reference transformation parameter
s */
double xhrs, yhrs;  /* Internal Spatial Reference transformation parameters */
double height,width;
double upperlx,upperly;
long li;
double x[5];
double y[5];
long  scale;
char ice;
char ccs[4];
char leadid;
long str_len;
char tag[10];
long nxy;
char string[5000];
char descr[5000];
char frmts[500];
int stat2;
int status;
long row, col, maxcol;
unsigned char temp[100]; /* temporary buffer used for hex dumps of binary */
long i;
long  fillvalue;
long  voidvalue;
long  minvalue;
long  maxvalue;
char title[144];
char DAID[100];
char date[11];
/*char *fdname;*/
char mod_name[10];
char base_name[100];
char file_name[100];
char out_file[100];
int order;       /* byte order returned by g123order */
double lat; 
double lon;
int zone = 0 ;
int level = 3;
int utm = 1 ; 
int meters = 2 ;
int zero = 0;
int sides = 4;
int one = 1;
double rem;

double  NE_LATITUDE ;
double  NE_LONGITUDE;
double  NW_LATITUDE ;
double  NW_LONGITUDE;
double  SW_LATITUDE ;
double  SW_LONGITUDE;
double  SE_LATITUDE ;
double  SE_LONGITUDE;
double  NEX;
double  NEY;
double  NWX;
double  NWY;
double  SWX;
double  SWY;
double  SEX;
double  SEY;
char rsnm[5] ;
char cellid [3] ;

void main(int,char*[]);
void get_iref(void);
void get_xref(void);
void dem_rc(int);
void dem_head(int);
void dem_mbr(int);

void cell_range(int);
void cells_out(int);
void dem_out(void);
void get_nw_corner(void);
int s123tol2(char *,long *,int);
void main(int argc,char *argv[])
  
{

/*     Print error if arguments were not included on command line        */

printf ("\n        Spatial Data Transfer Standard (SDTS)");
printf ("\n               SDTS to DEM Utility");
printf ("\n              SDTS2DEM BETA  ver .008");
printf ("\n         Another gis translation tool from");
printf ("\n         Sol Katz(skatz@blm.gov), April 1998.\n");

/*      Open line input file         */
if (argc < 4)
  {
  printf ("\nUsage: sdts2dem (base_input_name) (base_output_file) (cell id)\n ");
  printf ("    input file:  first 4 character base file name\n");
  printf ("   output file:  output file without .DEM extension\n");
  printf ("       cell id:  characters in position 7 and 8 of filename usually L0\n\n");
  }

if (argc < 2) /*      Prompt for input SDTS file name      */
  {
  printf ("\n\nEnter first 4 charcters of the base SDTS file name:\n ");
  scanf ("%s",base_name);
  }
else 
  strcpy (base_name, argv[1]);

/*      Determine byte order of current machine         */
  g123order (&order);

/*
    get translation parameters for DEM dataset from the Internal
      Spatial Reference module.)
*/
  strcpy (file_name,base_name);
  strcat (file_name,"IDEN.DDF");
  if (! beg123file (file_name,'R',&int_level,&ice,ccs,&fpin))
         {
          printf ("\nCAN'T OPEN 'DEM' IDEN FILE %s",file_name);
          exit(0);
          }
  stat2 = end123file (&fpin);
/*    
  Prompt for output report file name      */
  
if (argc < 3)  /*      prompt for output dem file name      */
  {
    printf ("\nEnter base output file name (exclude any extension):\n ");
    scanf ("%s",out_file); 
  }
  else
    strcpy (out_file, argv[2]);
  strcat(out_file,".dem") ;
  

  if (argc < 4)  /*      prompt for 2 digit layer number      */
  {
    printf 
("\nEnter the 2 character in position 7 and 8 of the CELL file name, usually L0 :\n ");
    scanf ("%s",cellid); 
  }
  else
    strcpy (cellid, argv[3]);

/*       Open output .dem file           */
  fpdem = fopen (out_file,"w");
  if (fpdem == null)
         {
         printf ("\nERROR OPENING .DEM FILE %s\m",out_file);
         stat2 = end123file (&fpin);
         exit (1);
         }

  dem_head(status);
  cell_range(status);
  get_iref();
  get_xref();
  get_nw_corner();
 
  dem_mbr(status);
  dem_rc(status);

  strcat ( title,"  ");
  strcat ( title,DAID);
  printf ("Summary of SDTS/DEM Data Files\n"); 
  printf ("title = %s \ndate = %s \n", title,date);
  printf ("Range:  max= %ld, min= %ld, void= %ld, fill= %ld\n",     
         maxvalue,minvalue,voidvalue,fillvalue);
  printf ("cell width:              %f\n",width);
  printf ("cell height:             %f\n",height);
  printf ("projection:              %s\n",rsnm);
  printf ("zone:                    %d\n",izone);
  printf ("Total rows = %ld, total columns= %ld \n",nrows,ncols);
  if (nrows > 1700 )
  {
     printf("%d rows execeed the 1700 limit of the program\n",nrows);
     printf("notify me and i'll try to increase the limits.\n");
     exit(1);
  }


  printf ("creating random access file \n");  

  fpran = fopen ("random.fil","w");
  if (fpran == null)
         {
         printf ("\nERROR OPENING Random access FILE 'random.fil'\n");
         stat2 = end123file (&fpin);
         exit (1);
         }
  cells_out(status);
  fclose(fpran);

  fpran = fopen ("random.fil","r");
  if (fpran == null)
         {
         printf ("\nERROR OPENING Random access FILE 'random.fil'\n");
         stat2 = end123file (&fpin);
         exit (1);
         }

  strcat ( title,"  SDTS to DEM, By Sol Katz, April 1998, ver .008");
  printf ("writing output dem file \n");
  dem_out();

/*  printf("\nEnd of Program\n"); */
/* Close files and end      */
  fclose (fpdem);
  fclose (fpran);

  exit(0);
}

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

void dem_rc(int status)
{
 
 strcpy (file_name,base_name);

  strcat (file_name,"LDEF.DDF");

  if (! beg123file (file_name,'R',&int_level,&ice,ccs,&fpin))
         {
          printf ("\nCAN'T OPEN 'dem' LDEF FILE %s",file_name);
          exit(0);
          }
 
 /*      Read data descriptive record (DDR)      */
  if (! rd123ddrec      
        (fpin,          /* file pointer */
        string,         /* DDR record returned */
        &status))       /* status returned */
          {
            printf ("\n*** ERROR READING DDR *** %d",status);
            fprintf (fpdem,"\n*** ERROR READING DDR *** %d",status);
            goto done;
         }
 status = -1;

  
  /*       Loop to process each subfield             */

  do 
  {
 
 /*      Read data record subfield    */
    
 if (! rd123sfld
        (fpin,          /* file pointer */
        tag,            /* field tag returned */
        &leadid,        /* leader identifier returned */
        string,         /* subfield contents returned */
        &str_len,       /* length of subfield */
        &status))       /* status returned */
         {
         printf ("\nERROR READING DATA RECORD SUBFIELD");
         fprintf (fpdem,"\nERROR READING DATA RECORD SUBFIELD");

         goto done;
         }

  /*      Retrieve description of current subfield        */

     if (! chk123sfld    
        (fpin,          /* file pointer */
        tag,            /* tag output */
        descr,          /* subfield descriptions output */
        frmts))          /* subfield format control */
         {
         printf ("\nERROR CHECKING DATA RECORD SUBFIELD");
 
        fprintf (fpdem,"\nERROR CHECKING DATA RECORD SUBFIELD");

         goto done;
         
}
  /*       Process based on field and subfield tags           */
    if ( !strcmp(tag,"LDEF") && !strcmp(descr,"NROW"))
         {
         nrows = atol (string);
         }
    else if ( !strcmp(tag,"LDEF") && !strcmp(descr,"NCOL"))
         {
          ncols = atol (string);
         }

/*    If end of record, write out record and reinitialize        */
    if (status == 3 || status == 4)  
    {
/*       printf ("dem _rc nrows = %ld, ncols= %ld \n",nrows,ncols);*/
  
    }
   } while (status != 4);
   /* Break out of loop at end of file */
  done:
  stat2 = end123file (&fpin);
  return;

}
void get_xref(void)

{
/* set some default values */

strcpy(rsnm,"??1")  ;
/*strcpy(hdat,"??2")  ;*/
/*strcpy(rdoc,"??3")  ;*/
strcpy (file_name,base_name);
strcat (file_name,"XREF.DDF");

if (! beg123file (file_name,'R',&int_level,&ice,ccs,&fpin))
         {
         printf ("\nERROR OPENING FILE %s",file_name);
         exit(0);
         }

if (! rd123ddrec 
        (fpin,          /* file pointer */
        string,         /* DDR record returned */
        &status))       /* status returned */
         {
         printf ("\n*** ERROR READING DDR ***");
         goto done;
         }
status = -1;
/*       Loop to process each subfield in Identification module            */
do {

/*      Read data record subfield    */
 if (! rd123sfld  
       (fpin,          /* file pointer */
        tag,            /* field tag returned */
        &leadid,        /* leader identifier returned */
        string,         /* subfield contents returned */
        &str_len,       /* string length */
        &status))       /* status returned */
         {
       
  printf ("\nERROR READING DATA RECORD SUBFIELD (IDEN MODULE)");

         goto done;
       
  }
/*      Retrieve description of current subfield        */

 if (! chk123sfld      
        (fpin,          /* file pointer */
        tag,            /* tag output */
        descr,          /* subfield descriptions output */
        frmts))         /* subfield format control */
         {

         printf ("\nERROR CHECKING DATA RECORD SUBFIELD");
         goto done;
         }

/*    check subfield name and extract contents for each subfield       */
  
    if (!strcmp      (tag, "XREF") && !strcmp (descr, "RSNM"))
        strcpy(rsnm,string)  ;
      else if (!strcmp (tag, "XREF") && !strcmp (descr, "ZONE"))
        izone = atoi(string)  ;
/*
      else if (!strcmp (tag, "XREF") && !strcmp (descr, "HDAT"))
        strcpy(hdat,string)  ;
      else if (!strcmp (tag, "XREF") && !strcmp (descr, "RDOC"))     
        strcpy(rdoc,string)  ;
*/

 } while (status != 4);   /* Break out of loop at end of file */
/*
printf ("hdat:                              %s\n",hdat);
printf ("rdoc:                              %s\n",rdoc);
*/

done:
stat2 = end123file (&fpin);

return;
}


/***************************************/
void dem_head(int status)
{
/*  
    Open Identifcation module */
strcpy (file_name,base_name);
strcat (file_name,"IDEN.DDF");
if (! beg123file (file_name,'R',&int_level,&ice,ccs,&fpin))
         {
         printf ("\nERROR OPENING FILE %s",file_name);
         exit(0);
         }
/*printf ("\n\nIdentification module:  %s\n",file_name);*/
/*      Read Identification module data descriptive record (DDR)      */


if (! rd123ddrec 
        (fpin,          /* file pointer */
        string,         /* DDR record returned */
        &status))       /* status returned */
         {
         printf ("\n*** ERROR READING DDR ***");
         goto done;
         }
status = -1;
/*       Loop to process each subfield in Identification module            */
do {
/*      Read data record subfield    */
 if (! rd123sfld    
        (fpin,          /* file pointer */
        tag,            /* field tag returned */
        &leadid,        /* leader identifier returned */
        string,         /* subfield contents returned */ 
        &str_len,       /* string length */
        &status))       /* status returned */
         {
         printf ("\nERROR READING DATA RECORD SUBFIELD (IDEN MODULE)");
         goto done;
         }
/*      Retrieve description of current subfield        */

 if (! chk123sfld
        (fpin,          /* file pointer */
        tag,            /* tag output */
        descr,          /* subfield descriptions output */
        frmts))          /* subfield format control */
         {
         printf ("\nERROR CHECKING DATA RECORD SUBFIELD");
         goto done;
         }

/*    Display subfield name and contents for each subfield       */
      if (!strcmp (tag, "IDEN") && !strcmp (descr, "TITL")) /* title */
          strcpy(title,string);
      else if (!strcmp (tag, "IDEN") && !strcmp (descr, "SCAL"))
      {
         /* scale */
         scale = atol(string);
/*         fprintf (fpdem,"scale:                   %8s\n",string);*/
      }
      else if (!strcmp (tag, "IDEN") && !strcmp (descr, "DAID"))
        strcpy(DAID ,string);
      else if (!strcmp (tag, "IDEN") && !strcmp (descr, "DCDT"))
        strcpy(date,string);
/*
      else if (!strcmp (tag, "IDEN") && !strcmp (descr, "MPDT"))
        printf ("Map Date:                  %s\n",string);
*/
 } while (status != 4);   /* Break out of loop at end of file */

done:
/*     
  Close input Identification module           */

status = end123file (&fpin);

}
/*********************************************/
void dem_mbr(int status)
{
  int seq=0;
  double fl;
 /* int label ;*/
  strcpy (file_name,base_name);
  strcat (file_name,"SPDM.DDF");
/*  strcat (file_name,module);*/
  
if (! beg123file (file_name,'R',&int_level,&ice,ccs,&fpin))
   
      {
          printf ("\nCAN'T OPEN 'dem' SPDM FILE %s",file_name);
          exit(0);
          }
  /*      Read data descriptive record (DDR)      */

  if (! rd123ddrec 
        (fpin,          /* file pointer */
        string,         /* DDR record returned */
        &status))       /* status returned */
          {
            printf ("\n*** ERROR READING DDR *** %d",status);
            fprintf (fpdem,"\n*** ERROR READING DDR *** %d",status);
            goto done;
         }
  
status = -1;
  
nxy = 1;        
 /* number of coordinate pairs */
  
  /*       Loop to process each subfield             */


  do {  /*      Read data record subfield    */
  if (! rd123sfld      
        (fpin,          /* file pointer */
        tag,            /* field tag returned */
        &leadid,        /* leader identifier returned */
        string,         /* subfield contents returned */
        &str_len,       /* length of subfield */
        &status))        /* status returned */
 
        {
         printf ("\nERROR READING DATA RECORD SUBFIELD");
         fprintf (fpdem,"\nERROR READING DATA RECORD SUBFIELD");
         goto done;
         }
  /* 
     Retrieve description of current subfield        */
   
if (! chk123sfld 
        (fpin,          /* file pointer */
        tag,            /* tag output */
        descr,          /* subfield descriptions output */
        frmts))         /* subfield format control */
         {
         printf ("\nERROR CHECKING DATA RECORD SUBFIELD");
         fprintf (fpdem,"\nERROR CHECKING DATA RECORD SUBFIELD");
         goto done;
         }
  /*  
     Process based on field and subfield tags           */
       if ( !strcmp(tag,"DMSA"))
         {
/*         printf("tag = %s,descr = %s, string = %s\n",tag,descr,string); */
         fl = atof (string);
/*       Process if X spatial address    */
              if (!strcmp (descr, "!X"))
                {
                x[nxy] = fl;
                }
/*        Process if Y spatial address    */
        else if (!strcmp (descr, "!Y"))
                {
                y[nxy] = fl;
                nxy++;
                }
      }
/* 
   If end of record, write out record and reinitialize        */

    if (status == 3 || status == 4)
    {
       seq++;
       for (i = i; i < nxy; i++) 
       {
         if      ( i==1 )     
         {
            SWX = x[i]; 
            SWY = y[i];
         }
    else if ( i==2 ) /*printf( "NW= ");*/
         {
            NWX = x[i];
            NWY = y[i];
         }
         else if ( i==3 ) /*printf( "NE= ");*/
         {   
            NEX = x[i];
            NEY = y[i];
         }
     else if ( i==4 ) /* printf( "SE= ");*/
         {
            SEX = x[i];
            SEY = y[i];
         }
 
/*      printf ("dem mbr %12.2f %12.2f,%12.2f %12.2f,
                     %12.2f %12.2f,%12.2f %12.2f \n",
                  SWX,SWY,NWX,NWY,NEX,NEY,SEX,SEY);
*/

/*         
           fprintf (fpdem,"mbr  %12.2f %12.2f \n, %12.2f %12.2f \n,
              %12.2f %12.2f \n, %12.2f %12.2f \n",
                  SWX,SWY,NWX,NWY,NEX,NEY,SEX,SEY);
*/
       }
       nxy=0;
   }
  } while (status != 4);   /* Break out of loop at end of file */
/*
     printf ("sw dem mbr %12.2f %12.2f \n",  SWX,SWY);
     printf ("nw dem mbr %12.2f %12.2f \n",  NWX,NWY);
     printf ("se dem mbr %12.2f %12.2f \n",  SEX,SEY);
     printf ("ne dem mbr %12.2f %12.2f \n",  NEX,NEY);
*/
  done:
  stat2 = end123file (&fpin);
  return;
}
/*********************************************/
void cell_range(int status)
{
int seq=0;
int recid;
strcpy (file_name,base_name);
strcat (file_name,"DDOM.DDF");
/*printf( "looking for cell range info in DDOM file\n");*/


if (! beg123file (file_name,'R',&int_level,&ice,ccs,&fpin))
         {
         printf ("\nERROR OPENING FILE %s",file_name);
         exit(0);
         }

if (! rd123ddrec 
        (fpin,          /* file pointer */
        string,         /* DDR record returned */
        &status))       /* status returned */
         {
         printf ("\n*** ERROR READING DDR ***");
         goto done;
         }
status = -1;
/*       Loop to process each subfield in CATS module            */
do {  
/*      Read data record subfield    */
 if (! rd123sfld 
        (fpin,          /* file pointer */
        tag,            /* field tag returned */
        &leadid,        /* leader identifier returned */
        string,         /* subfield contents returned */
        &str_len,       /* string length */
        &status))       /* status returned */
         {
         printf ("\nERROR READING DATA RECORD SUBFIELD (AHDR MODULE)");
         goto done;
         }
/*      Retrieve description of current subfield        */
 
if (! chk123sfld 
        (fpin,          /* file pointer */
        tag,            /* tag output */
        descr,          /* subfield descriptions output */
        frmts))         /* subfield format control */    
        {
         printf ("\nERROR CHECKING DATA RECORD SUBFIELD");
         goto done;
         }
/*    check subfield name and extract contents for each subfield       */

      if      (!strcmp (tag, "DDOM") && !strcmp (descr, "RCID"))
        {
/*           printf("RECID as string %s \n", string);*/
             recid = atoi(string); 
/*           printf ("rec id as number= %d \n",recid);*/
        }      
  
    else if (recid == 1  && !strcmp ( descr,"DVAL"))
      {
        voidvalue = atoi (string)   ;
/*        printf ("void %d %s %d\n",recid,string, voidvalue);*/
      }

      else if (recid == 2  && !strcmp ( descr,"DVAL"))
      {
        fillvalue = atoi(string)   ;
/*        printf ("fill %d %s %d\n",recid,string, fillvalue);*/
      }
      else if (recid == 3  && !strcmp ( descr,"DVAL"))
      {
        minvalue = atoi (string)   ;
/*        printf ("min %d %s %d\n",recid,string, minvalue);*/
      }
      else if (recid == 4  && !strcmp ( descr,"DVAL"))
      {
        maxvalue = atoi (string)   ;
/*        printf ("max %d %s %d\n",recid,string, maxvalue);*/
      }

 } while (status != 4);   /* Break out of loop at end of file */
done:
stat2 = end123file (&fpin);
return;
}
/***************************************************************************** 
**    INVOCATION NAME: S123TOL2** 

**    PURPOSE: TO CONVERT A 2 CHARACTER STRING TO A LONG INTEGER AND
**              CHANGE ITS BYTE ORDERING WHEN SPECIFIED.
** 
**    INVOCATION METHOD: S123TOL(STRING,NUM,REVERSE)
** 
**    ARGUMENT LIST: 
**     NAME          TYPE      USE      DESCRIPTION
**     STRING[]      PTR        I       CHARACTER STRING
**     NUM           LONG       O       NUMBER TO BE CONVERTED
**     REVERSE       LOGICAL    I       REVERSE BYTE ORDER FLAG
**                                      1 - REVERSE     
                
/**********************************/

int s123tol2(string,num,reverse)
char *string;
long *num;

int reverse;
{
   /* INTERNAL VARIABLES */
  
 unsigned char MSB; 
   unsigned char LSB; 
  
 long i4;   
  
 int I256 = 256;

   if (reverse) {    /* IF BYTE ORDER TO BE REVERSED */
 
     /* MOVE INPUT STRING TO WORK STRING IN REVERSE BYTE ORDER */
      MSB = string[0];
      LSB = string[1];
/*      printf("\nreverse  %2.2x %2.2x %d %d\n", MSB, LSB, MSB, LSB); */
   
}
   else {

      /* MOVE INPUT STRING TO WORK STRING WITH NO CHANGE IN BYTE ORDER */
   
   MSB = string[1];
      LSB = string[0];
/*    printf("\nstandard %2.2x %2.2x \n", MSB , LSB);*/
   }
 
  
   /* MOVE WORK INTEGER TO OUTPUT LONG INTEGER */
      i4 = (unsigned long) (MSB * I256) ;
      i4 = i4 + LSB;
      *num = i4;
   /* RETURN SUCCESS */
   return(1);

}
/********************************************/
/*  write direct (random) access file of cell values */

void cells_out(int status)
{
 
 strcpy (file_name,base_name);

  strcat (file_name,"CE");
  strcat (file_name,cellid);
  strcat (file_name,".DDF");
  if (! beg123file (file_name,'R',&int_level,&ice,ccs,&fpin))
         {
          printf ("\nCAN'T OPEN CELL VALUES FILE %s.",file_name);
        
  return ;
    
      }
/*      Read data descriptive record (DDR)      */
if (! rd123ddrec 
        (fpin,          /* file pointer */
        string,         /* DDR record returned */
        &status))       /* status returned */

         {
    
     printf ("\n*** ERROR READING DDR ***");
  
       fprintf (fpdem,"\n*** ERROR READING DDR ***");
         
goto done;
    
     }
status = -1;
/*       Loop to process each subfield    
         */
do 
{
 /*      Read data record subfield    */
 if (! rd123sfld 
        (fpin,          /* file pointer */
        tag,            /* field tag returned */
        &leadid,        /* leader identifier returned */
        string,         /* subfield contents returned */
        &str_len,       /* string length */
        &status))       /* status returned */
         {
         printf ("\nERROR READING DATA RECORD SUBFIELD");
         goto done;
      
   }
/*      Retrieve description of current subfield        */

 if (! chk123sfld 
        (fpin,          /* file pointer */
        tag,            /* tag output */
        descr,          /* subfield descriptions output */
        frmts))          /* subfield format control */

         {
    
     printf ("\nERROR CHECKING DATA RECORD SUBFIELD, cells_out");
         fprintf (fpdem,"\nERROR CHECKING DATA RECORD SUBFIELD, cells_out");
         goto done;
         }

/*     only output if format is 2 byte binary format  */
  if (strstr (frmts, "B") != NULL)

       {
/*       memcpy (temp, string, str_len);*/
       strncpy (temp, string, (int)str_len);
       if (str_len == 2)
  
        {
   /*     If little endian, switch byte order within long word       
          (SDTS requires "big endian" representation           */
          if (!order)
                {
                s123tol2 (string, &li, 1);
                }
          else
                {
                s123tol2 (string, &li, 0);
                }
          col++;
          /* one value per line, for ease of debugging */
          fprintf (fpran,"%7ld\n",li); 
/*          fprintf (fpran,"%6ld",li);  */ /* trying to speed things up */
          }
   }
  /*       Output record/end of file delimeters                */
   if (status == 3)   /* subfield is at end of record */
        {
        row ++;
        if (maxcol < col) 
        {
         maxcol = col;
/*       printf ("max col = %d \n",maxcol);*/
        }
   
     col = 1;
       
/*       printf   ("\n##### End of Row %d ######", row);*/
      
  }
   else if (status == 4)   /* subfield is at end of file */
        {
/*       printf ("\n END OF RANDOM ACCESS FILE \n");
         printf ("rows = %ld cols = %ld \n", row, maxcol-1);*/
        }
} while (status != 4);   /* Break out of loop at end of file */
done:
/*done2:*/
/*       Close input ISO 8211 file        */
status = end123file (&fpin);
}
      
/*************************************************************************

            s u b r o u t i n e     d e m o u t
 function:
             this routine reads in the cell values for a cell map
             and writes it out in dem format
 routines
 called:     

  programmer
  sol katz, blm/sc344, sept 93

  revised by:
   sol katz, blm, march 1998  to work with generic grids

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

void dem_out()
{

double    xgo,ygo;
int       cmin,cmax,gmax,gmin  ; 
double    elodat,dphi,xcor[5],ycor[5];

long      jcol,imrow,nvals,incol;
long      ipos,ibot,nfirst,nlast,i,n,irow,icol;

long      ilast,nn,lastelev;
long      irec,icell;
int       cellval;
long      iaccu,ilevel,ipttrn,icoord,igunit;
long      izunit,isides;

char      dummy[7];
double    xmin,ymin;
long      missing = 0;

int crecord[11] = { 0,0,0,0,0,0,0,0,0,0,0 };
double resolu[4] = { 0.0, 0.0, 0.0, 1.0 };
double dproj[16] = { 0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0. };

ilevel=1;
ipttrn=1;
icoord=1;
igunit=2;
izunit=2;
isides=4;
iaccu=0;
irow=1;
imrow=1;
incol=1;
dphi = 0.0;
elodat = 0.0 ;

/*    initialize */

      irec = 1;
      icol = ncols;
/*    decode the header values and the passed arrays */
/*
      print*,corner;
      corner[3] south;
      corner[1] west;
*/
/*   look at old calculations 
      ymin    = SEY;
      xmin    = SEX;
      if ( SWY < SEY ) ymin = SWY;
      if ( SWX < SEX ) xmin = SWX;
      printf ("upperlx: %f upperly: %f\n",upperlx,upperly);
      printf ("1  xmin: %f,   ymin: %f\n",xmin,ymin);  
*/

      ymin = upperly  - ( nrows * height) ; 
      xmin = upperlx ; 
/*      printf ("2  xmin: %f,   ymin: %f\n",xmin,ymin);  */
/*    make them multiples of the cell dimensions */
      ymin = ( (long) ( (ymin / height) + .5 ) ) * height ;
      xmin = ( (long) ( (xmin / width) + .5 ) ) * width ;
/*      printf ("3  xmin: %f,   ymin: %f\n",xmin,ymin);  */

/*    south west */
      ycor[1] = SWY;
      xcor[1] = SWX;
/*    north west */
      ycor[2] = NWY;
      xcor[2] = NWX;
/*    north east */
      ycor[3] = NEY;
      xcor[3] = NEX;
/*    south east */
      ycor[4] = SEY;
      xcor[4] = SEX;


      cmin = 32767;
      gmin = cmin;
      cmax =-cmin;
      gmax = cmax;
      resolu[1] = width;
      resolu[2] = height;
      ipos = 0;

/*
     read in the cell values for each map column, starting
     at the bottom row
*/
      irec = 1;
      sprintf(buffer,"%-144s%6ld%6ld%6ld%6ld",title,ilevel,ipttrn,icoord,izone);
      for ( i = 1; i <= 15;i++ )
         {
         sprintf(short_buff,"%24.15e",dproj[i]);
         strcat ( buffer,short_buff);
         }
      sprintf(short_buff,"%6ld%6ld%6ld", igunit,izunit,isides);
      strcat ( buffer,short_buff);

      for ( i = 1; i <= 4;i++ )
      {
         sprintf(short_buff,"%24.15e%24.15e",xcor[i],ycor[i]);
         strcat ( buffer,short_buff);
/*          printf("%ld:  %24.15e%24.15e\n",i, xcor[i],ycor[i]);*/
      }

      
      sprintf(short_buff,"%24.15e%24.15e%24.15e%6ld",
         (float)minvalue,(float)maxvalue,dphi,iaccu);
      strcat ( buffer,short_buff);

      for ( i = 1; i <= 3; i++ )
         {
/*         sprintf(short_buff,"%12.6e",resolu[i]);  give wrong spacing */
         sprintf(short_buff,"%12.5e",resolu[i]);
         strcat ( buffer,short_buff);
         }

      sprintf(short_buff,"%6ld%6ld",irow,icol );
      strcat ( buffer,short_buff);
      fprintf(fpdem,"%-1024s",buffer);
      fprintf(fpdem,"\n");
         
      irec = irec + 1;

      printf ("total columns = %ld, total rows =, %ld\n",ncols, nrows);
      printf ("it will take %4.1f rows of *'s to process this dem\n",
               (float)ncols/80.0);


      for (col = 1; col <= ncols; col++)
      {
        strcpy (buffer,"");
        printf ("*");
        for (row = nrows; row >= 1;  row--)
        {
/*        printf ("col = %ld,  row = %ld \n",col, row);*/
/*        get the cell values at the row and column */

          icell = (long) ( ( ( (long)row - (long)1 
                             ) * (long)ncols
                           ) + (long)col - (long)1
                         ) * (long)reclen  ;

          fseek (fpran,icell,0) ;
          if (  fscanf (fpran,"%s", dummy) == EOF  )
          {
            printf ("icell, row, col = %d %d %d \n",icell,row,col);
            printf(" *demout*  error from input read \n");
            return;
          }

          cellval = atoi(dummy);
          if ( cellval < -9999 ) cellval = -9999;
          /*  assign to dem format  */
          idem[nrows-row+1] = cellval;
      } /* endfor (row = nrows; row >= 1;  row--) 

   /* here is where we write out the dem profiles*/
      nvals  = nrows;      
      jcol   = col;
      ibot   = 1;
/*    get rid of trailing -9999, missing data flag */ 
      for (nn = nvals; nn >= 1 ;nn--)
      {
           ilast = nn;
           if ( idem[nn] != -9999 ) break;
      }
      nvals = ilast;
/*    get rid of leading -9999, missing data flag;*/
      for (nn = 1; nn <= nvals; nn++ )
      {
           ibot = nn;
           if ( idem[nn] != -9999  ) break;
      }
/*       calculate column min and max;*/
      for (nn = ibot; nn<=nvals; nn++)
      {
           if ( idem[nn] < cmin ) cmin = idem[nn];
           if ( idem[nn] > cmax ) cmax = idem[nn];
      }
/*    printf("%ld %ld %ld %d %ld\n", row,col,icell, idem[row], icval); */
      nvals = nvals - ibot + 1;

/*    printf ("xmin= %f,  ymin= %f\n\n", xmin,ymin);  */
      xgo   = xmin + (float)(jcol - 1 ) * width;
      ygo   = ymin + (float)(ibot - 1 ) * height;
/*    printf(" xgo = %f, ygo = %f \n", xgo, ygo);*/
/*
      write b records.  note that the first record for each
      column will include the header and, at most, 146
      elevations.  each subsequent record for the column
      can hold 170 elevations
*/
      lastelev = ibot + nvals - 1;
      nfirst   = ibot;
/*     
      for ( n = 1; n <= nvals; n++ )
         {
         if (idem[n] == -9999) missing++ ;
         printf("%6d",idem[n]);
         }
      printf ("\n nfirst = %d, lastelev= %d\n",nfirst,lastelev);
*/
      nlast = ibot + 146 - 1;
      if ( lastelev < nlast )  nlast = lastelev;
/*      sprintf(buffer,"%6ld%6ld%6ld%6ld",imrow,jcol,nvals,incol);*/
      sprintf(buffer,"%6ld%6ld%6ld%6ld",imrow,jcol,nvals,(long)1);
      sprintf(short_buff,"%24.15e%24.15e%24.15e%24.15e%24.15e",
                     xgo,ygo,elodat,(float)cmin,(float)cmax);
      strcat(buffer,short_buff);
      for ( n = nfirst; n <= nlast; n++ )
         {
           sprintf(short_buff,"%6d",idem[n]);
           strcat(buffer,short_buff);
           if (idem[n] == -9999) missing++ ;
         }
      fprintf(fpdem,"%-1024s",buffer);
      fprintf(fpdem,"\n");
/*         printf ( "\ncol= %ld, nf= %ld, nl= %ld ",col,nfirst,nlast); */

      irec = irec+1;
      while (nlast != lastelev )
         {
         /* we have to process addition output lines */
         nfirst = nlast + 1;
         nlast  = nlast + 170;
         if ( lastelev <  nlast ) nlast = lastelev;
    
         strcpy (buffer, "");
  
         for ( n = nfirst; n <= nlast; n++ )
         {    

             sprintf(short_buff,"%6d",idem[n]);
             strcat(buffer,short_buff);
         }
         fprintf(fpdem,"%-1024s",buffer);
         fprintf(fpdem,"\n");
/*
      
         printf ("col= %ld, nf= %ld, nl= %ld ",col,nfirst,nlast);
*/
         irec = irec+1;
  
       }
   
        /* compute grid minimum and maximum */ 
        if ( cmin < gmin ) gmin = cmin;
        if ( cmax > gmax ) gmax = cmax;
      }
 
     /*  write record c */
  
      strcpy (buffer, " ");
      for ( i = 1; i <= 10; i++)
      {
        sprintf(short_buff,"%6d",crecord[i] );
        strcat(buffer,short_buff);
      }
      fprintf(fpdem,"%-1024s",buffer);
      fprintf(fpdem,"\n");

/*    write a summary to the screen  */
      printf("\n    final output usgs dem:\n\n" );
      printf(" min:             %8d\n",gmin );
      printf(" max:             %8d\n",gmax );
      printf(" missing value:   %8d\n",-9999 );
      printf(" missing count:   %8ld\n",missing );
      printf(" rows:            %8ld\n",nrows );
      printf(" cols:            %8ld\n\n",ncols );
      printf ("   Quad Boundary \n");
      printf ("SW %12.2f %12.2f\n",SWX,SWY);
      printf ("NW %12.2f %12.2f\n",NWX,NWY);
      printf ("NE %12.2f %12.2f\n",NEX,NEY);
      printf ("SE %12.2f %12.2f\n",SEX,SEY);
}

/*********************************************/
void get_nw_corner(void)
{
long sadr_x,sadr_y;

strcpy (file_name,base_name);
strcat (file_name,"RSDF.DDF");
if (! beg123file (file_name,'R',&int_level,&ice,ccs,&fpin))
         {
         printf ("\nERROR OPENING FILE %s",file_name);
         exit(0);
         }
if (! rd123ddrec      
        (fpin,          /* file pointer */
        string,         /* DDR record returned */
        &status))       /* status returned */
         {
         printf ("\n*** ERROR READING DDR ***");
       
  goto done;
  
       }
status = -1;
/*  
     Loop to process each subfield in Raster Definition module            */
do 
{
/*      Read data record subfield    */

 if (! rd123sfld 
        (fpin,          /* file pointer */
        tag,            /* field tag returned */
        &leadid,        /* leader identifier returned */
        string,      
   /* subfield contents returned */
        &str_len,       /* string length */
        &status))       /* status returned */
         {
   
      printf ("\nERROR READING DATA RECORD SUBFIELD (IDEN MODULE)");
      goto done;
   
      }
/*      Retrieve description of current subfield        */
 if (! chk123sfld 
        (fpin,          /* file pointer */
        tag,            /* tag output */
        descr,          /* subfield descriptions output */
        frmts))          /* subfield format control */
         {
         printf ("\nERROR CHECKING DATA RECORD SUBFIELD");
         goto done;
         }
/*    check subfield name and extract contents for each subfield       */
      if (!strcmp (tag, "SADR") && !strcmp (descr, "X"))
      {   

/*         Binary data, convert character string returned by rd123sfld to a
           long integer, changing bit order if necessary     */

           if (strstr (frmts,"B") != null)
           {
             if (!order)
                s123tol (string, &sadr_x, 1);
             else
                s123tol (string, &sadr_x, 0);
           }
      }
      else if (!strcmp (tag, "SADR") && !strcmp (descr, "Y"))
      {
/*         Binary data, convert character string returned by rd123sfld to a
           long integer, changing bit order if necessary     */

           if (strstr (frmts,"B") != null)
           {
             if (!order)
                s123tol (string, &sadr_y, 1);
             else
                s123tol (string, &sadr_y, 0);
           }
      }  
 } while (status != 4);   /* Break out of loop at end of file */
done:
stat2 = end123file (&fpin);

upperlx = (sadr_x * sfax ) + xorg;
upperly = (sadr_y * sfay ) + yorg;
/*
printf ("\nsadr_x:            %ld",sadr_x);
printf ("\nsadr_y:            %ld",sadr_y);
printf ("\nupperlx:           %f",upperlx);
printf ("\nupperly:           %f",upperly);
*/
return;
}

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

void get_iref(void)
{

/* set some default values */
sfax = 1.0;
sfay = 1.0;
xorg = 0.0;
yorg = 0.0;
strcpy (file_name,base_name);
strcat (file_name,"IREF.DDF");
if (! beg123file (file_name,'R',&int_level,&ice,ccs,&fpin))
         {
         printf ("\nERROR OPENING FILE %s",file_name);
         exit(0);
         }
if (! rd123ddrec      
        (fpin,          /* file pointer */
        string,         /* DDR record returned */
        &status))       /* status returned */
         {
         printf ("\n*** ERROR READING DDR ***");
       
  goto done;
  
       }
status = -1;
/*  
     Loop to process each subfield in Identification module            */
do 
{
/*      Read data record subfield    */

 if (! rd123sfld 
        (fpin,          /* file pointer */
        tag,            /* field tag returned */
        &leadid,        /* leader identifier returned */
        string,      
   /* subfield contents returned */
        &str_len,       /* string length */
        &status))       /* status returned */
         {
   
      printf ("\nERROR READING DATA RECORD SUBFIELD (IDEN MODULE)");
      goto done;
   
      }
/*      Retrieve description of current subfield        */
 if (! chk123sfld 
        (fpin,          /* file pointer */
        tag,            /* tag output */
        descr,          /* subfield descriptions output */
        frmts))          /* subfield format control */
         {
         printf ("\nERROR CHECKING DATA RECORD SUBFIELD");
         goto done;
         }
/*    check subfield name and extract contents for each subfield       */
      if (!strcmp (tag, "IREF") && !strcmp (descr, "SFAX"))
        sfax = atof(string)  ;
      else if (!strcmp (tag, "IREF") && !strcmp (descr, "SFAY"))
        sfay = atof(string)  ;
      else if (!strcmp (tag, "IREF") && !strcmp (descr, "XORG"))
        xorg = atof(string)  ;
      else if (!strcmp (tag, "IREF") && !strcmp (descr, "YORG"))
        yorg = atof(string)  ;
      else if (!strcmp (tag, "IREF") && !strcmp (descr, "XHRS"))
        xhrs = atof(string)  ;
      else if (!strcmp (tag, "IREF") && !strcmp (descr, "YHRS"))
        yhrs = atof(string)  ;
 } while (status != 4);   /* Break out of loop at end of file */
width  = xhrs;
height = yhrs; 
done:
stat2 = end123file (&fpin);
/*
printf ("\nsfax:            %f",sfax);
printf ("\nsfay:            %f",sfay);
printf ("\nxorg:            %f",xorg);
printf ("\nyorg:            %f",yorg);
*/
return;
}

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


