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

#include <cdi.h>

#include "process_int.h"
#include "cdo_options.h"

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

  cdoInitialize(process);

  operatorCheckArgc(0);

  const auto lcopy = unchangedRecord();

  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);

  const auto ntsteps = vlistNtsteps(vlistID1);

  Varray<double> array;
  if (!lcopy)
    {
      const auto gridsizemax = vlistGridsizeMax(vlistID1);
      array.resize(gridsizemax);
    }

  int tsID = 0;
  int fyear = 0, lyear, fmonth = 0, lmonth, dummy;
  int step_per_year = 0, currentyear, currentmon;

  while ((nrecs = cdoStreamInqTimestep(streamID1, tsID)))
    {
      if (tsID == 0)
        {
          cdiDecodeDate(taxisInqVdate(taxisID1), &fyear, &fmonth, &dummy);
          currentyear = fyear;
          currentmon = fmonth;
        }
      else
        cdiDecodeDate(taxisInqVdate(taxisID1), &currentyear, &currentmon, &dummy);
      if (currentyear == fyear)
        {
          // lymonth = currentmon;
          step_per_year++;
        }
      taxisCopyTimestep(taxisID2, taxisID1);
      cdoDefTimestep(streamID2, tsID);

      for (int recID = 0; recID < nrecs; recID++)
        {
          cdoInqRecord(streamID1, &varID, &levelID);
          cdoDefRecord(streamID2, varID, levelID);

          if (lcopy)
            {
              cdoCopyRecord(streamID2, streamID1);
            }
          else
            {
              cdoReadRecord(streamID1, array.data(), &nmiss);
              cdoWriteRecord(streamID2, array.data(), nmiss);
            }
        }

      tsID++;
    }

  const char *frequency = "";

  if (ntsteps > 2)
    {
      cdoStreamInqTimestep(streamID2, ntsteps);
      cdiDecodeDate(taxisInqVdate(taxisID2), &lyear, &lmonth, &dummy);
      /* First, estimation by maximal number of time steps divided by covered years between last and first time step */
      if (Options::cdoVerbose)
        printf("Frequency is calculated by dividing the number of time steps '%d' included in the time axis by the covered years"
               " of the time axis\ncomputed by the difference of the year of the last time stamp '%d' and the year of the first"
               " time stamp '%d'.\n",
               ntsteps, lyear, fyear);
      double covered_years = lyear - fyear + 1.0;
      double freq = ntsteps / covered_years;
      if (DBL_IS_EQUAL(freq, 1.))
        frequency = "yr";
      else if (DBL_IS_EQUAL(freq, 12.))
        frequency = "mon";
      else if (IS_EQUAL(freq, 365.) || IS_EQUAL(freq, 365.25) || IS_EQUAL(freq, 366.))
        frequency = "day";
      else if (IS_EQUAL(freq, 365. * 4) || IS_EQUAL(freq, 365.25 * 4) || IS_EQUAL(freq, 366. * 4))
        frequency = "6hr";
      else if (IS_EQUAL(freq, 365. * 8) || IS_EQUAL(freq, 365.25 * 8) || IS_EQUAL(freq, 366. * 8))
        frequency = "3hr";
      else
        {
          int covered_months = lmonth - fmonth + 1;
          if (Options::cdoVerbose)
            printf("The fraction ntsteps / covered_years = '%f' is neither 1, 12, 365, 365.25, 366 nor a multiple of 365 which "
                   "would correspond to frequencies yearly, monthly, daily or subdaily respectively.\n Next try:\n\nFrequency is "
                   "calculated by dividing the number of time steps '%d' in year '%d' by the covered months in that year '%d'.\n",
                   ntsteps / covered_years, step_per_year, fyear, covered_months);
          if (step_per_year > 366 * 8)
            cdoAbort("Step per year '%d' in year '%d' is bigger than 366*8 which corresponds to a frequency of sub-3hourly!"
                     " This is not yet enabled.",
                     step_per_year, fyear);
          else
            {
              freq = (double) step_per_year / (double) covered_months;
              // clang-format off
              if      (freq > 31 * 8) cdoAbort("Frequency is sub-3hourly! Not yet enabled.");
              else if (freq > 31 * 4) frequency = "3hr";
              else if (freq > 31)     frequency = "6hr";
              else if (freq > 1)      frequency = "day";
              else                    frequency = "mon";
              // clang-format on
            }
        }
    }
  else
    cdoAbort("For %d found timesteps no frequency can be computed - at least 3 timesteps are required.", ntsteps);

  if (Options::cdoVerbose) printf("Your file indicates a frequency of '%s'.\n", frequency);
  cdiDefAttTxt(vlistID2, CDI_GLOBAL, "frequency", 3, frequency);

  cdoStreamClose(streamID1);
  cdoStreamClose(streamID2);

  vlistDestroy(vlistID2);

  cdoFinish();

  return nullptr;
}
