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

  Copyright (C) 2003-2020 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:

      Fldstat2    fldcor         Correlation of two fields
*/

#include <cdi.h>

#include "functs.h"
#include "process_int.h"
#include "cdo_vlist.h"
#include <mpim_grid.h>

// routine corr copied from PINGO
// correclation in space
static double
correlation_s(const Varray<double> &in0, const Varray<double> &in1, const Varray<double> &weight, double missval1,
              double missval2, size_t gridsize)
{
  double sum0 = 0.0, sum1 = 0.0, sum00 = 0.0, sum01 = 0.0, sum11 = 0.0, wsum0 = 0.0;

  for (size_t i = 0; i < gridsize; ++i)
    {
      if (IS_NOT_EQUAL(weight[i], missval1) && IS_NOT_EQUAL(in0[i], missval1) && IS_NOT_EQUAL(in1[i], missval2))
        {
          sum0 += weight[i] * in0[i];
          sum1 += weight[i] * in1[i];
          sum00 += weight[i] * in0[i] * in0[i];
          sum01 += weight[i] * in0[i] * in1[i];
          sum11 += weight[i] * in1[i] * in1[i];
          wsum0 += weight[i];
        }
    }

  double out = IS_NOT_EQUAL(wsum0, 0.0)
                   ? DIVMN((sum01 * wsum0 - sum0 * sum1), SQRTMN((sum00 * wsum0 - sum0 * sum0) * (sum11 * wsum0 - sum1 * sum1)))
                   : missval1;

  return out;
}

// covariance in space
static double
covariance_s(const Varray<double> &in0, const Varray<double> &in1, const Varray<double> &weight, double missval1,
             double missval2, size_t gridsize)
{
  double sum0 = 0.0, sum1 = 0.0, sum01 = 0.0, wsum0 = 0.0, wsum00 = 0.0;

  for (size_t i = 0; i < gridsize; ++i)
    {
      if (IS_NOT_EQUAL(weight[i], missval1) && IS_NOT_EQUAL(in0[i], missval1) && IS_NOT_EQUAL(in1[i], missval2))
        {
          sum0 += weight[i] * in0[i];
          sum1 += weight[i] * in1[i];
          sum01 += weight[i] * in0[i] * in1[i];
          wsum0 += weight[i];
          wsum00 += weight[i] * weight[i];
        }
    }

  double out = IS_NOT_EQUAL(wsum0, 0.0) ? (sum01 * wsum0 - sum0 * sum1) / (wsum0 * wsum0) : missval1;

  return out;
}

void *
Fldstat2(void *process)
{
  int lastgridID = -1;
  int nrecs;
  int varID, levelID;
  size_t nmiss1, nmiss2;
  bool wstatus = false;
  bool needWeights = true;

  cdoInitialize(process);

  // clang-format off
  cdoOperatorAdd("fldcor",   func_cor,   0, nullptr);
  cdoOperatorAdd("fldcovar", func_covar, 0, nullptr);
  // clang-format on

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

  const auto streamID1 = cdoOpenRead(0);
  const auto streamID2 = cdoOpenRead(1);

  const auto vlistID1 = cdoStreamInqVlist(streamID1);
  const auto vlistID2 = cdoStreamInqVlist(streamID2);
  const auto vlistID3 = vlistDuplicate(vlistID1);

  vlistCompare(vlistID1, vlistID2, CMP_ALL);

  const auto taxisID1 = vlistInqTaxis(vlistID1);
  const auto taxisID3 = taxisDuplicate(taxisID1);
  vlistDefTaxis(vlistID3, taxisID3);

  VarList varList1, varList2;
  varListInit(varList1, vlistID1);
  varListInit(varList2, vlistID2);

  double slon = 0.0, slat = 0.0;
  const auto gridID3 = gridCreate(GRID_LONLAT, 1);
  gridDefXsize(gridID3, 1);
  gridDefYsize(gridID3, 1);
  gridDefXvals(gridID3, &slon);
  gridDefYvals(gridID3, &slat);

  const auto ngrids = vlistNgrids(vlistID1);

  for (int index = 0; index < ngrids; index++) vlistChangeGridIndex(vlistID3, index, gridID3);

  const auto streamID3 = cdoOpenWrite(2);
  cdoDefVlist(streamID3, vlistID3);

  const auto gridsizemax = vlistGridsizeMax(vlistID1);

  Varray<double> array1(gridsizemax), array2(gridsizemax);
  Varray<double> weight;
  if (needWeights) weight.resize(gridsizemax);

  int tsID = 0;
  while ((nrecs = cdoStreamInqTimestep(streamID1, tsID)))
    {
      const auto nrecs2 = cdoStreamInqTimestep(streamID2, tsID);

      if (nrecs2 == 0)
        {
          cdoWarning("Input streams have different number of time steps!");
          break;
        }

      taxisCopyTimestep(taxisID3, taxisID1);
      cdoDefTimestep(streamID3, tsID);

      for (int recID = 0; recID < nrecs; recID++)
        {
          cdoInqRecord(streamID1, &varID, &levelID);
          cdoInqRecord(streamID2, &varID, &levelID);
          cdoReadRecord(streamID1, array1.data(), &nmiss1);
          cdoReadRecord(streamID2, array2.data(), &nmiss2);

          const auto gridID = varList1[varID].gridID;
          const auto gridsize = varList1[varID].gridsize;
          if (needWeights && gridID != lastgridID)
            {
              lastgridID = gridID;
              wstatus = gridWeights(gridID, weight.data()) != 0;
            }
          if (wstatus && tsID == 0 && levelID == 0)
            cdoWarning("Using constant grid cell area weights for variable %s!", varList1[varID].name);

          const auto missval1 = varList1[varID].missval;
          const auto missval2 = varList2[varID].missval;

          double sglval = 0.0;
          if (operfunc == func_cor)
            sglval = correlation_s(array1, array2, weight, missval1, missval2, gridsize);
          else if (operfunc == func_covar)
            sglval = covariance_s(array1, array2, weight, missval1, missval2, gridsize);

          const auto nmiss3 = DBL_IS_EQUAL(sglval, missval1) ? 1 : 0;

          cdoDefRecord(streamID3, varID, levelID);
          cdoWriteRecord(streamID3, &sglval, nmiss3);
        }

      tsID++;
    }

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

  cdoFinish();

  return nullptr;
}
