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

      Vertint    gh2hl           Model geometric height level to height level interpolation
*/

#include <cdi.h>

#include "cdo_options.h"
#include "process_int.h"
#include "cdo_vlist.h"
#include "field_vinterp.h"
#include "stdnametable.h"
#include "util_string.h"
#include "const.h"
#include "cdo_zaxis.h"
#include "param_conversion.h"


static bool
is_height_axis(int zaxisID)
{
  bool isHeight = false;
  if (zaxisInqType(zaxisID) == ZAXIS_REFERENCE)
    {
      char units[CDI_MAX_NAME], stdname[CDI_MAX_NAME];
      int length = CDI_MAX_NAME;
      cdiInqKeyString(zaxisID, CDI_GLOBAL, CDI_KEY_UNITS, units, &length);
      length = CDI_MAX_NAME;
      cdiInqKeyString(zaxisID, CDI_GLOBAL, CDI_KEY_STDNAME, stdname, &length);
      if (cdo_cmpstr(stdname, "height") && *units == 0) isHeight = true;
    }
  return isHeight;
}

void *
Vertintgh(void *process)
{
  int varID, levelID;
  int f_heightID = -1, h_heightID = -1;;
  char stdname[CDI_MAX_NAME];
  bool extrapolate = false;

  cdoInitialize(process);

  // clang-format off
  const auto GH2HL  = cdoOperatorAdd("gh2hl",   0, 0, "height levels in meter");
  const auto GH2HLX = cdoOperatorAdd("gh2hlx",  0, 0, "height levels in meter");
  // clang-format on

  const auto operatorID = cdoOperatorID();

  if (operatorID == GH2HL)
    {
      const auto envstr = getenv("EXTRAPOLATE");
      if (envstr && isdigit((int) envstr[0]))
        {
          if (atoi(envstr) == 1) extrapolate = true;
          if (extrapolate) cdoPrint("Extrapolation of missing values enabled!");
        }
    }
  else if (operatorID == GH2HLX)
    {
      extrapolate = true;
    }

  operatorInputArg(cdoOperatorEnter(operatorID));

  int zaxisID2 = CDI_UNDEFID;
  const auto &arg1 = cdoOperatorArgv(0);
  std::vector<double> heightlevs;
  if (operatorArgc() == 1 && !isdigit(arg1[0]))
    {
      auto zfilename = arg1.c_str();
      auto zfp = fopen(zfilename, "r");
      if (zfp)
        {
          zaxisID2 = zaxisFromFile(zfp, zfilename);
          fclose(zfp);
          if (zaxisID2 == CDI_UNDEFID) cdoAbort("Invalid zaxis description file %s!", zfilename);
          const auto nlevels = zaxisInqSize(zaxisID2);
          heightlevs.resize(nlevels);
          zaxisInqLevels(zaxisID2, heightlevs.data());
        }
      else if (arg1 == "default")
        heightlevs = { 10, 50, 100, 500, 1000, 5000, 10000, 15000, 20000, 25000, 30000 };
      else
        cdoAbort("Open failed on %s", zfilename);
    }
  else
    {
      heightlevs = cdoArgvToFlt(cdoGetOperArgv());
    }

  int nheightlevs = heightlevs.size();

  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 gridsize = vlist_check_gridsize(vlistID1);

  if (zaxisID2 == CDI_UNDEFID)
    {
      zaxisID2 = zaxisCreate(ZAXIS_HEIGHT, nheightlevs);
      zaxisDefLevels(zaxisID2, heightlevs.data());
    }

  VarList varList1;
  varListInit(varList1, vlistID1);
  varListSetUniqueMemtype(varList1);
  const auto memtype = varList1[0].memType;

  const auto nvars = vlistNvars(vlistID1);

  for (varID = 0; varID < nvars; varID++)
    {
      int length = CDI_MAX_NAME;
      cdiInqKeyString(vlistID1, varID, CDI_KEY_STDNAME, stdname, &length);
      cstrToLowerCase(stdname);

      // clang-format off
      if (cdo_cmpstr(stdname, var_stdname(geometric_height_at_full_level_center))) f_heightID = varID;
      if (cdo_cmpstr(stdname, var_stdname(geometric_height_at_half_level_center))) h_heightID = varID;
      // clang-format on
    }

  if (Options::cdoVerbose)
    {
      cdoPrint("Found:");
      // clang-format off
      if (-1 != f_heightID) cdoPrint("  %s -> %s", var_stdname(geometric_height_at_full_level_center), varList1[f_heightID].name);
      if (-1 != h_heightID) cdoPrint("  %s -> %s", var_stdname(geometric_height_at_half_level_center), varList1[h_heightID].name);
      // clang-format on
    }

  if (-1 == f_heightID && -1 == h_heightID) cdoAbort("%s not found!", var_stdname(geometric_height_at_full_level_center));

  const auto zaxisIDfull = (-1 != f_heightID) ? varList1[f_heightID].zaxisID : -1;
  const auto zaxisIDhalf = (-1 != h_heightID) ? varList1[h_heightID].zaxisID : -1;
  const auto nfulllevs = (-1 != zaxisIDfull) ? zaxisInqSize(zaxisIDfull) : 0;
  const auto nhalflevs = (-1 != zaxisIDhalf) ? zaxisInqSize(zaxisIDhalf) : 0;

  const auto nzaxis = vlistNzaxis(vlistID1);
  for (int index = 0; index < nzaxis; index++)
    {
      const auto zaxisID = vlistZaxis(vlistID1, index);
      const auto nlevels = zaxisInqSize(zaxisID);
      if (zaxisID == zaxisIDfull || zaxisID == zaxisIDhalf ||
          (is_height_axis(zaxisID) && (nlevels == nhalflevs || nlevels == nfulllevs)))
        vlistChangeZaxis(vlistID2, zaxisID, zaxisID2);
    }

  VarList varList2;
  varListInit(varList2, vlistID2);
  varListSetMemtype(varList2, memtype);

  Field height_bottom;

  std::vector<size_t> pnmiss;
  if (!extrapolate) pnmiss.resize(nheightlevs);

  std::vector<int> vert_index_full, vert_index_half;
  if (-1 != f_heightID) vert_index_full.resize(gridsize * nheightlevs);
  if (-1 != h_heightID) vert_index_half.resize(gridsize * nheightlevs);

  std::vector<bool> vars(nvars), varinterp(nvars);
  std::vector<std::vector<size_t>> varnmiss(nvars);
  Field3DVector vardata1(nvars), vardata2(nvars);

  const auto maxlev = std::max(std::max(nfulllevs, nhalflevs), nheightlevs);

  for (varID = 0; varID < nvars; varID++)
    {
      const auto gridID = varList1[varID].gridID;
      const auto zaxisID = varList1[varID].zaxisID;
      const auto nlevels = varList1[varID].nlevels;

      if (gridInqType(gridID) == GRID_SPECTRAL) cdoAbort("Spectral data unsupported!");

      vardata1[varID].init(varList1[varID]);

      varinterp[varID] = (zaxisID == zaxisIDfull || zaxisID == zaxisIDhalf ||
                          (is_height_axis(zaxisID) && (nlevels == nhalflevs || nlevels == nfulllevs)));

      if (varinterp[varID])
        {
          varnmiss[varID].resize(maxlev, 0);
          vardata2[varID].init(varList2[varID]);
        }
      else
        {
          if (is_height_axis(zaxisID) && nlevels > 1)
            {
              if (-1 == f_heightID && -1 != h_heightID && nlevels == (nhalflevs - 1))
                cdoAbort("%s not found (needed for %s)!", var_stdname(geometric_height_at_full_level_center), varList1[varID].name);
              else if (-1 != f_heightID && -1 == h_heightID && nlevels == (nfulllevs + 1))
                cdoAbort("%s not found (needed for %s)!", var_stdname(geometric_height_at_half_level_center), varList1[varID].name);
              else
                cdoWarning("Parameter %d has wrong number of levels, skipped! (name=%s nlevel=%d)", varID + 1, varList1[varID].name, nlevels);
            }
          varnmiss[varID].resize(nlevels);
        }
    }

  for (varID = 0; varID < nvars; ++varID)
    {
      if (varinterp[varID] && varList1[varID].timetype == TIME_CONSTANT) vlistDefVarTimetype(vlistID2, varID, TIME_VARYING);
    }

  const auto streamID2 = cdoOpenWrite(1);

  cdoDefVlist(streamID2, vlistID2);

  int tsID = 0;
  while (true)
    {
      const auto nrecs = cdoStreamInqTimestep(streamID1, tsID);
      if (nrecs == 0) break;

      for (varID = 0; varID < nvars; ++varID)
        {
          vars[varID] = false;
          const auto nlevels = varList1[varID].nlevels;
          for (levelID = 0; levelID < nlevels; levelID++) varnmiss[varID][levelID] = 0;
        }

      taxisCopyTimestep(taxisID2, taxisID1);
      cdoDefTimestep(streamID2, tsID);

      for (int recID = 0; recID < nrecs; recID++)
        {
          cdoInqRecord(streamID1, &varID, &levelID);
          cdoReadRecord(streamID1, vardata1[varID], levelID, &varnmiss[varID][levelID]);
          vars[varID] = true;
        }

      for (varID = 0; varID < nvars; varID++)
        if (varinterp[varID]) vars[varID] = true;

      bool lreverse = true;
      if (-1 != f_heightID && (tsID == 0 || varList1[f_heightID].timetype != TIME_CONSTANT))
        {
          genind(vert_index_full, heightlevs, vardata1[f_heightID], gridsize, lreverse);
          if (!extrapolate)
            {
              height_bottom.init(varList1[f_heightID]);
              fieldCopy(vardata1[f_heightID], nfulllevs - 1, height_bottom);
              genindmiss(vert_index_full, heightlevs, gridsize, height_bottom, pnmiss, lreverse);
            }
        }

      if (-1 != h_heightID && (tsID == 0 || varList1[h_heightID].timetype != TIME_CONSTANT))
        {
          genind(vert_index_half, heightlevs, vardata1[h_heightID], gridsize, lreverse);
          if (!extrapolate)
            {
              height_bottom.init(varList1[h_heightID]);
              fieldCopy(vardata1[h_heightID], nhalflevs - 1, height_bottom);
              genindmiss(vert_index_half, heightlevs, gridsize, height_bottom, pnmiss, lreverse);
            }
        }
      
      for (varID = 0; varID < nvars; varID++)
        {
          if (vars[varID])
            {
              if (tsID > 0 && varList1[varID].timetype == TIME_CONSTANT) continue;

              if (varinterp[varID])
                {
                  const auto nlevels = varList1[varID].nlevels;
                  if (nlevels != nfulllevs && nlevels != nhalflevs)
                    cdoAbort("Number of generalized height level differ from full/half level (param=%s)!", varList1[varID].name);

                  for (levelID = 0; levelID < nlevels; levelID++)
                    {
                      if (varnmiss[varID][levelID]) cdoAbort("Missing values unsupported for this operator!");
                    }

                  if (nlevels == nfulllevs)
                    vertical_interp_X(nlevels, vardata1[f_heightID], vardata1[varID], vardata2[varID], vert_index_full, heightlevs, gridsize);
                  else
                    vertical_interp_X(nlevels, vardata1[h_heightID], vardata1[varID], vardata2[varID], vert_index_half, heightlevs, gridsize);

                  if (!extrapolate) varrayCopy(nheightlevs, pnmiss, varnmiss[varID]);
                }

              for (levelID = 0; levelID < varList2[varID].nlevels; levelID++)
                {
                  cdoDefRecord(streamID2, varID, levelID);
                  cdoWriteRecord(streamID2, varinterp[varID] ? vardata2[varID] : vardata1[varID], levelID, varnmiss[varID][levelID]);
                }
            }
        }

      tsID++;
    }

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  cdoFinish();

  return nullptr;
}
