/*
 * FreeAdhocUDF - copyright (c) 2004 adhoc dataservice GmbH Peter Mandrella
 * based on FreeUDFLibC - copyright (c) 1999 Gregory Deatz
 * altered 2001 by ADITO Software GmbH Robert Loipfinger
 *
 *   date_functions.c
 *     Date and time routines
 *
 * for exported functions list see date_functions.h
 */

#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#include "global.h"
#include "date_functions.h"

static ISC_QUAD * gen_ib_date PROTO_LIST ((struct tm *));
static void i_week_of_year PROTO_LIST ((ISC_QUAD *, int *, int *));

#define SUNDAY 0
#define MONDAY 1
#define TUESDAY 2
#define WEDNESDAY 3
#define THURSDAY 4
#define FRIDAY 5
#define SATURDAY 6

#define JANUARY 0
#define FEBRUARY 1
#define MARCH 2
#define APRIL 3
#define MAY 4
#define JUNE 5
#define JULY 6
#define AUGUST 7
#define SEPTEMBER 8
#define OCTOBER 9
#define NOVEMBER 10
#define DECEMBER 11

static const char * DOW[] =
{
 "Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday",
 "Sonntag","Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag",
 "Dimanche","Semaine","Lundi","Mardi","Mercredi","Jeudi","Vendredi","Samedi",
 "Domenica","Settimana","Lunedì","Martedì","Mercoledì","Giovedì","Vernedì","Sabato",
 "Domingo","Lunes","Martes","Miércoles","Jueves","Viernes","Sábado"
};

static const char * MONTH[] =
{
 "January", "February", "March", "April", "May", "June",
 "July", "August", "September", "October", "November", "December",
 "Januar", "Februar", "März", "April", "Mai", "Juni",
 "Juli", "August", "September", "Oktober", "November", "Dezember",
 "Janvier", "Février", "Mars", "Avril", "Mai", "Juin",
 "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre",
 "Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Guigno",
 "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre",
 "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio",
 "Julio", "Agosto", "Setiembre", "Octubre", "Noviembre", "Diciembre"
};

const char* LANG_INDEX = "ukdefrites";


ISC_QUAD * addmonth (ib_date, months_to_add)
     ISC_QUAD *ib_date;
     int *months_to_add;
{
  struct tm t;
  int tm_mon, tm_year;

  isc_decode_date (ib_date, &t);
  tm_mon = t.tm_mon + (*months_to_add % 12);
  tm_year = t.tm_year + (*months_to_add / 12);
  if ((*months_to_add > 0) && (tm_mon < t.tm_mon))
    tm_year++;
  else if ((*months_to_add < 0) && (tm_mon > t.tm_mon))
    tm_year--;

  /*
   * Now, check that the month day is correctly adjusted.
   * 30 days has Sep, Apr, Jun, Nov all the rest have 31 except Feb
   */
  if (tm_mon != FEBRUARY) {
    if (t.tm_mday > 30)
      switch (tm_mon) {
      case APRIL:
      case JUNE:
      case SEPTEMBER:
      case NOVEMBER:
	t.tm_mday = 30;
      }
  }
  else if (t.tm_mday > 28)
    t.tm_mday = isleap(tm_year+1900) ? 29 : 28;

  t.tm_mon = tm_mon;
  t.tm_year = tm_year;

  return (ISC_QUAD *) gen_ib_date(&t);
}

ISC_QUAD * addyear (ib_date, years_to_add)
     ISC_QUAD *ib_date;
     int *years_to_add;
{
  struct tm t;

  isc_decode_date(ib_date, &t);
  t.tm_year += *years_to_add;

  /*
   * If it's February, and the day of the month is 29, and
   * it's *not* a leap year, then adjust the day
   */
  if (t.tm_mon == FEBRUARY && t.tm_mday > 28 && !isleap(t.tm_year+1900))
    t.tm_mday = 28;

  return (ISC_QUAD *) gen_ib_date(&t);
}

// pm 21.08.04  swapped parameters
int ageinmonths (ISC_QUAD *ib_ref_date, ISC_QUAD *ib_date)
{
  struct tm t, t_ref;

  isc_decode_date(ib_date, &t);
  isc_decode_date(ib_ref_date, &t_ref);

  return ((t.tm_year - t_ref.tm_year) * 12) + t.tm_mon - t_ref.tm_mon;
}


