/*************************************************************************
/* v09xx2adr.c  06Apr12 **************************************************
/* duplicate vhex2adr code using the raw2 files,
/* which have the ADP data embedded in them
/*-----this outputs the adpYYMXXXnn.adr file of same format as old files
/************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include "base_fnx.h"
#include "base_raw2.h" //includes the extern global declarations

// definitions -------------------------------------------
#define NMAX 500 // max # ensembles expected per each file
#define ND_MAX 3000  // max # dives expected
#define NLINE 512  // max # char per each line
#define NBEAM 3   // # of beams in the system
#define MAXCELL 5 // max # of cells
#define BD0 4.0 // default blanking distance
#define PGAIN 0.04; // SBE pressure gain
#define DTMIN 0.002   // 0.002 day = 2.9 minutes: dt match for .satI w/flash

// globals ------------------------------------------------
FILE  *fp_in, *fp_out, *fp_alt, *fpdbg;
char predat[] = "k:\\d_spray\\data\\"; // location of the data directories
int sn, m_id;   // Spray s/n plus mission id = m_id
char datdir[4]; // YYM of the data directory
char Vline[NLINE]; // copy of the V header line
char CD58[NLINE]; // Doppler calibration line
char MD[NLINE]; // Mission-Description line

// globals for each V file data
int pr[NMAX], he[NMAX], pi[NMAX], ro[NMAX]; // press, heading, pitch, roll
int no[NBEAM][NMAX]; // noise level for each  beam
int vel[NBEAM][MAXCELL][NMAX]; // velocity array
int amp[NBEAM][MAXCELL][NMAX]; // return amplitude array

//globals for the altimeter file
int adive[ND_MAX], z_alt[ND_MAX], iqc[ND_MAX], inn[ND_MAX];
long a_ux_tm[ND_MAX];

// globals for the data in a 'V' line
int Vid, NC, CS, PL, Vdive, P0, Gyr, Gdd, Gwk, Gwd;
float Gutc, Glat, Glon;
float Blankd = BD0; // set to the default value.
float Dp1;

// for the Doppler 'B1' line.
   int ncell[ND_MAX], cs[ND_MAX], pulse[ND_MAX], snr[ND_MAX];
   float pb1[ND_MAX];
   
// read in from the .raw file
   int GPS_yr[ND_MAX];
   float GPS_yd[ND_MAX], Xlat[ND_MAX], Xlon[ND_MAX];

//     following are used for the sbd .log file
   int   sbddive[ND_MAX], PSurf[ND_MAX], Alt[ND_MAX];
   float syd1[ND_MAX], syd2[ND_MAX], acq1[ND_MAX], acq2[ND_MAX];
   float odx[ND_MAX], ody[ND_MAX];
   int MaxDive=0;


// prototypes ---------------------------------------------
int    read_sat     ( char fname[] );
void   read_alt     (  void );
void   write_adr_header  ( int i0, int n );
void   write_adp_data    ( int ipro );

//*****************************************************************
//*****************************************************************
//*****************************************************************
int main(int argc, char *argv[])   //******************************
{
	int n, ipro, npts, jEng;

	char Rawfile[NLINE];
	char outfile[NLINE], altfile[NLINE], satfile[NLINE];

   // read in the arguments ----------------------------------------
   switch (argc) //-------------------------------------------------
   { // read in the variables
   		case 4 : sscanf(argv[3],"%d",&m_id);
   		case 3 : sscanf(argv[2],"%d",&sn);
   		case 2 : sscanf(argv[1],"%s",datdir);
   } // end switch
   			// now query the rest of the variables
   switch (argc)
   { // query for the rest
   		case 1 :	printf ("Give 3-char date YYM to process\n");
   					scanf("%s",datdir); 
   		case 2 :	printf("Give s/n to process for date %s\n",datdir);
   					scanf("%d",&sn);
   		case 3 :	printf("Give the mission id \n");
   					scanf("%d",&m_id);
   } // end switch ------------------------------------------------
   // -------------------------------------------------------------

	printf("Program will create the '.ADR' ascii file\n");

   	// create the file names --------------------------------------
   	sprintf(Rawfile,"%s%s\\%s%03d%02d.raw2",  predat,datdir,datdir,sn,m_id); // raw file
   	sprintf(outfile,"%s%s\\adp%s%03d%02d.ADR",predat,datdir,datdir,sn,m_id); // ADR file
   	sprintf(satfile,"%s%s\\%s%03d%02d.sat",predat,datdir,datdir,sn,m_id); // sat file
   	sprintf(altfile,"%s%s\\%s%03d%02d.alt",predat,datdir,datdir,sn,m_id); // alt file
	printf("input is from %s\n",Rawfile);
	printf("output will go to %s\n",outfile);
	// open the input file -------------
	fp_in  = fopen(Rawfile,"r"); 
	if (fp_in == NULL)
	{  
	   printf("Open input file failed: %s\n",Rawfile);
	   return 0;
	}
	// open the output file ------------
	fp_out = fopen(outfile,"w"); 
	if (fp_out==NULL)
	{  
	   printf("Open outfile failed: %s\n",outfile);
	   return 0;
	}
    //----- open debug files -------------
	fpdbg = fopen("c:\\d_spray\\data\\raw_dbg.txt","w");
	
	// read in the sat file info ---------
	read_sat( satfile );
	

	// open the altimeter file -----------
	fp_alt = fopen(altfile,"r"); 
	if (fp_alt==NULL)
	{  
	   printf("Open altfile failed: %s\n",altfile);
	   return 0;
	}
	// read in the altimeter info ----------------------------------
	read_alt();
	fclose(fp_alt);
	//--------------------------------------------------------------
	
    init_global0(); // initialize the global arrays
    //--get the first dive info
    ipro = get_dive_mark(fp_in); // get first dive marker info
    // data stored in global values
	
	do //==========================================================
	{ // read in dives until no more ------------------------------
        
        init_pro_global(); // zero out profile arrays
        npts=-1; jEng=-1; // init to bad value
        ipro = get_dive (fp_in, &npts, &jEng); //ipro=NEXT profile #
        n = jEng; //profile # from the engineering packet
        
        if (npts>0) 
        { // then valid, write out debug line
           //process the data from this profile
           //get_alt( npts, jEng );
           //write out debug line
           // K_adp = #ADP data lines
           write_adr_header(n, K_adp);
           write_adp_data(n);
           
           fprintf(fpdbg,"Pro %4d %4d    %12ld %12ld %6d \n",
                       n, UxSrf[n],UxTm1[n],UxTm2[n], npts );

        } 

    } while (ipro>0  && ipro< ND_MAX ); //ND_MAX); 
    //=============================================================
    
    
    // clean up ---------------------------------------------------
	fclose(fp_in);
	fclose(fp_out);
	fclose(fpdbg);


	return 0;
} //***************************************************************************
//*****************************************************************************
//*****************************************************************************


void  read_alt( void ) //******************************************************
{ // read altimeter data from the .alt file
  char s[NLINE];
  int i=0, n, k, depth, nn, qc;
  float y;
  
    do // ------------------------------------------------------------
     { // read in until EOF
        n = fget_line(fp_alt, s, NLINE);
        if (n>0) //,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
        { // then store
             sscanf(s,"%d %f %d %d %d",&k, &y, &depth, &qc, &nn);
             if (k>0 && k<ND_MAX ) //.............
             {
                a_ux_tm[k] = y; // unix time
                z_alt[k] = depth;
                iqc[k] = qc;
                inn[k] = nn;
             } //................................
        } // end if n>0 ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
        i++;
     } while (n>0);  //-----------------------------------------------
     printf("%d lines read in from alt\n",i);

  return;
} //***************************************************************************


//*****************************************************************************
int  read_sat( char fname[] ) //***********************************************
{ // read in the CD58 line
  // return 0=error, 1=successful
  FILE *fp;
  int i=0, n;
  char s[NMAX];
     
     fp = fopen(fname,"r"); // open up the file
     if (fp==NULL)
     { printf("sat file not found: %s\n",fname);
       return(0);
     }
     
    do // -------------------------------------------------------------
     { // read in until EOF or first 100 lines
        n = fget_line(fp, s, NMAX);
        if (n>0) //nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
        { // then process
           // printf("%s\n",s); /**/
           if (  s[0] == 'M' && s[1] == 'D' )//,,,,,,,,,,,,,,,,,,
           {
             strcpy(MD, s); // store the Mission Description line.
             printf("%s\n",MD );
           }
           else if (  s[0] == 'C' && s[1] == 'D' )
           {
             strcpy(CD58, s); // store the CD calibration line.
             printf("%s\n",CD58);
             n=-1; //set to exit loop
           }//,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
             
        } // end if n>0 nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
        i++;
     } while (n>0 && i<100);  //---------------------------------------
     fclose (fp);
     
  return(1);
} //***************************************************************************


