/**---------------------------------------------------------------------------
 ** 
 ** sbe.c -- Reading SBE data files
 ** 
 ** Author          : Pierre Jaccard
 ** Created On      : 1999/07/15 16:17:06
 ** Last Modified By: Pierre Jaccard
 ** Last Modified On: 1999/07/16 20:09:14
 ** Update Count    : 6
 ** Directory       : /home/pego/pcd1/codas3c/gfi/src/libs/ctd/
 ** Version         : 0.0
 ** Status          : Unknown
 ** ---------------------------------------------------------------------- ** 
 ** DESCRIPTION: 
 ** 
 **    This file provides functions to read data from ASCII CTD SBE files.
 ** 
 ** ---------------------------------------------------------------------- ** 
 ** REVISIONS: 
 ** ---------------------------------------------------------------------- ** 
 ** CHANGES: 
 **------------------------------------------------------------------------**/

#include "sbe.h"

/* ------------------------------------------------------------------
	 Read the header file and fills appropriate variables

   RETURNS: non-zero on error
	 ------------------------------------------------------------------ */
#if PROTOTYPE_ALLOWED
int get_sbe_header(/* Pointer xto ASCII header file */
                   FILE *fpasc, 
                   /* Place for configuration data */
                   CONFIGURATION_1_TYPE *conf, 
									 /* Place for ancillary data */
                   ANCILLARY_1_TYPE *anc, 
                   /* Place for time data */
                   YMDHMS_TIME_TYPE *time, 
									 /* Place for position data */
                   DMSH_POSITION_TYPE position[], 
                   /* Place for profile comments */
                   char profile_comment[])
#else
     int get_sbe_header(fpasc, conf, anc, time, position, profile_comment)
     FILE                 *fpasc;
     CONFIGURATION_1_TYPE *conf;
     ANCILLARY_1_TYPE     *anc;
     YMDHMS_TIME_TYPE     *time;
     DMSH_POSITION_TYPE   position[];
     char                 profile_comment[];