// pm 21.08.04
int ageinmonthsthreshold(ISC_QUAD *ib_date, ISC_QUAD *ib_ref_date,
                         int *min, int *usemin, int *max, int *usemax)
{
  int age = ageinmonths(ib_date,ib_ref_date);
  if (*usemin==1 && age<*min)
    age = *min;
  else if (*usemax==1 && age>*max)
    age = *max;
  return age;
}


// pm 21.08.04   rewritten
//
// sunday = 1st day of week
// If the two dates are in the same week, the return value is 0.
int ageinweeks (ISC_QUAD *ib_date, ISC_QUAD *ib_ref_date)
{
  struct tm t, t_ref;
  int days, days_ref;

  isc_decode_date(ib_date, &t);
  isc_decode_date(ib_ref_date, &t_ref);
  days = dtime(ib_date) - t.tm_wday;
  days_ref = dtime(ib_ref_date) - t_ref.tm_wday;

  return (days_ref - days) / 7;
}


// pm 21.08.04
int ageinweeksthreshold(ISC_QUAD *ib_date, ISC_QUAD *ib_ref_date,
                        int *min, int *usemin, int *max, int *usemax)
{
  int age = ageinweeks(ib_date,ib_ref_date);
  if (*usemin==1 && age<*min)
    age = *min;
  else if (*usemax==1 && age>*max)
    age = *max;
  return age;
}


int ageindays (ISC_QUAD *ib_date, ISC_QUAD *ib_ref_date)
{
  return (dtime(ib_ref_date) - dtime(ib_date));
}


// pm 21.08.04
int ageindaysthreshold(ISC_QUAD *ib_date, ISC_QUAD *ib_ref_date,
                       int *min, int *usemin, int *max, int *usemax)
{
  int age = ageindays(ib_date,ib_ref_date);
  if (*usemin==1 && age<*min)
    age = *min;
  else if (*usemax==1 && age>*max)
    age = *max;
  return age;
}


// pm 21.08.04
int decode_language(char *language)
{
  char cl[3];

  cl[0] = language[0] | 0x20;
  cl[1] = language[1] | 0x20;
  cl[2] = '\0';

  if (!strcmp(cl,"us"))
    return 0;
  else
  {
    const char * pc = strstr(LANG_INDEX,cl);
    if (pc == NULL)
      return -1;
    else
      return (pc-LANG_INDEX) / 2;
  }
}


// pm 21.08.04
char * cdowlonglang (ISC_QUAD *ib_date, char *language)
{
  struct tm t;
  char * result = (char *) MALLOC (LOC_STRING_SIZE);
  int lang;

  isc_decode_date(ib_date, &t);
  lang = decode_language(language);
  if (lang < 0)
    strcpy(result,"???");
  else                                          
    strcpy(result,DOW[lang*7 + t.tm_wday]);

  return result;
}


// pm 21.08.04
char * cdowlong (ISC_QUAD *ib_date)
{
  return cdowlonglang(ib_date,"us");
}


// pm 21.08.04
char * cdowshortlang (ISC_QUAD *ib_date, char * language)
{
  char * result = cdowlonglang(ib_date,language);
  result[3] = '\0';
  return result;
}


// pm 21.08.04
char * cdowshort (ISC_QUAD *ib_date)
{
  return cdowshortlang(ib_date,"us");
}


// pm 21.08.04  optimized
char * cmonthlonglang (ISC_QUAD *ib_date, char *language)
{
  struct tm t;
  char * result = (char *) MALLOC (LOC_STRING_SIZE);
  int lang;

  isc_decode_date(ib_date, &t);
  lang = decode_language(language);
  if (lang < 0)
    strcpy(result,"???");
  else
    strcpy(result,MONTH[12*lang + t.tm_mon]);

  return result;
}


// pm 21.08.04  optimized
char * cmonthlong (ISC_QUAD *ib_date)
{
  return cmonthlonglang(ib_date,"us");
}


// pm 21.08.04 optimized
char * cmonthshortlang (ISC_QUAD *ib_date, char * language)
{
  char * result = cmonthlonglang(ib_date,language);
  result[3] = '\0';
  return result;
}


