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

      Arithc     addc            Add by constant
      Arithc     subc            Subtract by constant
      Arithc     mulc            Multiply by constant
      Arithc     divc            Divide by constant
      Arithc     mod             Modulo operator
*/

#include <cdi.h>

#include "cdo_options.h"
#include "functs.h"
#include "process_int.h"
#include "cdo_vlist.h"
#include "param_conversion.h"

static void
fill_vars(const VarList &varList, std::vector<bool> &vars)
{
  const int nvars = vars.size();

  if (Options::cdoNumVarnames() > 0)
    {
      auto found = false;
      for (int varID = 0; varID < nvars; ++varID)
        {
          vars[varID] = false;
          for (int i = 0; i < Options::cdoNumVarnames(); ++i)
            if (strcmp(varList[varID].name, Options::cdoVarnames[i].c_str()) == 0)
              {
                vars[varID] = true;
                found = true;
                break;
              }
        }

      if (!found) cdoAbort("Variable %s%s not found!", Options::cdoVarnames[0], Options::cdoNumVarnames() > 1 ? ",..." : "");
    }
  else
    {
      for (int varID = 0; varID < nvars; ++varID) vars[varID] = true;
    }
}

static void
addOperators(void)
{
  // clang-format off
  cdoOperatorAdd("addc", func_add, 1, "constant value");
  cdoOperatorAdd("subc", func_sub, 1, "constant value");
  cdoOperatorAdd("mulc", func_mul, 1, "constant value");
  cdoOperatorAdd("divc", func_div, 1, "constant value");
  cdoOperatorAdd("minc", func_min, 0, "constant value");
  cdoOperatorAdd("maxc", func_max, 0, "constant value");
  cdoOperatorAdd("mod",  func_mod, 0, "divisor");
  // clang-format on
}

void *
Arithc(void *process)
{
  int nrecs;
  int varID, levelID;

  cdoInitialize(process);

  addOperators();

  const auto operatorID = cdoOperatorID();
  const auto operfunc = cdoOperatorF1(operatorID);
  const bool opercplx = cdoOperatorF2(operatorID);

  operatorInputArg(cdoOperatorEnter(operatorID));
  if (operatorArgc() < 1) cdoAbort("Too few arguments!");
  if (operatorArgc() > 2) cdoAbort("Too many arguments!");
  const auto rconst = parameter2double(cdoOperatorArgv(0));

  double rconstcplx[2] = { rconst, 0 };
  if (operatorArgc() == 2) rconstcplx[1] = parameter2double(cdoOperatorArgv(1));

  const auto streamID1 = cdoOpenRead(0);

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

  VarList varList1;
  varListInit(varList1, vlistID1);

  const auto nvars = vlistNvars(vlistID1);
  std::vector<bool> vars(nvars);
  fill_vars(varList1, vars);

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

  const auto streamID2 = cdoOpenWrite(1);
  cdoDefVlist(streamID2, vlistID2);

  size_t nwpv = (vlistNumber(vlistID1) == CDI_COMP) ? 2 : 1;
  if (nwpv == 2 && !opercplx) cdoAbort("Fields with complex numbers are not supported by this operator!");
  const auto gridsizemax = nwpv * vlistGridsizeMax(vlistID1);

  Field field;
  field.resize(gridsizemax);

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

      for (int recID = 0; recID < nrecs; recID++)
        {
          cdoInqRecord(streamID1, &varID, &levelID);
          cdoReadRecord(streamID1, field.vec_d.data(), &field.nmiss);

          if (vars[varID])
            {
              field.grid = varList1[varID].gridID;
              field.size = varList1[varID].nwpv * varList1[varID].gridsize;
              field.missval = varList1[varID].missval;

              if (nwpv == 2)
                vfarcfuncplx(field, rconstcplx, operfunc);
              else
                vfarcfun(field, rconst, operfunc);

              // recalculate number of missing values
              field.nmiss = fieldNumMiss(field);
            }

          cdoDefRecord(streamID2, varID, levelID);
          cdoWriteRecord(streamID2, field.vec_d.data(), field.nmiss);
        }

      tsID++;
    }

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  vlistDestroy(vlistID2);

  cdoFinish();

  return nullptr;
}
