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

      Setvals     setvals       Set list of old values to new values
      Setrtoc     setrtoc       Set range to new value
      Setrtoc2    setrtoc2      Set range to new value others to value2
*/

#include <cdi.h>

#include "process_int.h"
#include "param_conversion.h"

void *
Replacevalues(void *process)
{
  int nrecs;
  int varID, levelID;
  size_t nmiss;
  int nvals = 0;
  std::vector<double> fltarr;
  double rmin = 0, rmax = 0;
  double newval = 0, newval2 = 0;

  cdoInitialize(process);

  // clang-format off
  const auto SETVALS  = cdoOperatorAdd("setvals",  0, 0, "I1,O1,...,In,On");
  const auto SETRTOC  = cdoOperatorAdd("setrtoc",  0, 0, "range (min, max), value");
  const auto SETRTOC2 = cdoOperatorAdd("setrtoc2", 0, 0, "range (min, max), value1, value2");
  // clang-format on

  const auto operatorID = cdoOperatorID();

  operatorInputArg(cdoOperatorEnter(operatorID));

  if (operatorID == SETVALS)
    {
      fltarr = cdoArgvToFlt(cdoGetOperArgv());
      nvals = fltarr.size();
      if (nvals < 2) cdoAbort("Too few arguments!");
      if (nvals % 2 != 0) cdoAbort("Need pairs of arguments!");
      nvals = nvals / 2;
    }
  else if (operatorID == SETRTOC)
    {
      operatorCheckArgc(3);
      rmin = parameter2double(cdoOperatorArgv(0));
      rmax = parameter2double(cdoOperatorArgv(1));
      newval = parameter2double(cdoOperatorArgv(2));
    }
  else if (operatorID == SETRTOC2)
    {
      operatorCheckArgc(4);
      rmin = parameter2double(cdoOperatorArgv(0));
      rmax = parameter2double(cdoOperatorArgv(1));
      newval = parameter2double(cdoOperatorArgv(2));
      newval2 = parameter2double(cdoOperatorArgv(3));
    }

  const auto streamID1 = cdoOpenRead(0);

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

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

  const auto streamID2 = cdoOpenWrite(1);

  cdoDefVlist(streamID2, vlistID2);

  const auto gridsizemax = vlistGridsizeMax(vlistID1);
  Varray<double> array(gridsizemax);

  VarList varList1;
  varListInit(varList1, vlistID1);

  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, array.data(), &nmiss);

          const auto gridsize = varList1[varID].gridsize;
          const auto missval = varList1[varID].missval;

          if (operatorID == SETVALS)
            {
              for (size_t i = 0; i < gridsize; i++)
                if (!DBL_IS_EQUAL(array[i], missval))
                  {
                    for (int j = 0; j < nvals; j++)
                      {
                        if (DBL_IS_EQUAL(array[i], fltarr[j * 2]))
                          {
                            array[i] = fltarr[j * 2 + 1];
                            break;
                          }
                      }
                  }
            }
          else if (operatorID == SETRTOC)
            {
              for (size_t i = 0; i < gridsize; i++)
                if (!DBL_IS_EQUAL(array[i], missval))
                  {
                    if (array[i] >= rmin && array[i] <= rmax) array[i] = newval;
                  }
            }
          else if (operatorID == SETRTOC2)
            {
              for (size_t i = 0; i < gridsize; i++)
                if (!DBL_IS_EQUAL(array[i], missval))
                  {
                    array[i] = (array[i] >= rmin && array[i] <= rmax) ? newval : newval2;
                  }
            }

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

      tsID++;
    }

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  cdoFinish();

  return nullptr;
}