// pm 21.08.04 optimized
char * cmonthshort (ISC_QUAD *ib_date)
{
  return cmonthshortlang(ib_date,"us");
}


int dayofmonth (ib_date)
     ISC_QUAD *ib_date;
{
  struct tm t;
  isc_decode_date(ib_date, &t);

  return t.tm_mday;
}

int dayofweek (ib_date)
     ISC_QUAD *ib_date;
{
  struct tm t;
  isc_decode_date(ib_date, &t);

  return t.tm_wday + 1;
}

int dayofyear (ib_date)
     ISC_QUAD *ib_date;
{
  struct tm t;
  isc_decode_date(ib_date, &t);

  return t.tm_yday + 1;
}

// pm 21.08.04
char * gformatd (char *format, ISC_QUAD *ib_date)
{
  struct tm t;
  char * result = (char *) MALLOC (LOC_STRING_SIZE);
  char * pr = result;
  char c;
  int count;
  const char *pcmonth, *pcdow;

  isc_decode_date(ib_date, &t);

  while (*format)
  {
    c = *format++;
    count = 1;
    while (*format == c)
      count++, format++;

    pcdow = DOW[7 + t.tm_wday];       // german
    pcmonth = MONTH[12 + t.tm_mon];   // german

    switch (c)
    {
      case 'd':  if (count==1) sprintf(pr,"%d",t.tm_mday);
                 else if (count==2) sprintf(pr,"%02d",t.tm_mday);
                 else if (count==3) sprintf(pr,"%c%c%c",
	           pcdow[0], pcdow[1], pcdow[2]);
		 else if (count==4) strcpy(pr,pcdow);
		 break;

      case 'm':  if (count==1) sprintf(pr,"%d",t.tm_mon+1);
                 else if (count==2) sprintf(pr,"%02d",t.tm_mon+1);
                 else if (count==3) sprintf(pr,"%c%c%c",
	           pcmonth[0], pcmonth[1], pcmonth[2]);
		 else if (count==4) strcpy(pr,pcmonth);
		 break;

      case 'y':  if (count==2) sprintf(pr,"%02d",t.tm_year % 100);
                 else if (count==4) sprintf(pr,"%04d",t.tm_year + 1900);
      	         break;

      case 'h':  if (count==1) sprintf(pr,"%d",t.tm_hour);
	         else if (count==2) sprintf(pr,"%02d",t.tm_hour);
	         break;

      case 'n':  if (count==1) sprintf(pr,"%d",t.tm_min);
	         else if (count==2) sprintf(pr,"%02d",t.tm_min);
                 break;

      case 's':  if (count==1) sprintf(pr,"%d",t.tm_sec);
	         else if (count==2) sprintf(pr,"%02d",t.tm_sec);
	         break;

      default:   while (count--)
                   *pr++ = c;
		 *pr = '\0';

    }

    while (*pr) pr++;
  }

  *pr = '\0';
  return result;
}


int isleapyear (ib_date)
     ISC_QUAD *ib_date;
{
  struct tm t;
  isc_decode_date(ib_date, &t);

  return isleap(t.tm_year+1900);
}


ISC_QUAD * maxdate (ib_date_1, ib_date_2)
     ISC_QUAD *ib_date_1;
     ISC_QUAD *ib_date_2;
{
  ISC_QUAD * result = (ISC_QUAD *) MALLOC(sizeof(ISC_QUAD));
  
  if ((ib_date_1->isc_quad_high > ib_date_2->isc_quad_high) ||
      ((ib_date_1->isc_quad_high == ib_date_2->isc_quad_high) &&
       (ib_date_1->isc_quad_low > ib_date_2->isc_quad_low)))
    *result = *ib_date_1;
  else
    *result = *ib_date_2;

  return result;
}


ISC_QUAD * mindate (ib_date_1, ib_date_2)
     ISC_QUAD *ib_date_1;
     ISC_QUAD *ib_date_2;
{
  ISC_QUAD * result = (ISC_QUAD *) MALLOC(sizeof(ISC_QUAD));

  if ((ib_date_1->isc_quad_high < ib_date_2->isc_quad_high) ||
      ((ib_date_1->isc_quad_high == ib_date_2->isc_quad_high) &&
       (ib_date_1->isc_quad_low < ib_date_2->isc_quad_low)))
    *result = *ib_date_1;
  else
    *result = *ib_date_2;

  return result;
}


