/*
 * FreeAdhocUDF - copyright (c) 2004 - 2006 adhoc dataservice GmbH
 * Christoph Theuring / Peter Mandrella / Georg Horn
 * based on FreeUDFLibC - copyright (c) 1999 Gregory Deatz
 *
 * File Name:	date_functions.c
 * Description: this module contains UDFs to generate and manipulate date and time.
 *
 * for exported functions list see date_functions.h
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * rights and limitations under the License.
 *
*****************************************************************/

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

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

// gh 2006-10-24
// 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","Lundi","Mardi","Mercredi","Jeudi","Vendredi","Samedi",
 "Domenica","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 * 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 16.05.2006 Korrektur
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 + 12 * t.tm_year + *months_to_add;
  tm_year = tm_mon / 12;
  tm_mon %= 12;

  /*
   * 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);
}



// pm 16.10.05
static int daysoftsmonth(
        struct tm *t)
{
  int month = t->tm_mon + 1;
  int year = t->tm_year + 1900;
  return daysofmonth(&month,&year);
}


// pm 16.10.05
// pm 24.02.06 Korrektur
static ISC_QUAD * addseconds (ISC_QUAD *date, int seconds)
{
  struct tm t;

  isc_decode_date(date,&t);

  t.tm_sec += seconds;

  if (t.tm_sec >= 60)
  {
    t.tm_min  += (t.tm_sec / 60);  t.tm_sec %= 60;
    t.tm_hour += (t.tm_min / 60);  t.tm_min %= 60;
    t.tm_mday += (t.tm_hour / 24); t.tm_hour %= 24;

    while (t.tm_mday > daysoftsmonth(&t))
    {
      t.tm_mday -= daysoftsmonth(&t);
      t.tm_mon++;
      if (t.tm_mon > 11)
        t.tm_mon=0, t.tm_year++;
    }
  }
  else if (t.tm_sec < 0)
  {
    t.tm_min += ((t.tm_sec - 59) / 60);
    t.tm_sec = (t.tm_sec % 60) + 60;
    if (t.tm_min < 0)
    {
      t.tm_hour += ((t.tm_min - 59) / 60);
      t.tm_min = (t.tm_min % 60) + 60;
      if (t.tm_hour < 0)
      {
        t.tm_mday += ((t.tm_hour - 23) / 24);
        t.tm_hour = (t.tm_hour % 24) + 24;

        while (t.tm_mday < 1)
        {
          t.tm_mon--;
          if (t.tm_mon < 0)
            t.tm_mon = 11, t.tm_year--;
          t.tm_mday += daysoftsmonth(&t);
        }
      }
    }
  }

  return gen_ib_date(&t);
}

// pm 16.10.05
ISC_QUAD * addweek (ISC_QUAD *date, int *weeks)       { return addseconds(date, 7 * 24 * 60 * 60 * *weeks); }
ISC_QUAD * addday (ISC_QUAD *date, int *days)         { return addseconds(date, 24 * 60 * 60 * *days);      }
ISC_QUAD * addhour (ISC_QUAD *date, int *hours)       { return addseconds(date, 60 * 60 * *hours);          }
ISC_QUAD * addminute (ISC_QUAD *date, int *minutes)   { return addseconds(date, 60 * *minutes);             }
ISC_QUAD * addsecond (ISC_QUAD *date, int *seconds)   { return addseconds(date, *seconds);                  }




// pm 16.10.05
int ageinyears (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;
}


// pm 16.10.05
// ct 15.05.2006 Korrektur
int ageinyearsthreshold (ISC_QUAD *ib_ref_date, ISC_QUAD *ib_date,
        int *min, int *usemin, int *max, int *usemax)
{
  int age = ageinyears(ib_ref_date,ib_date);
  if (*usemin==1 && age<*min)
    age = *min;
  else if (*usemax==1 && age>*max)
    age = *max;
  return age;
}


// 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
// ct 15.05.2006 Korrektur
int ageinmonthsthreshold(ISC_QUAD *ib_ref_date, ISC_QUAD *ib_date,
                         int *min, int *usemin, int *max, int *usemax)
{
  int age = ageinmonths(ib_ref_date,ib_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 03.10.05
int ageinhours(
        ISC_QUAD *date1,
        ISC_QUAD *date2)
{
  return (int)zeitdifferenz(date2,date1,"h");
}


// pm 03.10.05
int ageinhoursthreshold(
        ISC_QUAD *date1,
        ISC_QUAD *date2,
        int *min,
        int *usemin,
        int *max,
        int *usemax)
{
  int age = ageinhours(date1,date2);
  if (*usemin==1 && age<*min)
    age = *min;
  else if (*usemax==1 && age>*max)
    age = *max;
  return age;
}


// pm 03.10.05
int ageinminutes (
        ISC_QUAD *date1,
        ISC_QUAD *date2)
{
  return (int)zeitdifferenz(date2,date1,"m");
}


// pm 03.10.05
int ageinminutesthreshold(
        ISC_QUAD *date1,
        ISC_QUAD *date2,
        int *min,
        int *usemin,
        int *max,
        int *usemax)
{
  int age = ageinminutes(date1,date2);
  if (*usemin==1 && age<*min)
    age = *min;
  else if (*usemax==1 && age>*max)
    age = *max;
  return age;
}


// pm 03.10.05
int ageinseconds(
        ISC_QUAD *date1,
        ISC_QUAD *date2)
{
  return (int)zeitdifferenz(date2,date1,"s");
}


// pm 03.10.05
int ageinsecondsthreshold(
        ISC_QUAD *date1,
        ISC_QUAD *date2,
        int *min,
        int *usemin,
        int *max,
        int *usemax)
{
  int age = ageinseconds(date1,date2);
  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);

  if (!strcmp(language,"fr") && result[1] == 'u')
    result[2] = result[3];         // Juin -> Jun,   Juillet -> Jul
  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);
}


// pm 16.10.05  Rueckgabetyp TIME statt TIMESTAMP
ISC_TIME * strtotime (sz)
     char *sz;
{
  struct tm t;
  int len = strlen(sz);
  int h, m, s, pm, i;
  ISC_TIME * result = (ISC_TIME *) MALLOC(sizeof(ISC_TIME));

  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_sql_time(&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 = 1; i <= t.tm_mon; i++)       // um 1 versetzt, wg. daysofmonth-Logik (Monat 1-basiert)
  {
    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 == 2) {
	if (!isleap(*y)) {
	    return 28;
	} else {
	    return 29;
	}
    }

    if ((*m == 4) || (*m == 6) || (*m == 9) || (*m == 11)) {
	return 30;
    }

    return 31;
}

// pm 16.10.05
int lastday (int *y, int *m)
{
  return daysofmonth(m,y);
}


// gh 2006-10-24
// static ISC_QUAD * gen_ib_date (t)
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;
}


// pm 03.10.05
int equaldate
        (ISC_QUAD *date1,
         ISC_QUAD *date2)
{
  struct tm d1, d2;

  isc_decode_date(date1, &d1);
  isc_decode_date(date2, &d2);

  return (d1.tm_year == d2.tm_year &&
          d1.tm_mon == d2.tm_mon &&
          d1.tm_mday == d2.tm_mday);
}


// pm 03.10.05
int equaldatetime
        (ISC_QUAD *date1,
         ISC_QUAD *date2)
{
  struct tm d1, d2;

  isc_decode_date(date1, &d1);
  isc_decode_date(date2, &d2);

  return (d1.tm_year == d2.tm_year &&
          d1.tm_mon == d2.tm_mon &&
          d1.tm_mday == d2.tm_mday &&
          d1.tm_hour == d2.tm_hour &&
          d1.tm_min == d2.tm_min &&
          d1.tm_sec == d2.tm_sec);
}



// pm 03.10.05
double zeitdifferenz
        (ISC_QUAD *date1,
         ISC_QUAD *date2,
         char *sz)
{
  struct tm     d1, d2;
  int           aid;
  int           secdiff;
  double        result = 0;

  isc_decode_date(date1, &d1);
  isc_decode_date(date2, &d2);

  aid = ageindays(date2,date1);
  secdiff = (3600*d1.tm_hour + 60 * d1.tm_min + d1.tm_sec) - (3600*d2.tm_hour + 60 * d2.tm_min + d2.tm_sec);


  if (strlen(sz) == 1)
    switch (sz[0])
    {
      case 't':  result = aid + (double)secdiff / 86400.0; break;
      case 'h':  result = aid*24 + (double)secdiff / 3600.0; break;
      case 'm':  result = (double)aid * 1440.0 + (double)secdiff / 60.0; break;
      case 's':  result = (double)aid * 86400.0 + secdiff; break;
    }

  //if (result <= 0)
  //  result = 0;

  return result;
}



// pm 03.10.05
ISC_QUAD *osterdatum
        (int *year)
{
  struct tm     date;
  int           m = 0, n = 0;
  int           a,b,c,d,e;

  if (*year < 100) {
    if (*year <= 80) {
	*year += 2000;
    } else {
	*year += 1900;
    }
  }

  // Osteralgorithmus (Pascal) von Michael Heydekamp

  date.tm_year = *year - 1900;

  if (*year<1700) m=22, n=2;
  else if (*year<1800) m=23, n=3;
  else if (*year<1900) m=23, n=4;
  else if (*year<2100) m=24, n=5;
  else if (*year<2200) m=24, n=6;
  else if (*year<2300) m=25, n=0;
  a = *year % 19;
  b = *year % 4;
  c = *year % 7;
  d = (19*a+m) % 30;
  e = (2*b + 4*c + 6*d + n) % 7;
  if (22+d+e <= 31)
    date.tm_mday = 22+d+e, date.tm_mon=3;
  else
    date.tm_mday = d+e-9, date.tm_mon=4;
  if (date.tm_mday==26 && date.tm_mon==4)
    date.tm_mday = 19;
  else if (date.tm_mday==25 && date.tm_mon==4 && d==28 && e==6 && a>10)
    date.tm_mday = 18;

  date.tm_mon--;

  date.tm_sec = 0;
  date.tm_min = 0;
  date.tm_hour = 0;
  date.tm_wday = 0;
  date.tm_yday = 0;

  return gen_ib_date(&date);
}


// pm 16.10.05
int yearsbetween (ISC_QUAD *d1, ISC_QUAD *d2)    { return abs(ageinyears(d1,d2));   }
int monthsbetween (ISC_QUAD *d1, ISC_QUAD *d2)   { return abs(ageinmonths(d1,d2));  }
int weeksbetween (ISC_QUAD *d1, ISC_QUAD *d2)    { return abs(ageinweeks(d1,d2));   }
int daysbetween (ISC_QUAD *d1, ISC_QUAD *d2)     { return abs(ageindays(d1,d2));    }
int hoursbetween (ISC_QUAD *d1, ISC_QUAD *d2)    { return abs(ageinhours(d1,d2));   }
int minutesbetween (ISC_QUAD *d1, ISC_QUAD *d2)  { return abs(ageinminutes(d1,d2)); }
int secondsbetween (ISC_QUAD *d1, ISC_QUAD *d2)  { return abs(ageinseconds(d1,d2)); }


// pm 16.10.05
ISC_DATE * encodedate (int *year, int *month, int *day)
{
  ISC_DATE * result = (ISC_DATE *) MALLOC(sizeof(ISC_DATE));
  struct tm t;

  t.tm_year = *year - 1900;
  t.tm_mon = *month - 1;
  t.tm_mday = *day;

  t.tm_wday = 0;
  t.tm_yday = 0;

  isc_encode_sql_date(&t,result);

  return result;
}


// pm 16.10.05
ISC_TIME * encodetime (int *hour, int *minute, int *second)
{
  ISC_TIME * result = (ISC_TIME *) MALLOC(sizeof(ISC_TIME));
  struct tm t;

  t.tm_hour = *hour;
  t.tm_min = *minute;
  t.tm_sec = *second;

  isc_encode_sql_time(&t,result);

  return result;
}


// pm 16.10.05
ISC_QUAD * encodetimestamp (int *year, int *month, int *day,
                            int *hour, int *minute, int *second)
{
  struct tm t;

  t.tm_year = *year - 1900;
  t.tm_mon = *month - 1;
  t.tm_mday = *day;
  t.tm_hour = *hour;
  t.tm_min = *minute;
  t.tm_sec = *second;

  t.tm_wday = 0;
  t.tm_yday = 0;

  return gen_ib_date(&t);
}


