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

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

#include <cdi.h>

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

void *
Arithlat(void *process)
{
  int gridID0 = -1;
  int nrecs;
  int varID, levelID;
  size_t nmiss;
  Varray<double> scale;

  cdoInitialize(process);

  cdoOperatorAdd("mulcoslat", func_mul, 0, nullptr);
  cdoOperatorAdd("divcoslat", func_div, 0, nullptr);

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

  operatorCheckArgc(0);

  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);
  
  VarList varList1;
  varListInit(varList1, vlistID1);

  const auto gridsizemax = vlistGridsizeMax(vlistID1);
  Varray<double> array(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, &array[0], &nmiss);

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

          if (gridID != gridID0)
            {
              gridID0 = gridID;

              const auto gridtype = gridInqType(gridID);
              const auto projtype = (gridtype == GRID_PROJECTION) ? gridInqProjType(gridID) : -1;
              if (gridtype == GRID_LONLAT || gridtype == GRID_GAUSSIAN || projtype == CDI_PROJ_LCC)
                {
                  gridID = gridToCurvilinear(gridID, 0);
                }
              else if (gridtype == GRID_CURVILINEAR || gridtype == GRID_UNSTRUCTURED)
                {
                  // No conversion necessary
                }
              else if (gridtype == GRID_GME)
                {
                  gridID = gridToUnstructured(gridID, 0);
                }
              else
                {
                  if (gridtype == GRID_GAUSSIAN_REDUCED)
                    cdoAbort("Unsupported grid type: %s, use CDO option -R to convert reduced to regular grid!",
                             gridNamePtr(gridtype));
                  else
                    cdoAbort("Unsupported grid type: %s", gridNamePtr(gridtype));
                }

              scale.resize(gridsize);
              gridInqYvals(gridID, &scale[0]);

              // Convert lat/lon units if required
              cdo_grid_to_radian(gridID, CDI_XAXIS, gridsize, &scale[0], "grid latitudes");

              if (operfunc == func_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. / std::cos(scale[i]);

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

          for (size_t i = 0; i < gridsize; ++i) array[i] *= scale[i];

          cdoDefRecord(streamID2, varID, levelID);
          cdoWriteRecord(streamID2, &array[0], nmiss);
        }

      tsID++;
    }

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  cdoFinish();

  return nullptr;
}