int month (ib_date)
     ISC_QUAD *ib_date;
{
  struct tm t;
  isc_decode_date(ib_date, &t);

  return t.tm_mon + 1;
}


// pm 21.08.04  bug fixed
int quarter (ib_date)
     ISC_QUAD *ib_date;
{
  struct tm t;
  isc_decode_date(ib_date, &t);

  return t.tm_mon / 3 + 1;
}


ISC_QUAD * stripdate (ib_date)
     ISC_QUAD *ib_date;
{
  struct tm t;
  isc_decode_date(ib_date, &t);

  t.tm_mday = 0;
  t.tm_mon = 0;
  t.tm_year = 0;
  t.tm_wday = 0;
  t.tm_yday = 0;

  return gen_ib_date(&t);
}


ISC_QUAD * striptime (ib_date)
     ISC_QUAD *ib_date;
{
  struct tm t;
  isc_decode_date(ib_date, &t);

  t.tm_sec = 0;
  t.tm_min = 0;
  t.tm_hour = 0;
  t.tm_isdst = 0;

  return gen_ib_date(&t);
}


ISC_QUAD * strtotime (sz)
     char *sz;
{
  struct tm t;
  int len = strlen(sz);
  int h, m, s, pm, i;
  ISC_QUAD * result = (ISC_QUAD *) MALLOC(sizeof(ISC_QUAD));

  i = 0;
  h = strtol(sz, NULL, 10);
  while (i < len && (sz[i] != ':')) i++; i++;
  if (i < len) {
    m = strtol(&sz[i], NULL, 10);
    while (i < len && (sz[i] != ':')) i++; i++;
  } else
    m = 0;
  if (i < len)
    s = strtol(&sz[i], NULL, 10);
  else
    s = 0;
  pm = len >= 2 ? (strcmp(&sz[len - 2], "AM")) : 0;

  t.tm_sec = s;
  t.tm_min = m;
  if (pm)
    t.tm_hour = (h + ((h == 12) ? 0 : 12)) % 24;
  else
    t.tm_hour = (h + ((h == 12) ? 12 : 0)) % 24;
  t.tm_mday = 0;
  t.tm_mon = 0;
  t.tm_year = 0;
  t.tm_wday = 0;
  t.tm_yday = 0;
  t.tm_isdst = 0;

  isc_encode_date(&t, result);
  return result;
}


int week (ISC_QUAD *ib_date)
{
  struct tm t;
  int dow_ybeg, /*yr,*/ wk;

  isc_decode_date(ib_date, &t);

//  yr = t.tm_year + 1900;

  /* On what day of the week did the year begin? */
  dow_ybeg = ((t.tm_wday + 7) - (t.tm_yday % 7)) % 7;
  
  wk = ((t.tm_yday - t.tm_wday + 7) / 7) + 1;
  if (dow_ybeg == SUNDAY)
    return wk - 1;
  else
    return wk;
}


int weekofyear (ib_date)
     ISC_QUAD *ib_date;
{
  int week, year;

  i_week_of_year(ib_date, &week, &year);
  return week;
}


char * woy (ib_date)
     ISC_QUAD *ib_date;
{
  char * result = (char *) MALLOC (LOC_STRING_SIZE + 1);
  int week, year;

  i_week_of_year(ib_date, &week, &year);

  sprintf(result, "%d%2d", year, week);
  return result;
}


int year (ib_date)
     ISC_QUAD *ib_date;
{
  struct tm t;
  isc_decode_date(ib_date, &t);

  return t.tm_year + 1900;
}


int yearofyear (ib_date)
     ISC_QUAD *ib_date;
{
  int week, year;

  i_week_of_year(ib_date, &week, &year);
  return year;
}


int hour (ib_date)
     ISC_QUAD *ib_date;
{
  struct tm t;
  isc_decode_date(ib_date, &t);
  return t.tm_hour;
}


