/*
  This file is part of CDO. CDO is a collection of Operators to
  manipulate and analyse Climate model Data.

  Copyright (C) 2006 Brockmann Consult
  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:

      Wct     wct          Compute the windchill temperature (degree C)
*/

#include <cdi.h>

#include "cdo_options.h"
#include "functs.h"
#include "process_int.h"
#include "cdo_vlist.h"
#include "cdo_cdi_wrapper.h"

static const char WCT_NAME[] = "wind_chill_temperature";
static const char WCT_LONGNAME[] = "Windchill temperature describes the fact that low temperatures are felt "
                                   "to be even lower in case of wind. It is based on the rate of heat loss "
                                   "from exposed skin caused by wind and cold. It is calculated according "
                                   "to the empirical formula: 33 + (T - 33) * (0.478 + 0.237 * ( "
                                   "SQRT(ff*3.6) - 0.0124 * ff * 3.6)) with T  = air temperature in "
                                   "degree Celsius, ff = 10 m wind speed in m/s. Windchill temperature is "
                                   "only defined for temperatures at or below 33 degree Celsius and wind "
                                   "speeds above 1.39 m/s. It is mainly used for freezing temperatures.";
static const char WCT_UNITS[] = "Celsius";

static const int FIRST_VAR = 0;

static double
windchillTemperature(double t, double ff, double missval)
{
  constexpr double tmax = 33.0;
  constexpr double vmin = 1.39; /* minimum wind speed (m/s) */

  return ff < vmin || t > tmax ? missval : tmax + (t - tmax) * (0.478 + 0.237 * (std::sqrt(ff * 3.6) - 0.0124 * ff * 3.6));
}

static void
farexpr(Field &field1, Field &field2, double (*expression)(double, double, double))
{
  const auto missval1 = field1.missval;
  const auto missval2 = field2.missval;

  const auto len = field1.size;
  if (len != field2.size) cdoAbort("Fields have different size (%s)", __func__);

  if (field1.nmiss || field2.nmiss)
    {
      for (size_t i = 0; i < len; i++)
        if (DBL_IS_EQUAL(field1.vec_d[i], missval1) || DBL_IS_EQUAL(field2.vec_d[i], missval2))
          field1.vec_d[i] = missval1;
        else
          field1.vec_d[i] = expression(field1.vec_d[i], field2.vec_d[i], missval1);
    }
  else
    {
      for (size_t i = 0; i < len; i++) field1.vec_d[i] = expression(field1.vec_d[i], field2.vec_d[i], missval1);
    }

  field1.nmiss = fieldNumMiss(field1);
}

void *
Wct(void *process)
{
  int nrecs, nrecs2;
  int varID1, varID2;
  int levelID1, levelID2;

  cdoInitialize(process);
  cdoOperatorAdd("wct", 0, 0, nullptr);

  operatorCheckArgc(0);

  const auto streamID1 = cdoOpenRead(0);
  const auto streamID2 = cdoOpenRead(1);

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

  const auto taxisID1 = vlistInqTaxis(vlistID1);

  vlistCompare(vlistID1, vlistID2, CMP_DIM);

  const auto gridsizemax = vlistGridsizeMax(vlistID1);

  Field field1, field2;
  field1.resize(gridsizemax);
  field2.resize(gridsizemax);

  if (Options::cdoVerbose) cdoPrint("Number of timesteps: file1 %d, file2 %d", vlistNtsteps(vlistID1), vlistNtsteps(vlistID2));

  const auto vlistID3 = vlistCreate();
  const auto gridID = vlistInqVarGrid(vlistID1, FIRST_VAR);
  const auto zaxisID = vlistInqVarZaxis(vlistID1, FIRST_VAR);
  const auto varID3 = vlistDefVar(vlistID3, gridID, zaxisID, TIME_VARYING);

  const auto taxisID3 = cdoTaxisCreate(TAXIS_RELATIVE);
  taxisDefTunit(taxisID3, TUNIT_MINUTE);
  taxisDefCalendar(taxisID3, CALENDAR_STANDARD);
  taxisDefRdate(taxisID3, 19550101);
  taxisDefRtime(taxisID3, 0);
  vlistDefTaxis(vlistID3, taxisID3);

  cdiDefKeyString(vlistID3, varID3, CDI_KEY_NAME, WCT_NAME);
  cdiDefKeyString(vlistID3, varID3, CDI_KEY_LONGNAME, WCT_LONGNAME);
  cdiDefKeyString(vlistID3, varID3, CDI_KEY_UNITS, WCT_UNITS);

  const auto streamID3 = cdoOpenWrite(2);
  cdoDefVlist(streamID3, vlistID3);

  int tsID = 0;
  while ((nrecs = cdoStreamInqTimestep(streamID1, tsID)))
    {
      nrecs2 = cdoStreamInqTimestep(streamID2, tsID);
      if (nrecs2 == 0) cdoAbort("Input streams have different number of timesteps!");

      taxisCopyTimestep(taxisID3, taxisID1);
      cdoDefTimestep(streamID3, tsID);

      for (int recID = 0; recID < nrecs; recID++)
        {
          cdoInqRecord(streamID1, &varID1, &levelID1);
          cdoReadRecord(streamID1, field1.vec_d.data(), &field1.nmiss);

          cdoInqRecord(streamID2, &varID2, &levelID2);
          cdoReadRecord(streamID2, field2.vec_d.data(), &field2.nmiss);

          if (varID1 != varID2 || levelID1 != levelID2) cdoAbort("Input streams have different structure!");

          if (varID1 != FIRST_VAR) continue;

          field1.missval = vlistInqVarMissval(vlistID1, varID1);
          field2.missval = vlistInqVarMissval(vlistID2, varID2);

          farexpr(field1, field2, windchillTemperature);

          cdoDefRecord(streamID3, varID3, levelID1);
          cdoWriteRecord(streamID3, field1.vec_d.data(), field1.nmiss);
        }

      tsID++;
    }

  cdoStreamClose(streamID3);
  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  cdoFinish();

  return nullptr;
}
