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

#include <stdlib.h>

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

int
getSeasonStart(void)
{
  static int season_start = START_DEC;
  static bool lgetenv = true;

  if (lgetenv)
    {
      lgetenv = false;

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

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

  return season_start;
}

void
getSeasonName(const char *seas_name[])
{
  if (getSeasonStart() == START_DEC)
    for (int i = 0; i < 4; ++i) seas_name[i] = seas_name_dec[i];
  else
    for (int i = 0; i < 4; ++i) seas_name[i] = seas_name_jan[i];
}

int
monthToSeason(int month)
{
  const auto season_start = getSeasonStart();
  int seas = -1;

  if (month < 0 || month > 16) cdoAbort("Month %d out of range!", month);

  if (season_start == START_DEC)
    {
      seas = (month <= 12) ? (month % 12) / 3 : month - 13;
    }
  else
    {
      seas = (month <= 12) ? (month - 1) / 3 : month - 13;
    }

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

  return seas;
}
