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

      Arithlat   mulcoslat       Multiply with cos(lat)
      Arithlat   divcoslat       Divide by cos(lat)
*/

#include <cdi.h>

#include "cdo_options.h"
#include "process_int.h"
#include <mpim_grid.h>
#include "field_functions.h"

class Arithlat : public Process
{
public:
  using Process::Process;
  inline static CdoModule module = {
    .name = "Arithlat",
    // clang-format off
    .operators = { { "mulcoslat", FieldFunc_Mul, 0, ArithlatHelp },
                   { "divcoslat", FieldFunc_Div, 0, ArithlatHelp } },
    // clang-format on
    .aliases = {},
    .mode = EXPOSED,     // Module mode: 0:intern 1:extern
    .number = CDI_REAL,  // Allowed number type
    .constraints = { 1, 1, NoRestriction },
  };
  inline static RegisterEntry<Arithlat> registration = RegisterEntry<Arithlat>(module);

  CdoStreamID streamID1;
  int taxisID1;

  CdoStreamID streamID2;
  int taxisID2;

  int operfunc;

  VarList varList1;
  Varray<double> array;
  Varray<double> scale;

public:
  void
  init() override
  {
    auto operatorID = cdo_operator_id();
    operfunc = cdo_operator_f1(operatorID);

    operator_check_argc(0);

    streamID1 = cdo_open_read(0);

    auto vlistID1 = cdo_stream_inq_vlist(streamID1);
    auto vlistID2 = vlistDuplicate(vlistID1);

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

    streamID2 = cdo_open_write(1);
    cdo_def_vlist(streamID2, vlistID2);

    varList1 = VarList(vlistID1);

    auto gridsizemax = vlistGridsizeMax(vlistID1);

    array = Varray<double>(gridsizemax);
  }

  void
  run() override
  {
    int gridID0 = -1;
    int tsID = 0;
    while (true)
      {
        auto numFields = cdo_stream_inq_timestep(streamID1, tsID);
        if (numFields == 0) break;

        cdo_taxis_copy_timestep(taxisID2, taxisID1);
        cdo_def_timestep(streamID2, tsID);

        for (int fieldID = 0; fieldID < numFields; ++fieldID)
          {
            auto [varID, levelID] = cdo_inq_field(streamID1);
            size_t numMissVals;
            cdo_read_field(streamID1, array.data(), &numMissVals);

            const auto &var1 = varList1.vars[varID];
            auto gridID = var1.gridID;
            auto gridsize = var1.gridsize;
            auto missval = var1.missval;

            if (gridID != gridID0)
              {
                gridID0 = gridID;
                gridID = generate_full_point_grid(gridID);
                if (!gridHasCoordinates(gridID)) cdo_abort("Cell center coordinates missing!");

                scale.resize(gridsize);
                gridInqYvals(gridID, scale.data());

                // Convert lat/lon units if required
                cdo_grid_to_radian(gridID, CDI_XAXIS, scale, "grid latitudes");

                if (operfunc == FieldFunc_Mul)
                  for (size_t i = 0; i < gridsize; ++i) scale[i] = std::cos(scale[i]);
                else
                  for (size_t i = 0; i < gridsize; ++i) scale[i] = 1.0 / std::cos(scale[i]);

                if (Options::cdoVerbose)
                  for (int i = 0; i < 10; ++i) cdo_print("coslat  %3d  %g", i + 1, scale[i]);
              }

            if (numMissVals)
              {
                for (size_t i = 0; i < gridsize; ++i)
                  if (fp_is_not_equal(array[i], missval)) array[i] *= scale[i];
              }
            else
              {
                for (size_t i = 0; i < gridsize; ++i) array[i] *= scale[i];
              }

            cdo_def_field(streamID2, varID, levelID);
            cdo_write_field(streamID2, array.data(), numMissVals);
          }

        tsID++;
      }
  }

  void
  close() override
  {
    cdo_stream_close(streamID2);
    cdo_stream_close(streamID1);
  }
};
