/*
  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.
*/

/*
   This module contains the following operators:

      Trend      trend           Trend
*/

#include <cdi.h>

#include "cdo_int.h"
#include "pstream_int.h"

void *
Trend(void *process)
{
  int64_t vdate = 0;
  int vtime = 0;
  int varID, levelID;
  size_t nmiss;
  int nrecs;
  constexpr int nwork = 5;
  FieldVector2D work[nwork];

  cdoInitialize(process);

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

  const int vlistID1 = cdoStreamInqVlist(streamID1);
  const int vlistID2 = vlistDuplicate(vlistID1);

  vlistDefNtsteps(vlistID2, 1);

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

  const int nvars = vlistNvars(vlistID1);

  const int maxrecs = vlistNrecs(vlistID1);
  std::vector<RecordInfo> recinfo(maxrecs);

  for (varID = 0; varID < nvars; varID++) vlistDefVarDatatype(vlistID2, varID, CDI_DATATYPE_FLT64);

  const int streamID2 = cdoStreamOpenWrite(cdoStreamName(1));
  const int streamID3 = cdoStreamOpenWrite(cdoStreamName(2));

  pstreamDefVlist(streamID2, vlistID2);
  pstreamDefVlist(streamID3, vlistID2);

  const size_t gridsizemax = vlistGridsizeMax(vlistID1);

  Field field1, field2;
  fieldInit(field1);
  fieldInit(field2);
  field1.ptr = (double *) Malloc(gridsizemax * sizeof(double));
  field2.ptr = (double *) Malloc(gridsizemax * sizeof(double));

  for (int w = 0; w < nwork; ++w) fieldsFromVlist(vlistID1, work[w], FIELD_PTR, 0);

  int tsID = 0;
  while ((nrecs = cdoStreamInqTimestep(streamID1, tsID)))
    {
      vdate = taxisInqVdate(taxisID1);
      vtime = taxisInqVtime(taxisID1);

      double zj = (double) tsID;

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

          if (tsID == 0)
            {
              recinfo[recID].varID = varID;
              recinfo[recID].levelID = levelID;
              recinfo[recID].lconst = vlistInqVarTimetype(vlistID1, varID) == TIME_CONSTANT;
            }

          pstreamReadRecord(streamID1, field1.ptr, &nmiss);

          const double missval = vlistInqVarMissval(vlistID1, varID);
          const int gridID = vlistInqVarGrid(vlistID1, varID);
          const size_t gridsize = gridInqSize(gridID);

          for (size_t i = 0; i < gridsize; i++)
            if (!DBL_IS_EQUAL(field1.ptr[i], missval))
              {
                work[0][varID][levelID].ptr[i] += zj;
                work[1][varID][levelID].ptr[i] += zj * zj;
                work[2][varID][levelID].ptr[i] += zj * field1.ptr[i];
                work[3][varID][levelID].ptr[i] += field1.ptr[i];
                work[4][varID][levelID].ptr[i]++;
              }
        }

      tsID++;
    }

  taxisDefVdate(taxisID2, vdate);
  taxisDefVtime(taxisID2, vtime);
  pstreamDefTimestep(streamID2, 0);
  pstreamDefTimestep(streamID3, 0);

  for (int recID = 0; recID < maxrecs; recID++)
    {
      const int varID = recinfo[recID].varID;
      const int levelID = recinfo[recID].levelID;

      const double missval = vlistInqVarMissval(vlistID1, varID);
      const int gridID = vlistInqVarGrid(vlistID1, varID);
      const size_t gridsize = gridInqSize(gridID);

      const double missval1 = missval;
      const double missval2 = missval;

      double temp1, temp2;
      for (size_t i = 0; i < gridsize; i++)
        {
          temp1 = SUBMN(work[2][varID][levelID].ptr[i], DIVMN(MULMN(work[0][varID][levelID].ptr[i], work[3][varID][levelID].ptr[i]),
                                                              work[4][varID][levelID].ptr[i]));
          temp2 = SUBMN(work[1][varID][levelID].ptr[i], DIVMN(MULMN(work[0][varID][levelID].ptr[i], work[0][varID][levelID].ptr[i]),
                                                              work[4][varID][levelID].ptr[i]));

          field2.ptr[i] = DIVMN(temp1, temp2);
          field1.ptr[i] = SUBMN(DIVMN(work[3][varID][levelID].ptr[i], work[4][varID][levelID].ptr[i]),
                                MULMN(DIVMN(work[0][varID][levelID].ptr[i], work[4][varID][levelID].ptr[i]), field2.ptr[i]));
        }

      nmiss = arrayNumMV(gridsize, field1.ptr, missval);
      pstreamDefRecord(streamID2, varID, levelID);
      pstreamWriteRecord(streamID2, field1.ptr, nmiss);

      nmiss = arrayNumMV(gridsize, field2.ptr, missval);
      pstreamDefRecord(streamID3, varID, levelID);
      pstreamWriteRecord(streamID3, field2.ptr, nmiss);
    }

  for (int w = 0; w < nwork; ++w) fieldsFree(vlistID1, work[w]);

  if (field1.ptr) Free(field1.ptr);
  if (field2.ptr) Free(field2.ptr);

  cdoStreamClose(streamID3);
  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  cdoFinish();

  return 0;
}