int minute (ib_date)
     ISC_QUAD *ib_date;
{
  struct tm t;
  isc_decode_date(ib_date, &t);
  return t.tm_min;
}


int second (ib_date)
     ISC_QUAD *ib_date;
{
  struct tm t;
  isc_decode_date(ib_date, &t);
  return t.tm_sec;
}


/*       dtime - Returns days since 31.12.1899                                 - (c) 2000 Robert Loipfinger
*/
// pm 21.08.04   renamed from d_time, bugfixed
int dtime (ib_date)
     ISC_QUAD *ib_date;
{
  struct tm t;
  int day,i,year;
  day=0;
  isc_decode_date(ib_date, &t);

  for (i = 0; i < t.tm_year; i++)
        day += isleap(i+1900) ? 366 : 365;

  for (i = 0; i < t.tm_mon; i++)
  {
    year = t.tm_year+1900;
    day += daysofmonth(&i, &year);
  }

  day += t.tm_mday-1;

  return day;
}


// pm 21.08.04   renamed (from dayinmonth)
int daysofmonth (int *m, int *y)
{
    if (*m == 1){
        if (!isleap(*y))
                return 28;
        else
                return 29;
    }


    if ((*m==3) || (*m==5) || (*m==8) || (*m==10))
        return 30;

    return 31;
}


static ISC_QUAD * gen_ib_date (t)
     struct tm *t;
{
  ISC_QUAD *ibd = (ISC_QUAD *) MALLOC (sizeof(ISC_QUAD));
  isc_encode_date(t, ibd);
  return ibd;
}


/*
 * Simple observations:
 *   7 * 52 = 364 = a common year + 1 (or 2 if it is a leap year)
 *   There are 365-366 days in the year.
 *   A week is Sunday - Saturday.
 * So....
 *
 * if the year begins on a Sun - Wed, then Jan 1 is considered to begin
 *   Week #1.
 * if the year begins on Thu - Sat, then Jan 1 is considered to still
 *   be part of the last week of the previous year.
 * if the year begins on a Wed OR
 *    the year begins on a Tue or Wed and its a leap year THEN
 *   the year has 53 weeks in it...
 */
static void i_week_of_year (ib_date, week, year)
     ISC_QUAD * ib_date;
     int * week;
     int * year;
{
  struct tm t;
  int dow_ybeg, yr, wk;

  isc_decode_date(ib_date, &t);

  yr = t.tm_year + 1900;

  /* When did the year begin? */
  dow_ybeg = ((t.tm_wday + 7) - (t.tm_yday % 7)) % 7;
  
  /* Get the Sunday beginning this week. */
  wk = (t.tm_yday - t.tm_wday);
  /*
   * If the Sunday beginning this week was last year, then
   *   if this year begins on a Wednesday or previous, then
   *   this is most certainly the first week of the year.
   *   if this year begins on a thursday or
   *     last year was a leap year and this year begins on a friday, then
   *   this week is 53 of last year.
   *   Otherwise this week is 52 of last year.
   */
  if (wk < 0) {
    if (dow_ybeg <= WEDNESDAY)
      wk = 1;
    else if ((dow_ybeg == THURSDAY) ||
	     (isleap((yr - 1)) && (dow_ybeg == FRIDAY))) {
      wk = 53;
      yr--;
    } else {
      wk = 52;
      yr--;
    }
  }
  else {
    /* If the Sunday beginning this week falls in this year
     *   if the year begins on a Sun, Mon, Tue or Wed then
     *     This week # is (Week + 7) div 7
     *   otherwise this week is
     *     Week div 7 + 1.
     *   if the week is > 52 then
     *     if this year began on a wed or this year is leap year and it
     *       began on a tuesday, then set the week to 53.
     *     otherwise set the week to 1 of *next* year.
     */
    if (dow_ybeg <= WEDNESDAY)
      wk = (wk + 7 + dow_ybeg) / 7;
    else
      wk = (wk / 7) + 1;
    if (wk > 52) {
      if ((dow_ybeg == WEDNESDAY) ||
	  (isleap(yr) && (dow_ybeg == TUESDAY)))
	wk = 53;
      else {
        wk = 1;
	yr++;
      }
    }
  }
  *week = wk;
  *year = yr;
}

