#include <stdio.h>
#include <string.h>
#include <math.h>
#include "dbext.h"
#include "ioserv.h"
#include "vector.h"
#include "use_db.h"
#include "vstat.h"
#include "pos_to_m.h"
#include "adcp.h"
#include "adcpsect.h"


int seq_cor = FALSE;             /* global flag for sequential correlation */
extern   char out_filename[];
static   int   first_seq_cor = 1;
static   int seqcor_bins[2];
static   char seqcor_filename[NPATHMAX];
static   FILE  *fp_seqcor;


PARAMETER_LIST_ENTRY_TYPE seqcor_params[] =
{
   {" bin_range:" , " %d"     , seqcor_bins        , TYPE_INT},
   {" to"         , " %d"     , seqcor_bins + 1    , TYPE_INT},
   {NULL          , NULL      , NULL               , 0}
};

#if PROTOTYPE_ALLOWED
int init_seqcor(FILE *fp_cnt)
#else
int init_seqcor(fp_cnt)
FILE *fp_cnt;
#endif
{
   check_error(get_parameters(fp_cnt, seqcor_params, NULL),
                  "sequential_cor parameters");

   /* convert from bin numbers starting from 1 to array indices from zero */
   seqcor_bins[0]--;
   seqcor_bins[1]--;
   seq_cor = TRUE;
   /* Make a seqcor output file name, and open the file. */
   new_extension(seqcor_filename, out_filename, ".cor");
   fp_seqcor = check_fopen(seqcor_filename, "w");
   return(0);
}

#if PROTOTYPE_ALLOWED
void sequential_correlation(FILE *fp_seqcor, float *u, float *v, double time, int n)
#else
void sequential_correlation(fp_seqcor, u, v, time, n)
FILE *fp_seqcor;
float *u, *v;
double time;
int n;
#endif
{
   static   float prev_u[NDMAX_NG];
   static   float prev_v[NDMAX_NG];
   static   double prev_time;
   static   int   prev_nu;

   int i;
   int n_min;
   int ngood;
   double dt;
   double amp, phase;


   if (!first_seq_cor)
   {
      dt = (time - prev_time) * 86400.0;   /* seconds */
      n_min = min_val(n, prev_nu);
      ngood = inner_correlation(prev_u, prev_v, u, v, n_min, &amp, &phase);
      fprintf(fp_seqcor, "%12.6f  %5.3f  %6.1f  %6.0f   %2d\n",
                           time, amp, phase, dt, ngood);
   }
   /* Move u, v into prev_u, prev_v. */
   for (i=0; i<n; i++)
   {
      prev_u[i] = u[i];
      prev_v[i] = v[i];
   }
   prev_nu = n;
   prev_time = time;
   first_seq_cor = 0;
}                       /* sequential_correlation() */

#if PROTOTYPE_ALLOWED
void calc_seqcor(float *adj_u, float *adj_v, int adj_nu, double ddtime)
#else
void calc_seqcor(adj_u, adj_v, adj_nu, ddtime)
float *adj_u, *adj_v;
int adj_nu;
double ddtime;
#endif
{
   int nbins, nn;
   nbins = seqcor_bins[1] - seqcor_bins[0];
   nn = adj_nu - seqcor_bins[0];
   nbins = min_val(nbins, nn);
   if (nbins > 1)
      sequential_correlation(fp_seqcor, adj_u + seqcor_bins[0],
               adj_v + seqcor_bins[0],
               ddtime, nbins);
}

#if PROTOTYPE_ALLOWED
void close_seqcor()
#else
void close_seqcor()
#endif
{
   fclose(fp_seqcor);
}