void   write_adr_header( int ipro, int num ) //********************************
{ // write out the adp info line, 'V', for profile ipro

  int   i, day, psurf, isurf, yr, yr2, ncell, cs, pulse, ncol;
  float yday, yday2, utc=0, t, xlat, xlon, bin0, dt, bd;
  //char *s;
  long uxt;
  struct tm *uxtm;
  
  psurf = Eng[ipro][Eng_PSURF]; // surface pressure
  isurf = Eng[ipro][0]; //surface dive # corresponding to this profile #
  //--get year and year-day of the start-dive
  yr    = GPS[1][isurf][GPS_YEAR]; // gps year
  yday  = GPS[1][isurf][GPS_YDAY]; // gps year-day
  xlat  = GPS[1][isurf][GPS_LAT]; // gps latitude
  xlon  = GPS[1][isurf][GPS_LON]; // gps longitude
  //-- or alternatively, can use the CF_DIVE start time
  uxt = UxTm2[ipro]; //=start time from the flash card
       //UxTm2[ipro] = start-time for this profile
  //s = ctime( &uxt);
  // s[ strlen(s) -1] = 0;
  uxtm = gmtime( &uxt );
  yr2 = uxtm->tm_year + 1900; // year
  day = uxtm->tm_yday; //day since Jan 1
  day++; //the +1 is so 1.0 = Jan1 0000 UTC
  t = (uxtm->tm_sec/60. + uxtm->tm_min)/60 + uxtm->tm_hour;
  utc = t; //keep a copy of hr:min
  yday2 = t/24.0 + day; 
  dt = yday2 - yday; // error with time
  if (dt<0) dt=-dt;
  if (dt>0.01) 
  { // gps time is screwy, must be no fix
    xlat=0; xlon=0;
  }
  
  //--debugging shows the above agrees for GPS/CF flash dive mark
  // CF dive mark will always be correct, so just use that
  //fprintf(fpdbg,"v %4d %4d %6d %6d %8.4f %8.4f\n",isurf, ipro,yr, yr2, yday, yday2);
  
  //--ADP header info
  bd    = Hadp[ADP_BD]*0.1;    //blanking distance
  ncell = Hadp[ADP_NCELL]; //last read #cells
  cs    = Hadp[ADP_CSIZE]; //cell size
  pulse = Hadp[ADP_PULSE]; //pulse length
  bin0  = Hadp[ADP_BIN0]*0.1;  //center of first bin

/* following is the original V output line
     fprintf(fp_out,"V %04d %2d %2d %2d %4.1f"
     " %04d %4d %4d %3d %5d %2d %7.4f %+11.5f %+11.5f\n",
     ipro, ncell, cs, pulse, bin0,
     isurf, psurf, yr2,day, 0, 0, utc, xlat, xlon ); 
*/
// following is the ADR output line
   // write the basic header info
   fprintf(fp_out,"-99 %4d %10.5f %3d %3d %4.1f %4.1f %4.1f",
      ipro, yday2, num, ncell,(float) bd, (float) cs, (float) pulse);
   // write the distances to each cell
   for (i=0;i<ncell;i++)
     fprintf(fp_out, " %5.2f", bin0 + cs*i);
   
   // write out the altimeter depth guess
   fprintf(fp_out," %4d %2d %1d ",z_alt[ipro],iqc[ipro], inn[ipro] );

   // fill the rest out with blanks
   ncol = ncell*6 + 3 + 4; // total #param=amp,vel, noise, pitch+roll+head+pr
   i = ncell + 8 +3; // #already written out
   for (i=ncell+8;i<ncol;i++) fprintf(fp_out," 0");
   //and finish the line
   fprintf(fp_out,"\n" );

  
  return;
} //***************************************************************************



