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

      Mastrfu    mastrfu         Mass stream function
*/

#include <cdi.h>

#include "array.h"
#include "process_int.h"
#include <mpim_grid.h>
#include "cdo_zaxis.h"

static void
mastrfu(int gridID, int zaxisID, Varray2D<double> &field1, Varray2D<double> &field2, size_t nmiss, double missval)
{
  const double fact = 4 * std::atan(1.0) * 6371000 / 9.81;

  const auto nlat = gridInqSize(gridID);
  const auto nlev = zaxisInqSize(zaxisID);
  Varray<double> phi(nlat), cosphi(nlat), plevel(nlev);

  cdoZaxisInqLevels(zaxisID, plevel.data());

  gridInqYvals(gridID, phi.data());

  char units[CDI_MAX_NAME];
  int length = CDI_MAX_NAME;
  cdiInqKeyString(gridID, CDI_YAXIS, CDI_KEY_UNITS, units, &length);

  if (memcmp(units, "degree", 6) == 0)
    for (size_t ilat = 0; ilat < nlat; ilat++) phi[ilat] *= DEG2RAD;

  for (size_t ilat = 0; ilat < nlat; ilat++) phi[ilat] = std::sin(phi[ilat]);

  for (size_t ilat = 0; ilat < nlat; ilat++) cosphi[ilat] = std::sqrt(1.0 - phi[ilat] * phi[ilat]);

  for (int ilev = 0; ilev < nlev; ilev++)
    for (size_t ilat = 0; ilat < nlat; ilat++) field2[ilev][ilat] = 0.0;

  if (nmiss == 0)
    {
      for (int ilev = nlev - 1; ilev >= 0; ilev--)
        for (int n = ilev; n < nlev - 1; n++)
          for (size_t ilat = 0; ilat < nlat; ilat++)
            {
              field2[ilev][ilat] += fact * (field1[n][ilat] + field1[n + 1][ilat]) * cosphi[ilat] * (plevel[n] - plevel[n + 1]);
            }
    }
  else
    {
      for (size_t ilat = 0; ilat < nlat; ilat++)
        for (int ilev = nlev - 1; ilev >= 0; ilev--)
          for (int n = ilev; n < nlev - 1; n++)
            {
              if (DBL_IS_EQUAL(field1[n][ilat], missval))
                {
                  field2[ilev][ilat] = missval;
                  break;
                }
              else
                field2[ilev][ilat] += fact * (field1[n][ilat] + field1[n + 1][ilat]) * cosphi[ilat] * (plevel[n] - plevel[n + 1]);
            }
    }
}

void *
Mastrfu(void *process)
{
  int nrecs;
  int varID, levelID;
  size_t nmiss, nmiss1;

  cdoInitialize(process);

  const auto streamID1 = cdoOpenRead(0);

  operatorCheckArgc(0);

  const auto vlistID1 = cdoStreamInqVlist(streamID1);

  const auto nvars = vlistNvars(vlistID1);
  if (nvars != 1) cdoAbort("This operator works only with one variable!");

  const auto code = vlistInqVarCode(vlistID1, 0);
  if (code > 0 && code != 132) cdoWarning("Unexpected code %d!", code);

  const auto missval = vlistInqVarMissval(vlistID1, 0);

  const auto zaxisID = vlistInqVarZaxis(vlistID1, 0);
  if (zaxisInqType(zaxisID) != ZAXIS_PRESSURE && zaxisInqType(zaxisID) != ZAXIS_GENERIC)
    {
      char longname[CDI_MAX_NAME];
      int length = CDI_MAX_NAME;
      cdiInqKeyString(zaxisID, CDI_GLOBAL, CDI_KEY_LONGNAME, longname, &length);
      cdoWarning("Unexpected vertical grid %s!", longname);
    }

  const auto gridID = vlistInqVarGrid(vlistID1, 0);
  if (gridInqXsize(gridID) > 1) cdoAbort("Grid must be a zonal mean!");

  const auto gridsize = gridInqSize(gridID);
  const auto nlev = zaxisInqSize(zaxisID);

  const auto vlistID2 = vlistDuplicate(vlistID1);

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

  vlistDefVarCode(vlistID2, 0, 272);
  cdiDefKeyString(vlistID2, 0, CDI_KEY_NAME, "mastrfu");
  cdiDefKeyString(vlistID2, 0, CDI_KEY_LONGNAME, "mass stream function");
  cdiDefKeyString(vlistID2, 0, CDI_KEY_UNITS, "kg/s");
  vlistDefVarDatatype(vlistID2, 0, CDI_DATATYPE_FLT32);

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

  VARRAY_2D(double, array1, nlev, gridsize);
  VARRAY_2D(double, array2, nlev, gridsize);

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

      nmiss = 0;
      for (int recID = 0; recID < nrecs; recID++)
        {
          cdoInqRecord(streamID1, &varID, &levelID);
          cdoReadRecord(streamID1, array1[levelID].data(), &nmiss1);
          nmiss += nmiss1;
        }

      mastrfu(gridID, zaxisID, array1, array2, nmiss, missval);

      for (int recID = 0; recID < nrecs; recID++)
        {
          varID = 0;
          levelID = recID;
          cdoDefRecord(streamID2, varID, levelID);
          cdoWriteRecord(streamID2, array2[levelID].data(), nmiss);
        }

      tsID++;
    }

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  cdoFinish();

  return nullptr;
}