#endif
{
   char   header_line[85], tmp[85], str[85], *tok;
   int    status, done;
	 SHORT  deg, min, hun;
   long   hundredths;
	 NAME_LIST_ENTRY_TYPE *list;
	 NAME_LIST_ENTRY_TYPE months[13]=
	 {{"Jan",  1}, {"Feb",  2}, {"Mar",  3}, {"Apr",  4}, 
		{"May",  5}, {"Jun",  6}, {"Jul",  7}, {"Aug",  8}, 
		{"Sep",  9}, {"Oct", 10}, {"Nov", 11}, {"Dec", 12},
		{NULL, 0}};

   set_byte((UBYTE *) header_line, (UBYTE) '\0', sizeof(header_line));
   set_byte((UBYTE *) profile_comment, (UBYTE) '\0', 40);

	 /* Get the time */
	 fseek(fpasc, 0L, 0L);
	 while(strstr(header_line, "System UpLoad Time") == NULL)
		 if(error_found(fgets(header_line, 85, fpasc) == NULL,
										"Cannot find time"))
			 return(EOF);
	 strcpy(str, header_line);
	 tok = strtok(str, " ");
	 done = 0;
	 while(tok && !done){
		 list = months;
		 while((list->name != NULL) && (strcmp(tok, list->name) != 0))
			 list++;
		 if(list->name)
			 done = 1;
		 tok = strtok(NULL, " ");
	 }
	 if(error_found(!done, "Unable to get month string"))
		 return(1);
	 time->month = (USHORT) list->code;
	 tok = strstr(header_line, tok);
	 strcpy(str, tok);
	 status = sscanf(str, "%2hu %4hu %2hu:%2hu:%2hu", 
									 &(time->day), &(time->year),
									 &(time->hour), &(time->minute), &(time->second));
	 if(error_found(status != 5, "Reading time"))
		 return(1);
	 if(error_found(invalid_time(time), "Invalid time"))
		 return(1);
	 
	 /* Get latitude */
	 fseek(fpasc, 0L, 0L);
	 while(strstr(header_line, "Latitude") == NULL)
		 if(error_found(fgets(header_line, 85, fpasc) == NULL, 
										"Cannot find latitude"))
			 return(EOF);
	 strcpy(str, header_line);
	 tok = strtok(str, " ");
	 while(tok &&
				 !((isdigit(tok[0])) || 
					 ( ((tok[0] == 'N') || (tok[0] == 'S')) && isdigit(tok[1])))  )
		 tok = strtok(NULL, " ");
	 if(error_found(!tok, "Cannot process latitude"))
		 return(1);
	 tok = strstr(header_line, tok);
	 strcpy(str, tok);
	 if(isdigit(str[0]))
		 status = sscanf(str, "%hd%*c%hd%*c%hd%s", &deg, &min, &hun, tmp);
	 else{
		 status = sscanf(str, "%c%hd%*c%hd%*c%hd", tmp, &deg, &min, &hun);
		 tmp[1] = '\0';
	 }
	 if(error_found( status != 4, "Reading latitude"))
		 return(1);
	 hundredths = deg * 360000 + min * 6000 + hun * 60;
	 if(strchr(tmp, 'S'))
		 hundredths *= -1;
	 /* Latitude corresponds to `y' and must be the second element in
			the position array */
	 HUNPOS(position+1, &hundredths);
	 if(error_found(invalid_position(position+1, 1), "Invalid latitude"))
		 return(1);

	 /* Get longitude */
	 fseek(fpasc, 0L, 0L);
	 while(strstr(header_line, "Longitude") == NULL)
		 if(error_found(fgets(header_line, 85, fpasc) == NULL,
										"Cannot find longitude"))
			 return(EOF);
	 strcpy(str, header_line);
	 tok = strtok(str, " ");
	 while(tok &&
				 !((isdigit(tok[0])) || 
					 ( ((tok[0] == 'E') || (tok[0] == 'W')) && isdigit(tok[1])))  )
		 tok = strtok(NULL, " ");
	 if(error_found(!tok, "Cannot process longitude"))
		 return(1);
	 tok = strstr(header_line, tok);
	 strcpy(str, tok);
	 if(isdigit(str[0]))
		 status = sscanf(str, "%hd%*c%hd%*c%hd%s", &deg, &min, &hun, tmp);
	 else{
		 status = sscanf(str, "%c%hd%*c%hd%*c%hd", tmp, &deg, &min, &hun);
		 tmp[1] = '\0';
	 }
	 if(error_found( status != 4, "Reading longitude"))
		 return(1);
	 hundredths = deg * 360000 + min * 6000 + hun * 60;
	 if(strchr(tmp, 'W'))
		 hundredths *= -1;
	 /* Longitude corresponds to `x' and must be the first element in
			the position array */	 
	 HUNPOS(position, &hundredths);
	 if(error_found(invalid_position(position, 0), "Invalid longitude"))
		 return(1);

	 /* Get station number */
	 fseek(fpasc, 0L, 0L);
	 while(strstr(header_line, "Station") == NULL)
		 if(error_found(fgets(header_line, 85, fpasc) == NULL,
										"Cannot find station number"))
			 return(EOF);
	 strcpy(str, header_line);
	 tok = strtok(str, " ");
	 while(tok && !(isdigit(tok[0])))
		 tok = strtok(NULL, " ");
	 if(error_found(!tok, "Cannot process station number"))
		 return(1);
	 tok = strstr(header_line, tok);
	 strcpy(str, tok);
	 status = sscanf(str, "%hu", &(anc->station));
	 if(error_found( status != 1, "Reading station number"))
		 return(1);
	 
	 /* Get depth */
	 fseek(fpasc, 0L, 0L);
	 while(strstr(header_line, "depth") == NULL)
		 if(error_found(fgets(header_line, 85, fpasc) == NULL,
										"Cannot find depth"))
			 return(EOF);
	 strcpy(str, header_line);
	 tok = strtok(str, " ");
	 while(tok && !(isdigit(tok[0])))
		 tok = strtok(NULL, " ");
	 if(error_found(!tok, "Cannot process depth"))
		 return(1);
	 tok = strstr(header_line, tok);
	 strcpy(str, tok);
	 status = sscanf(str, "%f", &(anc->ocean_depth));
	 if(error_found( status != 1, "Reading ocean depth"))
		 return(1);
	 
	 /* Skipping profile comments */
	 
	 /* Filling */
	 anc->cast_num = 1;
	 anc->end_time = BADUSHORT;
	 anc->aver = anc->rate = BADFLOAT;
	 strcpy((char *) conf->ship_name, (char *) SHIP_NAME);
	 strcpy((char *) conf->cruise_id, (char *) CRUISE);
	 strcpy(profile_comment, "NO COMMENT");

	 return(0);

}

/* ------------------------------------------------------------------
   Get data from the bottle file, and fill appropriate variables.

   RETURNS: number of bottles in file
   ------------------------------------------------------------------ */
#if PROTOTYPE_ALLOWED
int get_sbe_bottles(/* Pointer to bottle file */
                    FILE *fpbtl, 
                    /* Place for ancillary data */
                    ANCILLARY_1_TYPE *anc,
										/* Place for bottle ancillary data */
                    BTL_ANCILLARY_1_TYPE *btl_anc, 
                    /* Array of bottle data, where data[n-1][i] is the ith
                       data of the nth bottle, index i having the following
                       meanings: (0)=salinity, (1)=pressure, (2)=temperature
                       and (3)=conductivity */
                    FLOAT *data) 
#else
int get_sbe_bottles(fpbtl, data)
FILE   *btlname;
double *data;
#endif
{
	
	int n;
	char line[200], scan_format[100];
	FLOAT sal, p, temp, cond;
	
	/* Initializations */
	n = 0;

	/* Loop through the file */
	while(fgets(line, 200, fpbtl) != NULL){
		
		/* Check for bottle data */
		if(strstr(line, "(avg)")){
			strcpy(scan_format, " %*d %*3c %*d %*d %f %*f %f %f %f %*s");
			if(sscanf(line, scan_format, &sal, &p, &temp, &cond) < 4){
				printf("\n ERROR: Scanning bottle for n = %d", n);
				return(-1);
			}
			*(data + 4*n + 0) = sal; 
			*(data + 4*n + 1) = p; 
			*(data + 4*n + 2) = temp; 
			*(data + 4*n + 3) = cond; 
			n++;
		}
	}
	
	/* Fill the ANCILLARY_1 structure */
	if(n > 0){
		btl_anc->station     = anc->station;
		btl_anc->num_bottles = (USHORT) n;
		btl_anc->ocean_depth = anc->ocean_depth;
	}
	
	return(n);

}
			
	
	
	
	

