/*
  This file is part of CDO. CDO is a collection of Operators to
  manipulate and analyse Climate model Data.

  Copyright (C) 2003-2019 Uwe Schulzweida, <uwe.schulzweida AT mpimet.mpg.de>
  See COPYING file for copying and redistribution conditions.

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; version 2 of the License.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
*/

#include <cdi.h>

#include "cdo_int.h"
#include "param_conversion.h"
#include "pstream_int.h"
#include "pmlist.h"


void *
Varsstat(void *process)
{
  int nrecs;
  int varID, levelID;
  size_t nmiss;

  cdoInitialize(process);

  // clang-format off
  cdoOperatorAdd("varsrange", func_range, 0, nullptr);
  cdoOperatorAdd("varsmin",   func_min,   0, nullptr);
  cdoOperatorAdd("varsmax",   func_max,   0, nullptr);
  cdoOperatorAdd("varssum",   func_sum,   0, nullptr);
  cdoOperatorAdd("varsmean",  func_mean,  0, nullptr);
  cdoOperatorAdd("varsavg",   func_avg,   0, nullptr);
  cdoOperatorAdd("varsvar",   func_var,   0, nullptr);
  cdoOperatorAdd("varsvar1",  func_var1,  0, nullptr);
  cdoOperatorAdd("varsstd",   func_std,   0, nullptr);
  cdoOperatorAdd("varsstd1",  func_std1,  0, nullptr);

  const int operatorID = cdoOperatorID();
  const int operfunc   = cdoOperatorF1(operatorID);

  const bool lrange  = operfunc == func_range;
  const bool lmean   = operfunc == func_mean || operfunc == func_avg;
  const bool lstd    = operfunc == func_std || operfunc == func_std1;
  const bool lvarstd = operfunc == func_std || operfunc == func_var || operfunc == func_std1 || operfunc == func_var1;
  const int  divisor = operfunc == func_std1 || operfunc == func_var1;
  // clang-format on

  const int streamID1 = cdoStreamOpenRead(cdoStreamName(0));
  const int vlistID1 = cdoStreamInqVlist(streamID1);

  const int nzaxis = vlistNzaxis(vlistID1);
  const int zaxisID = vlistZaxis(vlistID1, 0);
  const int nlevs = zaxisInqSize(zaxisID);
  for (int index = 1; index < nzaxis; ++index)
    {
      if (nlevs != zaxisInqSize(vlistZaxis(vlistID1, index)))
        cdoAbort("Number of level differ!");
    }

  const int ngrids = vlistNgrids(vlistID1);
  const int gridID = vlistGrid(vlistID1, 0);
  const size_t gridsize = gridInqSize(gridID);
  for (int index = 0; index < ngrids; index++)
    {
      if (gridsize != gridInqSize(vlistGrid(vlistID1, index)))
        cdoAbort("Horizontal gridsize differ!");
    }

  const int timetype = vlistInqVarTimetype(vlistID1, 0);
  const int nvars = vlistNvars(vlistID1);
  for (varID = 1; varID < nvars; ++varID)
    {
      if (timetype != vlistInqVarTimetype(vlistID1, varID))
        cdoAbort("Number of timesteps differ!");
    }

  bool paramIsEqual = true;
  char name[CDI_MAX_NAME], zname[CDI_MAX_NAME];
  int param = vlistInqVarParam(vlistID1, 0);
  vlistInqVarName(vlistID1, 0, name);
  for (varID = 1; varID < nvars; ++varID)
    {
      int zparam = vlistInqVarParam(vlistID1, varID);
      vlistInqVarName(vlistID1, varID, zname);
      if (param != zparam || !cstrIsEqual(name, zname))
        {
          paramIsEqual = false;
          break;
        }
    }

  const int vlistID2 = vlistCreate();
  const int varID2 = vlistDefVar(vlistID2, gridID, zaxisID, timetype);
  if (!paramIsEqual) strcpy(name, cdoOperatorName(operatorID));
  vlistDefVarName(vlistID2, varID2, name);
  if (paramIsEqual)
    {
      if (param >= 0) vlistDefVarParam(vlistID2, varID2, param);
      zname[0] = 0;
      vlistInqVarLongname(vlistID1, 0, zname);
      if (*zname) vlistDefVarUnits(vlistID2, varID2, zname);
      zname[0] = 0;
      vlistInqVarUnits(vlistID1, 0, zname);
      if (*zname) vlistDefVarUnits(vlistID2, varID2, zname);
    }

  const int taxisID1 = vlistInqTaxis(vlistID1);
  const int taxisID2 = taxisDuplicate(taxisID1);
  vlistDefTaxis(vlistID2, taxisID2);

  const int streamID2 = cdoStreamOpenWrite(cdoStreamName(1));
  pstreamDefVlist(streamID2, vlistID2);

  const size_t gridsizemax = vlistGridsizeMax(vlistID1);

  Field field;
  fieldInit(field);
  field.ptr = (double *) Malloc(gridsizemax * sizeof(double));

  std::vector<Field> vars1(nlevs);
  std::vector<Field> samp1(nlevs);
  std::vector<Field> vars2;
  if (lvarstd || lrange) vars2.resize(nlevs);

  for (levelID = 0; levelID < nlevs; levelID++)
    {
      double missval = vlistInqVarMissval(vlistID1, 0);

      fieldInit(vars1[levelID]);
      fieldInit(samp1[levelID]);
      vars1[levelID].grid = gridID;
      vars1[levelID].zaxis = zaxisID;
      vars1[levelID].nsamp = 0;
      vars1[levelID].nmiss = 0;
      vars1[levelID].missval = missval;
      vars1[levelID].ptr = (double *) Malloc(gridsize * sizeof(double));
      samp1[levelID].grid = gridID;
      samp1[levelID].nmiss = 0;
      samp1[levelID].missval = missval;
      samp1[levelID].ptr = nullptr;
      if (lvarstd || lrange)
        {
          fieldInit(vars2[levelID]);
          vars2[levelID].grid = gridID;
          vars2[levelID].nmiss = 0;
          vars2[levelID].missval = missval;
          vars2[levelID].ptr = (double *) Malloc(gridsize * sizeof(double));
        }
    }

  int tsID = 0;
  while ((nrecs = cdoStreamInqTimestep(streamID1, tsID)))
    {
      taxisCopyTimestep(taxisID2, taxisID1);
      pstreamDefTimestep(streamID2, tsID);

      for (int recID = 0; recID < nrecs; recID++)
        {
          pstreamInqRecord(streamID1, &varID, &levelID);

          vars1[levelID].nsamp++;
          if (lrange) vars2[levelID].nsamp++;

          if (varID == 0)
            {
              pstreamReadRecord(streamID1, vars1[levelID].ptr, &nmiss);
              vars1[levelID].nmiss = nmiss;
              if (lrange)
                {
                  vars2[levelID].nmiss = nmiss;
                  for (size_t i = 0; i < gridsize; i++) vars2[levelID].ptr[i] = vars1[levelID].ptr[i];
                }

              if (lvarstd)
                {
                  farmoq(vars2[levelID], vars1[levelID]);
                }

              if (nmiss > 0 || samp1[levelID].ptr)
                {
                  if (samp1[levelID].ptr == nullptr) samp1[levelID].ptr = (double *) Malloc(gridsize * sizeof(double));

                  for (size_t i = 0; i < gridsize; i++)
                    if (DBL_IS_EQUAL(vars1[levelID].ptr[i], vars1[levelID].missval))
                      samp1[levelID].ptr[i] = 0.;
                }
            }
          else
            {
              pstreamReadRecord(streamID1, field.ptr, &nmiss);
              field.nmiss = nmiss;
              field.grid = vars1[levelID].grid;
              field.missval = vars1[levelID].missval;

              if (field.nmiss > 0 || samp1[levelID].ptr)
                {
                  if (samp1[levelID].ptr == nullptr)
                    {
                      samp1[levelID].ptr = (double *) Malloc(gridsize * sizeof(double));
                      for (size_t i = 0; i < gridsize; i++) samp1[levelID].ptr[i] = vars1[levelID].nsamp;
                    }

                  for (size_t i = 0; i < gridsize; i++)
                    if (!DBL_IS_EQUAL(field.ptr[i], vars1[levelID].missval)) samp1[levelID].ptr[i]++;
                }

              if (lvarstd)
                {
                  farsumq(vars2[levelID], field);
                  farsum(vars1[levelID], field);
                }
              else if (lrange)
                {
                  farmin(vars2[levelID], field);
                  farmax(vars1[levelID], field);
                }
              else
                {
                  farfun(vars1[levelID], field, operfunc);
                }
            }
        }

      for (levelID = 0; levelID < nlevs; levelID++)
        {
          if (vars1[levelID].nsamp)
            {
              if (lmean)
                {
                  if (samp1[levelID].ptr == nullptr)
                    farcdiv(vars1[levelID], (double) vars1[levelID].nsamp);
                  else
                    fardiv(vars1[levelID], samp1[levelID]);
                }
              else if (lvarstd)
                {
                  if (samp1[levelID].ptr == nullptr)
                    {
                      if (lstd)
                        farcstd(vars1[levelID], vars2[levelID], vars1[levelID].nsamp, divisor);
                      else
                        farcvar(vars1[levelID], vars2[levelID], vars1[levelID].nsamp, divisor);
                    }
                  else
                    {
                      if (lstd)
                        farstd(vars1[levelID], vars2[levelID], samp1[levelID], divisor);
                      else
                        farvar(vars1[levelID], vars2[levelID], samp1[levelID], divisor);
                    }
                }
              else if (lrange)
                {
                  farsub(vars1[levelID], vars2[levelID]);
                }

              pstreamDefRecord(streamID2, 0, levelID);
              pstreamWriteRecord(streamID2, vars1[levelID].ptr, vars1[levelID].nmiss);
              vars1[levelID].nsamp = 0;
            }
        }

      tsID++;
    }

  for (levelID = 0; levelID < nlevs; levelID++)
    {
      Free(vars1[levelID].ptr);
      if (samp1[levelID].ptr) Free(samp1[levelID].ptr);
      if (lvarstd) Free(vars2[levelID].ptr);
    }

  if (field.ptr) Free(field.ptr);

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  vlistDestroy(vlistID2);

  cdoFinish();

  return nullptr;
}