void   write_adp_data  ( int ipro ) //*****************************************
{ // write out all of the data lines for the present dive subset
  int i, j, k, psurf, ncell, kk;
  float press, pitch, roll, head;
  
  psurf = Eng[ipro][Eng_PSURF]; // surface pressure
  ncell = Hadp[ADP_NCELL]; //last read #cells
  if (ncell>MAXCELL) ncell=MAXCELL;
  //printf("adp_write %d\n",K_adp);


  for (k=0;k<K_adp; k++) //-----------------------------------------------
  {  // write out data for each scan
     // start with the header info ..............................
     press = ( Dadp[k][DADP_PR] - psurf )*PGAIN; // dBar depth
     pitch = Dadp[k][DADP_PI]*0.4; // pitch degrees
     roll  = Dadp[k][DADP_RO]*0.4; // roll degrees
     head  = Dadp[k][DADP_HE]*0.1; // compass heading
     fprintf(fp_out,"%7.1f %5.1f %5.1f %5.1f",
        press, pitch, roll, head);
        
     //next is the noise .........................................
     for (j=0;j<NBEAM;j++)
       fprintf(fp_out," %3d", Dadp[k][DADP_NO+j] );
       
     //next is the return signal amplitude........................
     kk = DADP_AMP; // points to amplitude
     for (j=0;j<NBEAM;j++)
     { // do for each beam ...........
       for (i=0; i<ncell; i++) //do for ea cell
          fprintf(fp_out," %3d", Dadp[k][kk++] );
     } // end for ea beam
     
     //last is the velocity ......................................
     for (j=0;j<NBEAM;j++)
     { // do for each beam ...........
       for (i=0; i<ncell; i++) //do for ea cell
          fprintf(fp_out," %5d", Dadp[k][kk++] );
     } // end for ea beam
     
     //finish the line
     fprintf(fp_out,"\n" );
  } // end for i ------------------------------------------------------
   
  return;
} //***************************************************************************






//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
