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

  Author: Uwe Schulzweida

*/

/*
   This module contains the following operators:

      Fldstat2    fldcor         Correlation of two fields
*/

#include <cdi.h>

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

// routine corr copied from PINGO
// correclation in space
template <typename T>
static double
correlation_s(const Varray<T> &v1, const Varray<T> &v2, 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)
    {
      double vv1 = v1[i];
      double vv2 = v2[i];
      if (IS_NOT_EQUAL(weight[i], missval1) && IS_NOT_EQUAL(vv1, missval1) && IS_NOT_EQUAL(vv2, missval2))
        {
          sum0 += weight[i] * vv1;
          sum1 += weight[i] * vv2;
          sum00 += weight[i] * vv1 * vv1;
          sum01 += weight[i] * vv1 * vv2;
          sum11 += weight[i] * vv2 * vv2;
          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;
}

static double
correlation_s(const Field &field1, const Field &field2, const Varray<double> &weight)
{
  if (field1.memType == MemType::Float)
    return correlation_s(field1.vec_f, field2.vec_f, weight, field1.missval, field2.missval, field1.size);
  else
    return correlation_s(field1.vec_d, field2.vec_d, weight, field1.missval, field2.missval, field1.size);
}

// covariance in space
template <typename T>
static double
covariance_s(const Varray<T> &v1, const Varray<T> &v2, 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)
    {
      double vv1 = v1[i];
      double vv2 = v2[i];
      if (IS_NOT_EQUAL(weight[i], missval1) && IS_NOT_EQUAL(vv1, missval1) && IS_NOT_EQUAL(vv2, missval2))
        {
          sum0 += weight[i] * vv1;
          sum1 += weight[i] * vv2;
          sum01 += weight[i] * vv1 * vv2;
          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;
}

static double
covariance_s(const Field &field1, const Field &field2, const Varray<double> &weight)
{
  if (field1.memType == MemType::Float)
    return covariance_s(field1.vec_f, field2.vec_f, weight, field1.missval, field2.missval, field1.size);
  else
    return covariance_s(field1.vec_d, field2.vec_d, weight, field1.missval, field2.missval, field1.size);
}

void *
Fldstat2(void *process)
{
  bool wstatus = false;
  bool needWeights = true;

  cdo_initialize(process);

  // clang-format off
  cdo_operator_add("fldcor",   FieldFunc_Cor,   0, nullptr);
  cdo_operator_add("fldcovar", FieldFunc_Covar, 0, nullptr);
  // clang-format on

  const auto operatorID = cdo_operator_id();
  const auto operfunc = cdo_operator_f1(operatorID);

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

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

  vlist_compare(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 = cdo_open_write(2);
  cdo_def_vlist(streamID3, vlistID3);

  Field field1, field2;

  const auto gridsizemax = vlistGridsizeMax(vlistID1);
  Varray<double> weight;
  if (needWeights) weight.resize(gridsizemax);

  int lastgridID = -1;
  int tsID = 0;
  while (true)
    {
      const auto nrecs = cdo_stream_inq_timestep(streamID1, tsID);
      if (nrecs == 0) break;

      const auto nrecs2 = cdo_stream_inq_timestep(streamID2, tsID);
      if (nrecs2 == 0)
        {
          cdo_warning("Input streams have different number of time steps!");
          break;
        }

      cdo_taxis_copy_timestep(taxisID3, taxisID1);
      cdo_def_timestep(streamID3, tsID);

      for (int recID = 0; recID < nrecs; recID++)
        {
          int varID, levelID;
          cdo_inq_record(streamID1, &varID, &levelID);
          field1.init(varList1[varID]);
          cdo_inq_record(streamID2, &varID, &levelID);
          field2.init(varList2[varID]);
          cdo_read_record(streamID1, field1);
          cdo_read_record(streamID2, field2);

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

          double sglval = 0.0;
          if (operfunc == FieldFunc_Cor)
            sglval = correlation_s(field1, field2, weight);
          else if (operfunc == FieldFunc_Covar)
            sglval = covariance_s(field1, field2, weight);

          const auto nmiss3 = DBL_IS_EQUAL(sglval, varList1[varID].missval) ? 1 : 0;

          cdo_def_record(streamID3, varID, levelID);
          cdo_write_record(streamID3, &sglval, nmiss3);
        }

      tsID++;
    }

  cdo_stream_close(streamID3);
  cdo_stream_close(streamID2);
  cdo_stream_close(streamID1);

  cdo_finish();

  return nullptr;
}
