// This version works with the Windows 7 version of SAC
// modified 4/15/15 
#include <conio.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

#define YES     0
#define NO      1
#define char_size 120
#define char_size2 520
#define nxs_files 20     // max number of xs files
#define nlines  1500     // max number of lines in SAC input
#define RUNSAC  YES
void pause();

main(int argc, char *argv[])
{
FILE	*in, *inxs, *inwse[nxs_files], *outSAC, *outgo, *insacout, *qout, *qcsv;
char    line[char_size2], check_str[char_size], xs_file[char_size], wse_file[nxs_files][char_size], out_file[char_size], out_filet[char_size];
char    SACline[nlines][char_size], wse_check[12], min[char_size], xs_str[12], SACOUT_file[char_size];
char    teststr[44], xs1str[12], xs2str[12], out_dir[char_size], t1[128], t2[128], t3[128], t4[128], t5[128], t6[128], secid[12];
int nxs, i, nl, k, it, dt, time, first = YES, PRINT, lookforQ, WRITE_HEADERS = YES, nq;
float wse[nxs_files], *q, qt, avg, max, dq, datetime, qi;


printf("Running CSA2SAC. Documentation for the program is: \nWiele, S.M., 2015, CSA2SAC Manual, USGS Open-File Report 2015-1229, 4p. \n");

in = fopen("csa2sac7.in", "r");
if(in == NULL)
  {
  printf("Can't find csa2sac7.in");
  pause();
  exit(0);
  }
memset(line, '\0', char_size2);
while(fgets(line, char_size2, in) != NULL)
  {
  memset(check_str, '\0', char_size);
  sscanf(line, "%s", check_str);
  printf("%s\n", check_str);
  memset(line, '\0', char_size2);
  if(strcmp(check_str, "#") != YES) break;
  }
memset(out_dir, '\0', char_size);
strcpy(out_dir, check_str);

printf("The output directory is %s.\n", &out_dir);
fgets(line, char_size2, in);
memset(out_file, '\0', char_size);
//sscanf(line, "%s", out_file);
//printf("The output file is %s.\n", &out_file);
fgets(line, char_size2, in);
memset(xs_file, '\0', char_size);
sscanf(line, "%s", xs_file);
printf("The cross section file is %s.\n", &xs_file);             
i = 0;
memset(wse_file[0], '\0', char_size);
fgets(line, char_size2, in);
memset(wse_file[0], '\0', char_size);
sscanf(line, "%s", wse_file[0]);
printf("The stage file is %s.\n", &wse_file[0]);
fgets(line, char_size2, in);
sscanf(line, "%d", &nxs);
printf("There are %d cross sections.\n", nxs);
nq = 0;
for(i = 1; i < nxs; i++) nq += i;
q = (float*)malloc(sizeof(float)*nq);

inxs = fopen(xs_file, "r");
if(inxs == NULL)
  {
  printf("Can't find %s.\n", xs_file);
  pause();
  exit(0);
  }

  inwse[0] = fopen(wse_file[0], "r");
  if(inwse[0] == NULL)
     {
     printf("Can't find %s.\n", wse_file[0]);
     pause();
     exit(0);
     }

if(RUNSAC == YES)
   {
   qcsv = fopen("q.csv", "w");
   }
i = 0;
while(fgets(SACline[i], 120, inxs) != NULL)
  {
  printf("%s", SACline[i]);
  if(i >= nlines)
    {
    printf("Increase number of lines allowed and recompile.\n");
    pause();
    exit(0);
    }
  i++;
  }
nl = i;
it = 2; // time index
dt = 1;
while(fscanf(inwse[0], "%f", &datetime) != EOF)
  {
  for(i = nxs-1; i >= 0; i--)
    {                                                         
    fscanf(inwse[0], "%f", &wse[i]);
    printf("%d %g\n", i, wse[i]);
    }
  memset(out_filet, '\0', char_size);
  time = it*dt;
  itoa(time, min, 10);              // make an output name
  it++;
  strcpy(out_filet, out_dir);
  strcat(out_filet, "\\");
  //strcat(out_filet, out_file);
  //strcat(out_filet, min);
  strcpy(SACOUT_file, out_filet);   // this is the file SAC writes to

  strcat(out_filet, "SACinput");
  strcat(SACOUT_file, "SACoutput");
  strcat(out_filet, min);
  strcat(SACOUT_file, min);
  strcat(out_filet, ".txt");
  strcat(SACOUT_file, ".txt");
 
  outSAC = fopen(out_filet, "w");
  if(outSAC == NULL)
    {
    printf("\n\n  %s not open. Did you create the directory for SAC files?\n", out_filet);
    pause();
    exit(0);
    }
  k = 0;
  for(i = 0; i < nl; i++)         // i is the line index in the SAC/xs file
    {
    sscanf(SACline[i], "%s %s", wse_check, xs_str);
    if(strcmp(wse_check, "HP") == YES)
      {
      //sscanf(SACline[i], "%*s %s", secid);
      fprintf(outSAC, "HP    X%d    %g\n", nxs - k, wse[k]);
      k++;
      }
    else fprintf(outSAC, "%s", SACline[i]);
    }
  fclose(outSAC);
  outgo = fopen("sac.in", "w");
  fprintf(outgo, "%s\n", out_filet);
  fprintf(outgo, "%s\n", SACOUT_file);
  fprintf(outgo, "CSA\n");
  fclose(outgo);
  if(RUNSAC == YES)
    {  //4
    k = 0;
    if(WRITE_HEADERS == YES) fprintf(qcsv, "date_time");
    system("SAC7 < sac.in");              // run SAC                            
    insacout = fopen(SACOUT_file, "r");
    lookforQ = NO;                   // get Q from SAC output

    // find discharges and write to file

    PRINT = NO;
    k = 0;
    while(fgets(line, char_size2, insacout) != NULL)
      {    //3
      memset(teststr, '\0', 44);
      sscanf(line, "%s", teststr);
      if(strcmp(teststr, "DISCHARGE") == YES) lookforQ = YES;
      if(lookforQ == YES)
       if(strncmp(teststr, "X", 1) == YES)  // This line is why the secid has to be "X"
        {
        printf("%s", line);
        sscanf(line, "%s %s %s %s %s %f", &t1, &t2, &t3, &t4, &t5, &q[k]);
        if(WRITE_HEADERS == YES) fprintf(qcsv, ", %s%s%s", t1, t2, t3 );
        //printf("     %s %s %s %f\n", t1, t2, t3, q[k]);
        k++;
        }
       memset(line, '\0', char_size2);
       }  //3
      if(WRITE_HEADERS == YES)
         {
         for(i = 0; i < nxs; i++) fprintf(qcsv, ", PT%d", i+1);
         fprintf(qcsv, "\n");
         }
      fprintf(qcsv, "%f", datetime);
      for(i = 0; i < nq; i++) fprintf(qcsv, ", %g", q[i]);
      for(i = nxs - 1; i >= 0; i--) fprintf(qcsv, ", %g", wse[i]);
      WRITE_HEADERS = NO;
      fprintf(qcsv, "\n");
      fclose(insacout);
      }   //4
  }

fclose(inxs);
fclose(inwse[0]);
fclose(outSAC);
fclose(qout);
fclose(qcsv);
if(in != NULL) fclose(in);
if(outgo != NULL) fclose(outgo);
if(insacout != NULL) fclose(insacout);
pause();
}


void pause()
  {
  printf("\nHit any ket to continue\n");
  getch();
  }