/* makenc.c
 *              Emilio          3/31/99
 *                Updated program.
 *              Emilio          4/22/98
 *                *
 * COMPILE AS: gccemu makenc
 * RUN AS: makenc -o <Name of output NC file> -tit  -hist 
 ******************************************************************************/

#include "emu.h"

const char * cpszUsage = {"usage: makenc \n\
Convert datasets to single netcdf file.\n\
\n\
"};

/* local functions */
void Setup(void);
void ProcessAndOutput(void);

/* local variables */
float *x, *varf;
short *vars;
int ncID;     /* netCDF file IDs  */
int varID;    /* variable ID      */
int tID;      /* time axis ID     */
static size_t count[3];
int errnc;


int main(int argc, char *argv[])
{
  AssignString(&pszNCtitle, "Time series");
  AssignString(&pszNChist, "netcdf variables created using makenc");

  Initialize(&argc, argv, DOMASK);

  Setup();
  ProcessAndOutput();

  CleanUp();

  return(0);
}

/* ================================================================= */
void Setup(void)
{
  x = alloc1d_f(0,nRows*nCols-1);
  varf = alloc1d_f(0,nRows*nCols-1);
  vars = alloc1d_s(0,nRows*nCols-1);

  /* setup new NC file from NC headers, define variables */
  SetupDefaultAxes(TRUE, FALSE);
  count[0] = 1;
  count[1] = stAxes[1].length;
  count[2] = stAxes[0].length;
  ncID = newNCsetup(&tID, pszOutputFile, pszNCtitle, pszNChist);
  DefNCvarsFromNCs(ncID, "none", 0);
}

/* ================================================================= */
void ProcessAndOutput(void)
{
  int v, yr, mo, i;     int bug=0;
  int irev, col, row;
  short tvar = 0, t1;
  double tvalue = 0;
  static size_t start[] = {0,0,0};


  t1 = (nFirstYear - (YEARORIGIN + 1))*12 + nFirstMonth;
  /* tvar index of "nFirstMonth" of "nFirstYear", with respect to "timeorigin" */

  for (v = 0; v < nVars; v++)
  {
    errnc = nc_inq_varid(ncID, pstVars[v].param, &varID);

    for (tvar = 0; tvar < nTimeSteps;tvar++)
    {
      getyrmonth(tvar, &yr, &mo);
      if (bDebug)  printf("\n pstVars[%d]=%s: tvar=%d, year=%d, month=%d  *  ",
                          v,pstVars[v].param,tvar,yr,mo+1);
      ReadXY(x, pstVars[v], yr, mo);

      for (i = 0; i < nRows*nCols; i++)
      {
        irev = getRowRevCol(i, &col, &row);

        /* if outside mask or isNaN, use _FillValue */
        if (pstVars[v].tEmuType == EMU_SHORT)
          vars[irev] = (!masktest(pMask[i]) || IsBad((double) x[i])) ?
                        pstVars[v].nFillValue : (short) x[i];
        else if (pstVars[v].tEmuType == EMU_FLOAT)
          varf[irev] = (!masktest(pMask[i]) || IsBad((double) x[i])) ?
                        pstVars[v].fFillValue : x[i];
      } /* end i-loop */

      /* write current time value to time-axis */
      start[0] = tvar;
      tvalue = (double) MONTH2HOUR*(t1 + tvar + 0.001);
      errnc = nc_put_var1_double(ncID, tID, &start[0], &tvalue);

      /* write array for this year/month into netCDF file */
      if (pstVars[v].tEmuType == EMU_SHORT)
        errnc = nc_put_vara_short(ncID, varID, start, count, vars);
      else if (pstVars[v].tEmuType == EMU_FLOAT)
        errnc = nc_put_vara_float(ncID, varID, start, count, varf);
    } /* end tvar-loop */
  } /* end v-loop */
}

/* ================================================================= */
void ProcessCommandLineArgs(int * pArgc, char * argv[])
{
}

/* ================================================================= */
void LocalCleanUp(void)
{
  free1d_f(x,0,nRows*nCols-1);
  free1d_f(varf,0,nRows*nCols-1);
  free1d_s(vars,0,nRows*nCols-1);

  errnc = nc_close(ncID);
}