#include "cdo_season.h"
#include "compare.h"
#include "cdo_output.h"
#include "cdo_options.h"

#include <stdlib.h>

const char *seasonNamesDec[4] = { "DJF", "MAM", "JJA", "SON" };
const char *seasonNamesJan[4] = { "JFM", "AMJ", "JAS", "OND" };

int
get_season_start(void)
{
  static int seasonStart = START_DEC;
  static bool lgetenv = true;

  if (lgetenv)
    {
      lgetenv = false;

      char *envstr = getenv("CDO_SEASON_START");
      if (envstr)
        {
          if (cdo_cmpstr(envstr, "DEC"))
            seasonStart = START_DEC;
          else if (cdo_cmpstr(envstr, "JAN"))
            seasonStart = START_JAN;

          if (Options::cdoVerbose)
            {
              if (seasonStart == START_DEC)
                cdo_print("Set SEASON_START to December");
              else if (seasonStart == START_JAN)
                cdo_print("Set SEASON_START to January");
            }
        }
    }

  return seasonStart;
}

void
get_season_name(const char *seasonNames[])
{
  if (get_season_start() == START_DEC)
    for (int i = 0; i < 4; ++i) seasonNames[i] = seasonNamesDec[i];
  else
    for (int i = 0; i < 4; ++i) seasonNames[i] = seasonNamesJan[i];
}
/*
const char **
get_season_name(void)
{
  return (get_season_start() == START_DEC) ? seasonNamesDec : seasonNamesJan;
}
*/
int
month_to_season(int month)
{
  if (month < 0 || month > 16) cdo_abort("Month %d out of range!", month);

  const auto zmonth = (get_season_start() == START_DEC) ? (month % 12) : (month - 1);
  const auto season = (month <= 12) ? zmonth / 3 : month - 13;

  if (season < 0 || season > 3) cdo_abort("Season %d out of range!", season + 1);

  return season;
}
