#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
get_season_start(void)
{
  static int season_start = START_DEC;
  static bool lgetenv = true;

  if (lgetenv)
    {
      lgetenv = false;

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

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

  return season_start;
}

void
get_season_name(const char *seas_name[])
{
  if (get_season_start() == 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
month_to_season(int month)
{
  const auto season_start = get_season_start();
  int seas = -1;

  if (month < 0 || month > 16) cdo_abort("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) cdo_abort("Season %d out of range!", seas + 1);

  return seas;
}
