blob_functions.h                                                                                    0000744 0000000 0000764 00000005370 10756255120 013060  0                                                                                                    ustar   root                            adhoc                                                                                                                                                                                                                  /*****************************************************************************
 * FreeAdhocUDF - copyright (c) 2004 - 2008 adhoc dataservice GmbH
 * Christoph Theuring / Peter Mandrella / Georg Horn
 * <http://www.udf.adhoc-data.de> eMail <udf@adhoc-data.de>
 * based on FreeUDFLibC - copyright (c) 1999 Gregory Deatz
 *
 * File Name:	blob_functions.h
 * Description: This header contains the prototype definitions
 *
 * This file is part of FreeAdhocUDF.
 * FreeAdhocUDF is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * FreeAdhocUDF is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with FreeAdhocUDF.  If not, see <http://www.gnu.org/licenses/>. 
*****************************************************************************/

/* Blob passing structure */
// InterBase uses follows, FireBird uses from ibase.h
#ifndef FB_API_VER
typedef struct blobcallback {
    short (*blob_get_segment) (void *hnd, void *buffer, long buf_size, long *result_len);
    isc_blob_handle *blob_handle;
    ISC_LONG blob_number_segments;
    ISC_LONG blob_max_segment;
    ISC_LONG blob_total_length;
    void (*blob_put_segment) (void *hnd, const void *buffer, ISC_USHORT buf_size);
    ISC_LONG(*blob_lseek) (void *hnd, ISC_USHORT mode, ISC_LONG offset);
} *BLOBCALLBACK;
#endif

char * blobaspchar (BLOBCALLBACK);
char * intern_blobaspchar (BLOBCALLBACK, int);
char * blobleft (BLOBCALLBACK, int *);
char * blobmid (BLOBCALLBACK, ISC_LONG *, int *);
char * r_blobmid (BLOBCALLBACK, int *, int *);
char * blobright (BLOBCALLBACK, int *);
ISC_LONG * blobsize (BLOBCALLBACK);
BLOBCALLBACK strblob (char *, BLOBCALLBACK);
BLOBCALLBACK blobcat (BLOBCALLBACK, BLOBCALLBACK, BLOBCALLBACK);
BLOBCALLBACK blobcatstr (BLOBCALLBACK, char *, BLOBCALLBACK);
char * excelblob (BLOBCALLBACK);
BLOBCALLBACK blobreplacestring (BLOBCALLBACK, char *, char *, int *,
    int *, BLOBCALLBACK);
ISC_LONG * blobsegmentcount (BLOBCALLBACK);
ISC_LONG * blobmaxsegmentlength (BLOBCALLBACK);
char * blobline (BLOBCALLBACK, int*);
int * bloblinecount (BLOBCALLBACK);
int * blobcompare (BLOBCALLBACK,BLOBCALLBACK);
int * b_strcmp (BLOBCALLBACK,BLOBCALLBACK);
int * blobsubstr (BLOBCALLBACK,char *);
int * b_strpos (char *, BLOBCALLBACK);
int * b_textpos (char *, BLOBCALLBACK);
int * blobwordcount (BLOBCALLBACK);
                                                                                                                                                                                                                                                                        const_functions.c                                                                                   0000744 0000000 0000764 00000003216 10756254776 013300  0                                                                                                    ustar   root                            adhoc                                                                                                                                                                                                                  /*****************************************************************************
 * FreeAdhocUDF - copyright (c) 2004 - 2008 adhoc dataservice GmbH
 * Christoph Theuring ct / Peter Mandrella pm / Georg Horn gh
 * <http://www.udf.adhoc-data.de> eMail <udf@adhoc-data.de>
 *  
 * File Name:	const_functions.c
 * Description: this module contains UDFs of technical constants
 * for exported functions list see const_functions.h
 *
 * This file is part of FreeAdhocUDF.
 * FreeAdhocUDF is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * FreeAdhocUDF is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with FreeAdhocUDF.  If not, see <http://www.gnu.org/licenses/>. 
*****************************************************************************/

#include <math.h>
#include "const_functions.h"

// mathematical constants
// pi
double pi ()
{
   return M_PI;
}

// e Euler
double euler ()
{
  return M_E;
}

// physical constants
// c Lichtgeschwindigkeit [m/s]
int c ()
{
  int result = 299792458;
  return result;
}

// g Erdbeschleunigung [m/s^2]
double g ()
{
  double result = 9.80665;
  return result;
}

// K absoluter Nullpunkt = 0Grad Kelvin
double k ()
{
  double result = -273.15;
  return result;
}

                                                                                                                                                                                                                                                                                                                                                                                  const_functions.h                                                                                   0000744 0000000 0000764 00000002335 10756255026 013273  0                                                                                                    ustar   root                            adhoc                                                                                                                                                                                                                  /*****************************************************************************
 * FreeAdhocUDF - copyright (c) 2004 - 2008 adhoc dataservice GmbH
 * Christoph Theuring / Peter Mandrella / Georg Horn
 * <http://www.udf.adhoc-data.de> eMail <udf@adhoc-data.de>
 *
 * File Name:	const_functions.h
 * Description: This header contains the prototype definitions
 *
 * This file is part of FreeAdhocUDF.
 * FreeAdhocUDF is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * FreeAdhocUDF is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with FreeAdhocUDF.  If not, see <http://www.gnu.org/licenses/>. 
*****************************************************************************/

double pi ();
double euler ();

int c ();
double g ();
double k ();
                                                                                                                                                                                                                                                                                                   conv_functions.c                                                                                    0000744 0000000 0000764 00000077470 10754363072 013120  0                                                                                                    ustar   root                            adhoc                                                                                                                                                                                                                  /*****************************************************************************
 * FreeAdhocUDF - copyright (c) 2004 - 2008 adhoc dataservice GmbH
 * Christoph Theuring ct / Peter Mandrella pm / Georg Horn gh
 * <http://www.udf.adhoc-data.de> eMail <udf@adhoc-data.de>
 *
 * File Name:	conv_functions.c
 * Description: this module contains UDFs to convert units
 * for exported functions list see conv_functions.h
 *
 * This file is part of FreeAdhocUDF.
 * FreeAdhocUDF is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * FreeAdhocUDF is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with FreeAdhocUDF.  If not, see <http://www.gnu.org/licenses/>. 
*****************************************************************************/

#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include "global.h"
#include "conv_functions.h"

/* *** number systems *** */

// pm
// ct 2006-11-25 implementation of NULL for FB 2.0
// number system: number in 33-system to decimal-system
int *convertfrom33(char *sz)
{
    if (!sz)
	return NULL;
    else {
	int base = 33;
	int *result = convertfrombase(sz, &base,
	    "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ");
	return result;
    }
}

// pm 
// ct 2006-11-25 implementation of NULL for FB 2.0
// number system: number in decimal-system to 33-system
char *convertto33(int *value)
{
    if (!value)
	return NULL;
    else {
	int base = 33;
	char *result = converttobase(value, &base,
	    "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ");
	return result;
    }
}

// pm
static int get_value_of(char c, char *digits)
{
    int i;

    for (i = 0; (digits[i] != (char) 0) && (digits[i] != c); i++);
    return i;
}

// pm
// ct 2006-11-25 implementation of NULL for FB 2.0
// number system: number in anyone-system to decimal-system
int *convertfrombase(char *sz, int *base, char *digits)
{
    if (!sz || !base || !digits)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	int i;
	int res = 0;
	int len = strlen(sz);

	for (i = 0; i < len; i++)
	    res = (*base * res) + get_value_of(sz[i], digits);
	*result = res;
	return result;
    }
}

// pm
// ct 2006-11-25 implementation of NULL for FB 2.0
// number system: number decimal-system to in anyone-system
char *converttobase(int *value, int *base, char *digits)
{
    if (!value || !base || !digits)
	return NULL;
    else {
	char sz_res[LOC_STRING_SIZE + 1];
	char *sz_result = (char *) MALLOC(LOC_STRING_SIZE + 1);
	int i = 0;
	int j, r, len_sz_res;
	int first_time = 1;

	for (j = *value; (j != 0) || first_time; j = j / *base, first_time = 0) {
	    r = j % *base;
	    sz_res[i++] = digits[r];
	}
	sz_res[i] = (char) 0;
	sz_result[i] = (char) 0;
	len_sz_res = i;

	for (i = 0; i < len_sz_res; i++)
	    sz_result[i] = sz_res[len_sz_res - i - 1];

	return sz_result;
    }
}

// pm 2005-10-03
// ct 2006-11-25 implementation of NULL for FB 2.0
// number system: integer in decimal-system to hexword
char *inttohex(int *n, int *digits)
{
    if (!n || !digits)
	return NULL;
    else {
	char *sz_result = (char *) MALLOC(*digits + 1);
	char *pc = sz_result;

	sprintf(sz_result, "%*x", *digits, *n);

	while (*pc) {
	    if (*pc == ' ')
		*pc = '0';
	    pc++;
	}

	return sz_result;
    }
}

// pm 2005-10-03
// ct 2006-11-25 implementation of NULL for FB 2.0
// number system: hexword to integer in decimal-system
int *hextoint(char *sz)
{
    if (!sz)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	int res = 0;

	while (*sz) {
	    res *= 16;
	    if (isdigit(*sz)) {
		res += (*sz - '0');
	    } else if (isalpha(*sz)) {
		if (*sz <= 'Z')
		    res += ((*sz - 'A') + 10);
		else
		    res += ((*sz - 'a') + 10);
	    }
	    sz++;
	}

	*result = res;
	return result;
    }
}

// ct 2006-12-xx
// number system: roman to arabic
int *roman2arabic(char *rz)
{
    if (!rz)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	int len = strlen(rz);
	char ziffer;		/* enthaelt die aktuelle Ziffer der roemischen Zahl */
	int naechst = 0;	/* enthaelt 'ziffer' in arabischer Form             */
	int letzt = 0;		/* enthaelt die vorherige Ziffer in arabischer Form */
	int wert = 0;		/* enthaelt das Ergebnis = arabische Zahl           */

	int i;

    /*----------------------------------------------------
    verarbeite die roemische Zahl von links nach rechts:
    ----------------------------------------------------*/
	for (i = 0; i < len; i++) {

	    ziffer = toupper(rz[i]);

      /*-------------------------------------------
      Die aktuelle roemische Ziffer wird in ihren
      arabischen Gegenwert uebersetzt.
      -------------------------------------------*/
	    switch (ziffer) {

	    case 'M':
		naechst = 1000;
		break;

	    case 'D':
		naechst = 500;
		break;

	    case 'C':
		naechst = 100;
		break;

	    case 'L':
		naechst = 50;
		break;

	    case 'X':
		naechst = 10;
		break;

	    case 'V':
		naechst = 5;
		break;

	    case 'I':
		naechst = 1;
		break;

	    default:
		*result = -1;	/* ungueltige Ziffer => Abbruch */
		return result;

	    }			/* switch */

      /*--------------------------------------------------------
      Wenn die vorherige roemische Ziffer einen kleineren Wert
      hat als die akutelle, so wird der Wert der vorherigen
      subtrahiert, ansonsten wird er addiert.
      --------------------------------------------------------*/
	    if (letzt < naechst) {
		wert -= letzt;
	    } else {
		wert += letzt;
	    }

	    letzt = naechst;	/* eine Ziffer weiterruecken */

	}			/* for */

	wert += letzt;

	*result = wert;
	return result;
    }
}

// ct 2006-12-xx
// number system: arabic to roman
static int ArabicTab[13] =
    { 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000 };

static char *RomanTab[13] =
    { "I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M" };

char *arabic2roman(int *az)
{
    if (!az)
	return NULL;
    else {
	int i, a = *az;
	char *rz = (char *) MALLOC(250);

	*rz = '\0';
	if (a <= 200000) {
	    for (i = 12; i >= 0; i--) {
		while (a >= ArabicTab[i]) {
		    a -= ArabicTab[i];
		    strcat(rz, RomanTab[i]);
		}
	    }
	}
	return rz;
    }
}

/* *** geometrical system *** */

// pm 2005-10-03
// ct 2006-11-25 implementation of NULL for FB 2.0
// geometrical: angle (Alt-)degree to radian (radian measure)
double *degtorad(double *d)
{
    if (!d)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *d / 180.0 * M_PI;
	return result;
    }
}

// pm 2005-10-03
// ct 2006-11-25 implementation of NULL for FB 2.0
//  geometrical: radian (radian measure) to angle (Alt-)degree
double *radtodeg(double *d)
{
    if (!d)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *d / M_PI * 180.0;
	return result;
    }
}

/* *** length *** */

// ct 2006-12-xx
// length: inch to meter
double *in2m(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 2.54 / 100.0;
	return result;
    }
}

// ct 2006-12-xx
// length: meter to inch
double *m2in(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 2.54 * 100.0;
	return result;
    }
}

// ct 2006-12-xx
// length: feet to meter
double *ft2m(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 0.3048;
	return result;
    }
}

// ct 2006-12-xx
// length: meter to feet
double *m2ft(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 0.3048;
	return result;
    }
}

// ct 2006-12-xx
// length: yard to meter
double *yd2m(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 0.9144;
	return result;
    }
}

// ct 2006-12-xx
// length: meter to yard
double *m2yd(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 0.9144;
	return result;
    }
}

// ct 2006-12-xx
// length: mile to kilometer
double *mile2km(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 1.609344;
	return result;
    }
}

// ct 2006-12-xx
// length: kilometer to mile
double *km2mile(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 1.609344;
	return result;
    }
}

// ct 2006-12-xx
// length: fathom to meter
double *fm2m(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 1.829;
	return result;
    }
}

// ct 2006-12-xx
// length: meter to fathom
double *m2fm(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 1.829;
	return result;
    }
}

// ct 2008-02-12
// length: furlong to meter
double *fur2m(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 201.168;
	return result;
    }
}

// ct 2008-02-12
// length: meter to furlong
double *m2fur(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 201.168;
	return result;
    }
}

// ct 2008-02-12
// length: chain to meter
double *ch2m(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 20.1168;
	return result;
    }
}

// ct 2008-02-12
// length: meter to chain
double *m2ch(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 20.1168;
	return result;
    }
}

// ct 2008-02-12
// length: rod to meter
double *rd2m(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 5.0292;
	return result;
    }
}

// ct 2008-02-12
// length: meter to rod
double *m2rd(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 5.0292;
	return result;
    }
}

// ct 2008-02-12
// length: link to meter
double *li2m(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 0.201168;
	return result;
    }
}

// ct 2008-02-12
// length: meter to link
double *m2li(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 0.201168;
	return result;
    }
}

// ct 2008-02-12
// length: league to kilometer
double *lea2km(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 4.828032;
	return result;
    }
}

// ct 2008-02-12
// length: kilometer to league
double *km2lea(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 4.828032;
	return result;
    }
}

// ct 2006-12-xx
// nautic length: seamile to kilometer
double *sm2km(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 1.8520;
	return result;
    }
}

// ct 2006-12-xx
// nautic length: kilometer to seamile
double *km2sm(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 1.8520;
	return result;
    }
}

// ct 2008-02-12
// nautic length: shackle (GB) or shot(US) to meter
double *shot2m(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 27.432;
	return result;
    }
}

// ct 2008-02-12
// nautic length: meter to shackle (GB) or shot(US)
double *m2shot(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 27.432;
	return result;
    }
}

// ct 2008-02-12
// nautic length: cable to meter
double *cbl2m(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 185.3184;
	return result;
    }
}

// ct 2008-02-12
// nautic length: meter to cable
double *m2cbl(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 185.3184;
	return result;
    }
}

// ct 2008-02-12
// nautic length: sealeague to meter
double *nl2m(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 5559.552;
	return result;
    }
}

// ct 2008-02-12
// nautic length: meter to sealeague
double *m2nl(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 5559.552;
	return result;
    }
}

// ct 2008-02-12
// nautic length: admiraltymile to meter
double *nm2m(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 1853.184;
	return result;
    }
}

// ct 2008-02-12
// nautic length: meter to admiraltymile
double *m2nm(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 1853.184;
	return result;
    }
}

// ct 2006-12-xx
// typographic dimension: typoPoint to millimeter
double *p2mm(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 0.376065;
	return result;
    }
}

// ct 2006-12-xx
// typographic dimension: millimeter to typoPoint
double *mm2p(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 0.376065;
	return result;
    }
}

/* *** area *** */

// ct 2006-12-xx
// area: ar to squarmeter
double *ar2sqm(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 100.0;
	return result;
    }
}

// ct 2006-12-xx
// area: squarmeter to ar
double *sqm2ar(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 100.0;
	return result;
    }
}

// ct 2006-12-xx
// area: ha to squarmeter
double *ha2sqm(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 10000.0;
	return result;
    }
}

// ct 2006-12-xx
// area: squarmeter to ha
double *sqm2ha(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 10000.0;
	return result;
    }
}

// ct 2006-12-xx
// area: german Morgen to squarmeter
double *morgen2sqm(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 2500.0;
	return result;
    }
}

// ct 2006-12-xx
// area: squarmeter to german Morgen
double *sqm2morgen(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 2500.0;
	return result;
    }
}

// ct 2006-12-xx
// area: squarfeet to squarmeter
double *sqft2sqm(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 0.09290306;
	return result;
    }
}

// ct 2006-12-xx
// area: squarmeter to squarfeet
double *sqm2sqft(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 0.09290306;
	return result;
    }
}

// ct 2006-12-xx
// area: acre to squarmeter
double *ac2sqm(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 4046.856;
	return result;
    }
}

// ct 2006-12-xx
// area: squarmeter to acre
double *sqm2ac(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 4046.856;
	return result;
    }
}

// ct 2006-12-xx
// area: squaryard to squarmeter
double *sqyd2sqm(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 0.8361;
	return result;
    }
}

// ct 2006-12-xx
// area: squarmeter to squaryard
double *sqm2sqyd(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 0.8361;
	return result;
    }
}

/* *** volume *** */
// ct 2006-12-xx
// volume: barrel to litre
double *bbl2l(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 158.988;
	return result;
    }
}

// ct 2006-12-xx
// volume: litre to barrel
double *l2bbl(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 158.988;
	return result;
    }
}

// ct 2006-12-xx
// volume: GB fluid ounce to mililitre
double *gbfloz2ml(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 28.4131;
	return result;
    }
}

// ct 2006-12-xx
// volume: mililitre to GB fluid ounce
double *ml2gbfloz(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 28.4131;
	return result;
    }
}

// ct 2006-12-xx
// volume: US fluid ounce to mililitre
double *usfloz2ml(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 29.5735;
	return result;
    }
}

// ct 2006-12-xx
// volume: mililitre to US fluid ounce
double *ml2usfloz(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 29.5735;
	return result;
    }
}

// ct 2006-12-xx
// volume: GB pint to litre
double *gbpt2l(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 0.568262;
	return result;
    }
}

// ct 2006-12-xx
// volume: litre to GB pint
double *l2gbpt(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 0.568262;
	return result;
    }
}

// ct 2006-12-xx
// volume: US pint to litre
double *uspt2l(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 0.473176;
	return result;
    }
}

// ct 2006-12-xx
// volume: litre to US pint
double *l2uspt(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 0.473176;
	return result;
    }
}

// ct 2006-12-xx
// volume: GB quart to litre
double *gbqt2l(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 1.136521;
	return result;
    }
}

// ct 2006-12-xx
// volume: litre to GB quart
double *l2gbqt(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 1.136521;
	return result;
    }
}

// ct 2006-12-xx
// volume: US quart to litre
double *usqt2l(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 0.9463531;
	return result;
    }
}

// ct 2006-12-xx
// volume: litre to US quart
double *l2usqt(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 0.9463531;
	return result;
    }
}

// ct 2006-12-xx
// volume: GB gallon to litre
double *gbgal2l(double *x)
{
    if (!x)
   	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 4.546091;
	return result;
    }
}

// ct 2006-12-xx
// volume: litre to GB gallon
double *l2gbgal(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 4.546091;
	return result;
    }
}

// ct 2006-12-xx
// volume: US gallon to litre
double *usgal2l(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 3.785411;
	return result;
    }
}

// ct 2006-12-xx
// volume: litre to US gallon
double *l2usgal(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 3.785411;
	return result;
    }
}

// ct 2008-02-12
// volume: cubic inch to cubic meter
double *cuin2cum(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 0.000016387064;
	return result;
    }
}

// ct 2008-02-12
// volume: cubic meter to cubic inch
double *cum2cuin(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 0.000016387064;
	return result;
    }
}

// ct 2008-02-12
// volume: cubic foot to cubic meter
double *cuft2cum(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 0.028316846592;
	return result;
    }
}

// ct 2008-02-12
// volume: cubic meter to cubic foot
double *cum2cuft(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 0.028316846592;
	return result;
    }
}

// ct 2008-02-12
// volume: cubic yard to cubic meter
double *cuyd2cum(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 0.764554857984;
	return result;
    }
}

// ct 2008-02-12
// volume: cubic meter to cubic yard
double *cum2cuyd(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 0.764554857984;
	return result;
    }
}

// ct 2008-02-12
// volume: cup (8 ounces) to milliliter
double *cup2ml(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 236.56;
	return result;
    }
}

// ct 2008-02-12
// volume: milliliter to cup (8 ounces)
double *ml2cup(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 236.56;
	return result;
    }
}

// ct 2006-12-xx
// nautic volume: register ton to cubic meter
double *rt2cbm(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 2.83168;
	return result;
    }
}

// ct 2006-12-xx
// nautic volume: cubic meter to register ton
double *cbm2rt(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 2.83168;
	return result;
    }
}

/* *** weight *** */

// ct 2006-12-xx
// weight: carat to gramm
double *ct2g(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 0.2;
	return result;
    }
}

// ct 2006-12-xx
// weight: gramm to carat
double *g2ct(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 0.2;
	return result;
    }
}

// ct 2006-12-xx
// weight: ounce to gramm
double *oz2g(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 28.3495;
	return result;
    }
}

// ct 2006-12-xx
// weight: gramm to ounce
double *g2oz(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 28.3495;
	return result;
    }
}

// ct 2006-12-xx
// weight: troy ounce to gramm
double *oztr2g(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 31.1;
	return result;
    }
}

// ct 2006-12-xx
// weight: gramm to troy ounce
double *g2oztr(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 31.1;
	return result;
    }
}

// ct 2006-12-xx
// weight: pound to kilogramm
double *lb2kg(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 0.45359237;
	return result;
    }
}

// ct 2006-12-xx
// weight: kilogramm to pound
double *kg2lb(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 0.45359237;
	return result;
    }
}

// ct 2008-02-12
// weight: stone to gramm
double *st2g(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 6350.293180;
	return result;
    }
}

// ct 2008-02-12
// weight: gramm to stone
double *g2st(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 6350.293180;
	return result;
    }
}

// ct 2008-02-12
// weight: hundredweight (cental) to gramm
double *cwt2g(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 5359.237;
	return result;
    }
}

// ct 2008-02-12
// weight: gramm to hundredweight (cental)
double *g2cwt(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 5359.237;
	return result;
    }
}

/* *** temperature *** */

// ct 2006-12-xx
// temperature: celsius to fahrenheit
double *c2f(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 1.8 + 32.0;
	return result;
    }
}

// ct 2006-12-xx
// temperature: fahrenheit to celsius
double *f2c(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = (*x - 32.0) / 1.8;
	return result;
    }
}

/* *** technical *** */

// ct 2006-12-xx
// magnetic: Gauss to Tesla
double *g2t(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 10000.0;
	return result;
    }
}

// ct 2006-12-xx
// magnetic: Tesla to Gauss
double *t2g(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 10000.0;
	return result;
    }
}

// ct 2006-12-xx
// pressure: bar to torr
double *bar2torr(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 750.0638;
	return result;
    }
}

// ct 2006-12-xx
// pressure: torr to bar
double *torr2bar(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 750.0638;
	return result;
    }
}

// ct 2006-12-xx
// pressure: bar to pascal
double *bar2pa(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 100000.0;
	return result;
    }
}

// ct 2006-12-xx
// pressure: pascal to bar
double *pa2bar(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 100000.0;
	return result;
    }
}

// ct 2006-12-xx
// pressure: psi to pascal
double *psi2pa(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 6894.757;
	return result;
    }
}

// ct 2006-12-xx
// pressure: pascal to psi
double *pa2psi(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 6894.757;
	return result;
    }
}

// ct 2006-12-xx
// pressure: torr to pascal
double *torr2pa(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 133.322;
	return result;
    }
}

// ct 2006-12-xx
// pressure: pascal to torr
double *pa2torr(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 133.322;
	return result;
    }
}

// ct 2006-12-xx
// energie/work: calorie to joule
double *cal2j(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 4.1868;
	return result;
    }
}

// ct 2006-12-xx
// energie/work: joule to calorie
double *j2cal(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 4.1868;
	return result;
    }
}

// ct 2008-02-12
// energie/work: pounds-feet to Newton-meter
double *lbft2nm(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 1.3562811;
	return result;
    }
}

// ct 2008-02-12
// energie/work: Newton-meter to pounds-feet
double *nm2lbft(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 1.3562811;
	return result;
    }
}

// ct 2006-12-xx
// power: PS to kW
double *ps2kw(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 0.73549875;
	return result;
    }
}

// ct 2006-12-xx
// power: kW to PS
double *kw2ps(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 0.73549875;
	return result;
    }
}

// ct 2006-12-xx
// power: british hp to kW
double *bhp2kw(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 0.745699;
	return result;
    }
}

// ct 2006-12-xx
// power: kW to british hp
double *kw2bhp(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 0.745699;
	return result;
    }
}

// ct 2008-02-12
// consumption: Miles per USGallon to liter per 100km
// consumption: liter per 100km to Miles per USGallon
double *mpusgal2lp100km(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = 235.2145968 / *x;
	return result;
    }
}

// ct 2008-02-12
// consumption: Miles per GBGallon to liter per 100km
// consumption: liter per 100km to Miles per GBGallon
double *mpgbgal2lp100km(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = 282.4809363 / *x;
	return result;
    }
}

// ct 2008-02-12
// speed: miles per hour to kilometer per hour
double *mph2kmph(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 1.609344;
	return result;
    }
}

// ct 2008-02-12
// speed: kilometer per hour to miles per hour
double *kmph2mph(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 1.609344;
	return result;
    }
}

// ct 2008-02-12
// speed: food per seconds to meter per seconds
double *fps2mps(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 0.3048;
	return result;
    }
}

// ct 2008-02-12
// speed: meter per seconds to food per seconds
double *mps2fps(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 0.3048;
	return result;
    }
}

// ct 2008-02-12
// nautic speed: seamile per hour to kilometer per hour
double *smph2kmph(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x * 1.852;
	return result;        
    }
}

// ct 2008-02-12
// nautic speed: kilometer per hour to seamile per hour
double *kmph2smph(double *x)
{
    if (!x)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *x / 1.852;
	return result;
    }
}

                                                                                                                                                                                                        conv_functions.h                                                                                    0000744 0000000 0000764 00000011110 10756254732 013104  0                                                                                                    ustar   root                            adhoc                                                                                                                                                                                                                  /*****************************************************************************
 * FreeAdhocUDF - copyright (c) 2004 - 2008 adhoc dataservice GmbH
 * Christoph Theuring / Peter Mandrella / Georg Horn
 * <http://www.udf.adhoc-data.de> eMail <udf@adhoc-data.de>
 *
 * File Name:	conv_functions.h
 * Description: This header contains the prototype definitions
 *
 * This file is part of FreeAdhocUDF.
 * FreeAdhocUDF is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * FreeAdhocUDF is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with FreeAdhocUDF.  If not, see <http://www.gnu.org/licenses/>. 
*****************************************************************************/
 
double * in2m (double *);
double * ft2m (double *);
double * yd2m (double *);
double * mile2km (double *);
double * sm2km (double *);
double * fm2m (double *);
double * p2mm (double *);
double * m2in (double *);
double * m2ft (double *);
double * m2yd (double *);
double * km2mile (double *);
double * km2sm (double *);
double * m2fm (double *);
double * mm2p (double *);
double * ar2sqm (double *);
double * ha2sqm (double *);
double * morgen2sqm (double *);
double * sqft2sqm (double *);
double * ac2sqm (double *);
double * sqyd2sqm (double *);
double * sqm2ar (double *);
double * sqm2ha (double *);
double * sqm2morgen (double *);
double * sqm2sqft (double *);
double * sqm2ac (double *);
double * sqm2sqyd (double *);
double * bbl2l (double *);
double * gbfloz2ml (double *);
double * usfloz2ml (double *);
double * gbpt2l (double *);
double * uspt2l (double *);
double * gbqt2l (double *);
double * usqt2l (double *);
double * gbgal2l (double *);
double * usgal2l (double *);
double * rt2cbm (double *);
double * l2bbl (double *);
double * ml2gbfloz (double *);
double * ml2usfloz (double *);
double * l2gbpt (double *);
double * l2uspt (double *);
double * l2gbqt (double *);
double * l2usqt (double *);
double * l2gbgal (double *);
double * l2usgal (double *);
double * cbm2rt (double *);
double * ct2g (double *);
double * oz2g (double *);
double * oztr2g (double *);
double * lb2kg (double *);
double * g2ct (double *);
double * g2oz (double *);
double * g2oztr (double *);
double * kg2lb (double *);
double * g2t (double *);
double * bar2torr (double *);
double * bar2pa (double *);
double * psi2pa (double *);
double * torr2pa (double *);
double * cal2j (double *);
double * ps2kw (double *);
double * bhp2kw (double *);
double * t2g (double *);
double * torr2bar (double *);
double * pa2bar (double *);
double * pa2psi (double *);
double * pa2torr (double *);
double * j2cal (double *);
double * kw2ps (double *);
double * kw2bhp (double *);
double * c2f (double *);
double * f2c (double *);
int * roman2arabic(char *);
char * arabic2roman (int *);
int * convertfrom33 (char *);
char * convertto33 (int *);
int * convertfrombase (char *, int *, char *);
char * converttobase (int *, int *, char *);
char * inttohex (int *, int *);
int * hextoint (char *);
double *degtorad (double *);
double * radtodeg (double *);

double *mpusgal2lp100km(double *);
double *mpgbgal2lp100km(double *);
double *fur2m(double *);
double *m2fur(double *);
double *ch2m(double *);
double *m2ch(double *);
double *rd2m(double *);
double *m2rd(double *);
double *li2m(double *);
double *m2li(double *);
double *lea2km(double *);
double *km2lea(double *);
double *shot2m(double *);
double *m2shot(double *);
double *cbl2m(double *);
double *m2cbl(double *);
double *nl2m(double *);
double *m2nl(double *);
double *nm2m(double *);
double *m2nm(double *);
double *smph2kmph(double *);
double *kmph2smph(double *);
double *lbft2nm(double *);
double *nm2lbft(double *);
double *cuin2cum(double *);
double *cum2cuin(double *);
double *cuft2cum(double *);
double *cum2cuft(double *);
double *cuyd2cum(double *);
double *cum2cuyd(double *);
double *cup2ml(double *);
double *ml2cup(double *);
double *st2g(double *);
double *g2st(double *);
double *cwt2g(double *);
double *g2cwt(double *);
double *mph2kmph(double *);
double *kmph2mph(double *);
double *fps2mps(double *);
double *mps2fps(double *);

                                                                                                                                                                                                                                                                                                                                                                                                                                                        date_functions.c                                                                                    0000744 0000000 0000764 00000222716 10756540036 013062  0                                                                                                    ustar   root                            adhoc                                                                                                                                                                                                                  /*****************************************************************************
 * FreeAdhocUDF - copyright (c) 2004 - 2008 adhoc dataservice GmbH
 * Christoph Theuring ct / Peter Mandrella pm / Georg Horn gh
 * <http://www.udf.adhoc-data.de> eMail <udf@adhoc-data.de>
 * based on FreeUDFLibC - copyright (c) 1999 Gregory Deatz
 * some code from Robert Loipfinger rl copyright (c) 2000 ADITO Software GmbH
 *
 * File Name:	date_functions.c
 * Description: this module contains UDFs to generate and manipulate date/time
 * for exported functions list see date_functions.h
 *
 * This file is part of FreeAdhocUDF.
 * FreeAdhocUDF is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * FreeAdhocUDF is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with FreeAdhocUDF.  If not, see <http://www.gnu.org/licenses/>. 
*****************************************************************************/

#include <time.h>           
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <locale.h>


#include "global.h"
#include "math_functions.h"
#include "date_functions.h"
#include "string_functions.h"

static void i_week_of_year (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

// 2007-07-22 ct add more languages
// uk de fr it es pt nl no se dk fi hu ie ee is al va v1 c1 s1 s2 w1 b1 b2 n1 za fo lu w2
static 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ì","Venerdì","Sabato",
 "Domingo","Lunes","Martes","Miércoles","Jueves","Viernes","Sábado",
 "Segunda-feira", "Terça-feira", "Quarta-feira", "Quinta-feira", "Sexta-feira", "Sábado", "Domingo",
 "Zondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag",
 "Søndag", "Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag",
 "Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag",
 "Søndag", "Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag",
 "Sunnuntai", "Maanantai", "Tiistai", "Keskiviikko", "Torstai", "Perjantai", "Lauantai",
 "Vasárnap", "Hétfõ", "Kedd", "Szerda", "Csütörtök", "Péntek", "Szombat",
 "Dé Domhnaigh", "Dé Luain", "Dé Máirt", "Dé Céadaoin", "Déardaoin", "Dé hAoine", "Dé Sathairn",
 "Pühapäev", "Esmaspäev", "Teisipäev", "Kolmapäev", "Neljapäev", "Reede", "Laupäev",
 "Sunnudagur", "Mánudagur", "Þriðjudagur", "Miðvikudagur", "Fimmtudagur", "Föstudagur", "Laugardagur",
 "e diel", "e hënë", "e martë", "e mërkurë", "e enjte", "e premte", "e shtunë",
 "Dies Solis", "Dies Lunae", "Dies Martis", "Dies Mercurii", "Dies Jovis", "Dies Veneris", "Dies Saturni",
 "Dominica", "Feria Secunda", "Feria Tertia", "Feria Quarta", "Feria Quinta", "Feria Sexta", "Sabbatum",
 "Diumenge", "Dilluns", "Dimarts", "Dimecres", "Dijous", "Divendres", "Dissabte",
 "Sunday", "Monanday", "Tysday", "Wadensday", "Fuirsday", "Friday", "Seturday",
 "Di-Dòmhnaich", "Di-Luain", "Di-Màirt", "Di-Ciadain", "Di-Ardaoin", "Di-Haoine", "Di-Sàthairne",
 "Dydd Sul", "Dydd Llun", "Dydd Mawrth", "Dydd Mercher", "Dydd Iau", "Dydd Gwener", "Dydd Sadwrn",
 "Disul", "Dilun", "Dimeurzh", "Dimerc’her", "Diriaou", "Digwener", "Disadorn",
 "igandea", "astelehena", "asteartea", "asteazkena", "osteguna", "ostirala", "larunbata",
 "Sundag", "Mandag", "Tysdag", "Onsdag", "Forsdag", "Fredag", "Laurdag",
 "Sondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrydag", "Saterdag",
 "sunnudagur", "mánadagur", "týsdagur", "mikudagur", "hósdagur", "fríggjadagur", "leygardagur",
 "Sonndeg", "Méindeg", "Dënschdeg", "Mëttwoch", "Donneschdeg", "Freideg", "Samschdeg",
 "dimenge", "londi", "mårdi", "mierkidi", "djudi", "vénrdi", "semdi"
};

// 2007-07-22 ct
// 2008-02-05 ct corrects se and fi
// uk de fr it es pt nl no se dk fi hu ie ee is al va v1 c1 s1 s2 w1 b1 b2 n1 za fo lu w2
static char *DOWSHORT[] =
{
 "Sun","Mon","Tue","Wed","Thu","Fri","Sat",
 "So","Mo","Di","Mi","Do","Fr","Sa",
 "Dim","Lun","Mar","Mer","Jeu","Ven","Sam",
 "Dom","Lun","Mar","Mer","Gio","Ven","Sab",
 "Dom","Lun","Mar","Miér","Jue","Viér","Sáb",
 "Dom","2ª", "3ª", "4ª", "5ª", "6ª", "Sáb",
 "Zondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag",
 "Søndag", "Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag",
 "Sö", "Må", "Ti", "On", "To", "Fr", "Lö",
 "Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør",
 "Su", "Ma", "Ti", "Ke", "To", "Pe", "La",
 "Vasárnap", "Hétfõ", "Kedd", "Szerda", "Csütörtök", "Péntek", "Szombat",
 "Dé Domhnaigh", "Dé Luain", "Dé Máirt", "Dé Céadaoin", "Déardaoin", "Dé hAoine", "Dé Sathairn",
 "Pühapäev", "Esmaspäev", "Teisipäev", "Kolmapäev", "Neljapäev", "Reede", "Laupäev",
 "Sunnudagur", "Mánudagur", "Þriðjudagur", "Miðvikudagur", "Fimmtudagur", "Föstudagur", "Laugardagur",
 "e diel", "e hënë", "e martë", "e mërkurë", "e enjte", "e premte", "e shtunë",
 "Dies Solis", "Dies Lunae", "Dies Martis", "Dies Mercurii", "Dies Jovis", "Dies Veneris", "Dies Saturni",
 "Dominica", "Feria Secunda", "Feria Tertia", "Feria Quarta", "Feria Quinta", "Feria Sexta", "Sabbatum",
 "Diumenge", "Dilluns", "Dimarts", "Dimecres", "Dijous", "Divendres", "Dissabte",
 "Sunday", "Monanday", "Tysday", "Wadensday", "Fuirsday", "Friday", "Seturday",
 "Di-Dòmhnaich", "Di-Luain", "Di-Màirt", "Di-Ciadain", "Di-Ardaoin", "Di-Haoine", "Di-Sàthairne",
 "Dydd Sul", "Dydd Llun", "Dydd Mawrth", "Dydd Mercher", "Dydd Iau", "Dydd Gwener", "Dydd Sadwrn",
 "Disul", "Dilun", "Dimeurzh", "Dimerc’her", "Diriaou", "Digwener", "Disadorn",
 "igandea", "astelehena", "asteartea", "asteazkena", "osteguna", "ostirala", "larunbata",
 "Sundag", "Mandag", "Tysdag", "Onsdag", "Forsdag", "Fredag", "Laurdag",
 "Sondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrydag", "Saterdag",
 "sunnudagur", "mánadagur", "týsdagur", "mikudagur", "hósdagur", "fríggjadagur", "leygardagur",
 "Sonndeg", "Méindeg", "Dënschdeg", "Mëttwoch", "Donneschdeg", "Freideg", "Samschdeg",
 "dimenge", "londi", "mårdi", "mierkidi", "djudi", "vénrdi", "semdi"
};

// 2007-07-22 ct add more languages
// uk de fr it es pt nl no se dk fi hu ie ee is al va v1 c1 s1 s2 w1 b1 b2 n1 za fo lu w2
static 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",
 "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro",
 "Januari", "Februari", "Maart", "April", "Mei", "Juni", "Juli", "Augustus", "September", "October", "November", "December",
 "Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember",
 "Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December",
 "Januar", "Februar", "Marts", "April", "Maj", "Juni", "Juli", "August", "September", "Oktober", "November", "December",
 "Tammikuu", "Helmikuu", "Maaliskuu", "Huhtikuu", "Toukokuu", "Kesäkuu", "Heinäkuu", "Elokuu", "Syyskuu", "Lokakuu", "Marraskuu", "Joulukuu",
 "Január", "Február", "Március", "Április", "Május", "Június", "Július", "Augusztus", "Szeptember", "Október", "November", "December",
 "Enáir", "Feabhra", "An Márta", "An t-Aibreán", "An Bhealtaine", "An Meitheamh", "Iúil", "Lúnasa", "Meán Fómhair", "Deireadh Fómhair", "Samhain", "Nollaig",
 "Jaanuar", "Veebruar", "Märts", "Aprill", "Mai", "Juuni", "Juuli", "August", "September", "Oktoober", "November", "Detsember",
 "janúar", "febrúar", "mars", "apríl", "maí", "júní", "júlí", "ágúst", "september", "október", "nóvember", "desember",
 "janar", "shkurt", "mars", "prill", "maj", "qershor", "korrik", "gusht", "shtator", "tetor", "nëntor", "dhjetor",
 "Ianuarius", "Februarius", "Martius", "Aprilis", "Maius", "Iunius", "Iulius", "Augustus", "September", "October", "November", "December",
 "Ianuarius", "Februarius", "Martius", "Aprilis", "Maius", "Iunius", "Iulius", "Augustus", "September", "October", "November", "December",
 "Gener", "Febrer", "Març", "Abril", "Maig", "Juny", "Juliol", "Agost", "Setembre", "Octubre", "Novembre", "Desembre",
 "Januar", "Februar", "Mairch", "Apryle", "Mey", "Juin", "Julie", "Augist", "September", "October", "November", "Dizember",
 "an Faoilteach", "an Gearran", "an Márt", "an Giblean", "an Ceitean", "an t-Òg-mhios", "an t-luchar", "an Lúnasdal", "an t-Sultain", "an Dàmhair", "an t-Samhain", "an Dúbhlachd",
 "Ionawr", "Chwefror", "Mawrth", "Ebrill", "Mai", "Mehefin", "Gorffennaf", "Awst", "Medi", "Hydref", "Tachwedd", "Rhagfyr",
 "Genver", "C'hwevrer", "Meurzh", "Ebrel", "Mae", "Mezheven", "Gouere", "Eost", "Gwengolo", "Here", "Miz Du", "Kerzu",
 "urtarrila", "otsaila", "martxoa", "apirila", "maiatza", "ekaina", "uztaila", "abuztua", "iraila", "urria", "azaroa", "abendua",
 "januar", "februar", "mars", "april", "mai", "juni", "juli", "august", "september", "oktober", "november", "desember",
 "Januarie", "Februarie", "Maart", "April", "Mei", "Junie", "Julie", "Augustus", "September", "Oktober", "November", "Desember",
 "januar", "februar", "mars", "apríl", "mai", "juni", "juli", "august", "september", "oktober", "november", "desember",
 "Januar", "Februar", "Mäerz", "Abrëll", "Mee", "Juni", "Juli", "August", "September", "Oktouber", "November", "Dezember",
 "djanvî", "fevrî", "måss", "avri", "may", "djun", "djulete", "awousse", "setimbe", "octôbe", "nôvimbe", "decimbe"
};

// 2007-07-22 ct add more languages and delimiter
const char* LANG_INDEX = "uk-de-fr-it-es-pt-nl-no-se-dk-fi-hu-ie-ee-is-al-va-v1-c1-s1-s2-w1-b1-b2-n1-za-fo-lu-w2-";

// ct 2006-11-23 implementation of NULL for FB 2.0
// ct 2008-02-12 correction
ISC_QUAD * addyear (ISC_QUAD *date, int *years_to_add)
{
  if (!date || !years_to_add)
    return NULL;
  else
  {
    struct tm t;

    isc_decode_date(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 to 1st march
     */
    if (t.tm_mon == FEBRUARY && t.tm_mday > 28 && !isleap(t.tm_year+1900)) {
      t.tm_mday = 1;
      t.tm_mon = MARCH;
    }

    return (ISC_QUAD *) gen_ib_date(&t);
  }
}

// pm 2006-05-16 Korrektur
// ct 2006-11-23 implementation of NULL for FB 2.0
ISC_QUAD * addmonth (ISC_QUAD * date, int * months_to_add)
{
  if (!date || !months_to_add)
    return NULL;
  else
  {
    struct tm t;
    int tm_mon, tm_year;

    isc_decode_date (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);
  }
}

// intern: return days of month m in year y
static int intern_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 2005-10-16
// return days of month stored in t
static int daysoftsmonth(struct tm *t)
{
  int month = t->tm_mon + 1;
  int year = t->tm_year + 1900;
  return intern_daysofmonth(month, year);
}


// intern
// pm 2005-10-16
// pm 2006-02-24 Korrektur
// ct 2007-11-28
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)
    {
      if (seconds % 60 == 0 && t.tm_sec - seconds == 0) {
         t.tm_min += ((t.tm_sec - 59) / 60) - 1;
      }
      else {
         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 (ISC_QUAD *) gen_ib_date(&t);
}

// pm 2005-10-16
// ct 2006-11-23 implementation of NULL for FB 2.0
ISC_QUAD * addweek (ISC_QUAD *date, int *weeks)
{
  if (!date || !weeks)
    return NULL;
  else
    return addseconds(date, 7 * 24 * 60 * 60 * *weeks);
}

// ct 2006-11-23 implementation of NULL for FB 2.0
ISC_QUAD * addday (ISC_QUAD *date, int *days)
{
  if (!date || !days)
    return NULL;
  else
    return addseconds(date, 24 * 60 * 60 * *days);
}

// ct 2006-11-23 implementation of NULL for FB 2.0
ISC_QUAD * addhour (ISC_QUAD *date, int *hours)
{
  if (!date || !hours)
    return NULL;
  else
    return addseconds(date, 60 * 60 * *hours);
}

// ct 2006-11-23 implementation of NULL for FB 2.0
ISC_QUAD * addminute (ISC_QUAD *date, int *minutes)
{
  if (!date || !minutes)
    return NULL;
  else
    return addseconds(date, 60 * *minutes);
}

// ct 2006-11-23 implementation of NULL for FB 2.0
ISC_QUAD * addsecond (ISC_QUAD *date, int *seconds)
{
  if (!date || !seconds)
    return NULL;
  else
    return addseconds(date, *seconds);
}

// intern: calculate age in years between date1 and date2
static int intern_ageinyears(ISC_QUAD * date1, ISC_QUAD * date2)
{
    struct tm t1, t2;

    isc_decode_date(date2, &t2);
    isc_decode_date(date1, &t1);
    return t2.tm_year - t1.tm_year;
}

// return also negative ages
int *ageinyears(ISC_QUAD * date1, ISC_QUAD * date2)
{
    if (!date1 || !date2) {
	return NULL;
    } else {
	int *result = MALLOC(sizeof(int));
	*result = intern_ageinyears(date1, date2);
	return result;
    }
}

// return null instead of negativ ages
int *ageinyearsnull(ISC_QUAD * date1, ISC_QUAD * date2)
{
    if (!date1 || !date2) {
	return NULL;
    } else {
	int res = intern_ageinyears(date1, date2);
	if (res < 0) {
	    return NULL;
	} else {
	    int *result = MALLOC(sizeof(int));
	    *result = res;
	    return result;
	}
    }
}

// intern: calculate age in years with min and max threshold
static int intern_ageinyearsthreshold(ISC_QUAD * date1, ISC_QUAD * date2,
    int *min, int *usemin, int *max, int *usemax)
{
    int age = intern_ageinyears(date1, date2);
    if (*usemin == 1 && age < *min) {
	age = *min;
    } else if (*usemax == 1 && age > *max) {
	age = *max;
    }
    return age;
}

//  return age in years with min and max threshold
int *ageinyearsthreshold(ISC_QUAD * date1, ISC_QUAD * date2, int *min,
    int *usemin, int *max, int *usemax)
{
    if (!date1 || !date2 || !min || !usemin || !max || !usemax) {
	return NULL;
    } else {
	int *result = MALLOC(sizeof(int));
	*result = intern_ageinyearsthreshold(date1, date2, min, usemin,
	    max, usemax);
	return result;
    }
}

//  return null instead of negativ age
int *ageinyearsthresholdnull (ISC_QUAD *date1, ISC_QUAD *date2, int *min,
    int *usemin, int *max, int *usemax)
{
    if (!date1 || !date2 || !min || !usemin || !max || !usemax) {
	return NULL;
    } else {
	int res = intern_ageinyearsthreshold(date1, date2, min, usemin,
	    max, usemax);
	if (res < 0) {
	    return NULL;
	} else {
	    int *result = MALLOC(sizeof(int));
	    *result = res;
	    return result;
	}
    }
}

// intern: calculate age in months
static int intern_ageinmonths(ISC_QUAD * date1, ISC_QUAD * date2)
{
    struct tm t1, t2;

    isc_decode_date(date2, &t2);
    isc_decode_date(date1, &t1);

    return ((t2.tm_year - t1.tm_year) * 12) + t2.tm_mon - t1.tm_mon;
}

//  return age in months
int *ageinmonths(ISC_QUAD * date1, ISC_QUAD * date2)
{
    if (!date1 || !date2) {
	return NULL;
    } else {
	int *result = MALLOC(sizeof(int));
	*result = intern_ageinmonths(date1, date2);
	return result;
    }
}

//  return null instead of negativ ages
int *ageinmonthsnull(ISC_QUAD * date1, ISC_QUAD * date2)
{
    if (!date1 || !date2) {
	return NULL;
    } else {
	int res = intern_ageinmonths(date1, date2);
	if (res < 0) {
	    return NULL;
	} else {
	    int *result = MALLOC(sizeof(int));
	    *result = res;
	    return result;
	}
    }
}

//  return age in months with threshold
int *ageinmonthsthreshold(ISC_QUAD * date1, ISC_QUAD * date2, int *min,
    int *usemin, int *max, int *usemax)
{
    if (!date1 || !date2 || !min || !usemin || !max || !usemax) {
	return NULL;
    } else {
	int *result = MALLOC(sizeof(int));
	int age = intern_ageinmonths(date1, date2);
	if (*usemin == 1 && age < *min) {
	    age = *min;
	} else if (*usemax == 1 && age > *max) {
	    age = *max;
	}
	*result = age;
	return result;
    }
}

//  return null instead of negativ age
int *ageinmonthsthresholdnull(ISC_QUAD * date1, ISC_QUAD * date2, int *min,
    int *usemin, int *max, int *usemax)
{
    if (!date1 || !date2 || !min || !usemin || !max || !usemax) {
	return NULL;
    } else {
	int age = intern_ageinmonths(date1, date2);
	if (*usemin == 1 && age < *min) {
	    age = *min;
	} else if (*usemax == 1 && age > *max) {
	    age = *max;
	}
	if (age < 0) {
	    return NULL;
	} else {
	    int *result = MALLOC(sizeof(int));
	    *result = age;
	    return result;
	}
    }
}

// rl 2000 written as dtime
// Returns days since 31.12.1899 - (c) 2000 Robert Loipfinger
static int intern_dtime(ISC_QUAD * date)
{
    struct tm t;
    int day = 0, i, year;

    isc_decode_date(date, &t);

    for (i = 0; i < t.tm_year; i++) {
	day += isleap(i + 1900) ? 366 : 365;
    }

    // um 1 versetzt, wg. daysofmonth-Logik (Monat 1-basiert)
    for (i = 1; i <= t.tm_mon; i++) {
	year = t.tm_year + 1900;
	day += intern_daysofmonth(i, year);
    }

    day += t.tm_mday - 1;
    return day;
}

//  return days since 31.12.1899
int *dtime(ISC_QUAD * date)
{
    if (!date) {
	return NULL;
    } else {
	int *result = MALLOC(sizeof(int));
	*result = intern_dtime(date);
	return result;
    }
}

// gh 2008-02-14
// return number of occurences of a certain weekday between date1 and date2
int *countweekdays(ISC_QUAD * date1, ISC_QUAD * date2, int *weekday)
{
    if (!date1 || !date2 || !weekday) {
	return NULL;
    } else {
        int *result = MALLOC(sizeof(int));
	struct tm t1, t2;

	isc_decode_date(date1, &t1);
	isc_decode_date(date2, &t2);

	/* number of occurences is number of full weeks */
	*result = (intern_dtime(date2) - intern_dtime(date1)) / 7;

        /* if a weekday is between t1 and t2, increase number by 1
          weekday is: 1 = Monday, ..., 7 = Sunday
          tm_wday is: 0 = Sunday, ..., 6 = Saturday */
        if (t1.tm_wday == 0) {
            t1.tm_wday = 7;
        }
        if (t2.tm_wday == 0) {
            t2.tm_wday = 7;
        }
        if (((t1.tm_wday != t2.tm_wday) && (*weekday <= t2.tm_wday)) || ((t1.tm_wday == t2.tm_wday) && (t1.tm_wday == *weekday))) {
            (*result)++;
        }

	return result;
    }
}

// intern: calculate age in weeks
// sunday = 1st day of week
// If the two dates are in the same week, the return value is 0.
static int intern_ageinweeks(ISC_QUAD * date1, ISC_QUAD * date2)
{
    struct tm t1, t2;
    int days1, days2;

    isc_decode_date(date1, &t1);
    isc_decode_date(date2, &t2);
    days1 = intern_dtime(date1) - t1.tm_wday;
    days2 = intern_dtime(date2) - t2.tm_wday;
//    days1 = intern_dtime(date1);
//    days2 = intern_dtime(date2);

    return (days2 - days1) / 7;
}

// ct 2008-02-18
// intern: calculate age in weeks ISO standard
// monday = 1st day of week
// If the two dates are in the same week, the return value is 0.
static int intern_ageinweeksiso(ISC_QUAD * date1, ISC_QUAD * date2)
{
    struct tm t1, t2;
    int days1, days2;

    isc_decode_date(date1, &t1);
    isc_decode_date(date2, &t2);
    days1 = intern_dtime(date1);
    days2 = intern_dtime(date2);

    return (days2 - days1) / 7;
}

//  return age in weeks
int *ageinweeks(ISC_QUAD * date1, ISC_QUAD * date2)
{
    if (!date1 || !date2) {
	return NULL;
    } else {
	int *result = MALLOC(sizeof(int));
	*result = intern_ageinweeks(date1, date2);
	return result;
    }
}

// ct 2008-02-18
//  return age in weeks ISO standard
int *ageinweeksiso(ISC_QUAD * date1, ISC_QUAD * date2)
{
    if (!date1 || !date2) {
	return NULL;
    } else {
	int *result = MALLOC(sizeof(int));
	*result = intern_ageinweeksiso(date1, date2);
	return result;
    }
}

//  return return age in weeks and null instead of negativ age
int *ageinweeksnull(ISC_QUAD * date1, ISC_QUAD * date2)
{
    if (!date1 || !date2) {
	return NULL;
    } else {
	int res = intern_ageinweeks(date1, date2);
	if (res < 0) {
	    return NULL;
	} else {
	    int *result = MALLOC(sizeof(int));
            *result = res;
	    return result;
	}
    }
}

// ct 2008-02-18
// return age in weeks ISO standard and null instead of negativ age
int *ageinweeksnulliso(ISC_QUAD * date1, ISC_QUAD * date2)
{
    if (!date1 || !date2) {
	return NULL;
    } else {
	int res = intern_ageinweeksiso(date1, date2);
	if (res < 0) {
	    return NULL;
	} else {
	    int *result = MALLOC(sizeof(int));
            *result = res;
	    return result;
	}
    }
}

//  return age in weeks with threshold
int *ageinweeksthreshold(ISC_QUAD * date1, ISC_QUAD * date2,
    int *min, int *usemin, int *max, int *usemax)
{
    if (!date1 || !date2 || !min || !usemin || !max || !usemax) {
	return NULL;
    } else {
	int *result = MALLOC(sizeof(int));
	int age = intern_ageinweeks(date1, date2);
	if (*usemin == 1 && age < *min) {
	    age = *min;
	} else if (*usemax == 1 && age > *max) {
	    age = *max;
	}
	*result = age;
	return result;
    }
}

// ct 2008-02-18
//  return age in weeks ISO standard with threshold
int *ageinweeksthresholdiso(ISC_QUAD * date1, ISC_QUAD * date2,
    int *min, int *usemin, int *max, int *usemax)
{
    if (!date1 || !date2 || !min || !usemin || !max || !usemax) {
	return NULL;
    } else {
	int *result = MALLOC(sizeof(int));
	int age = intern_ageinweeksiso(date1, date2);
	if (*usemin == 1 && age < *min) {
	    age = *min;
	} else if (*usemax == 1 && age > *max) {
	    age = *max;
	}
	*result = age;
	return result;
    }
}

//  returns age in weeks with threshold null instead of negativ ages
int *ageinweeksthresholdnull(ISC_QUAD * date1, ISC_QUAD * date2,
    int *min, int *usemin, int *max, int *usemax)
{
    if (!date1 || !date2 || !min || !usemin || !max || !usemax) {
	return NULL;
    } else {
	int age = intern_ageinweeks(date1, date2);
	if (*usemin == 1 && age < *min) {
	    age = *min;
	} else if (*usemax == 1 && age > *max) {
	    age = *max;
	}
	if (age < 0) {
	    return NULL;
	} else {
	    int *result = MALLOC(sizeof(int));
	    *result = age;
	    return result;
	}
    }
}

// ct 2008-02-18
//  returns age in weeks with threshold ISO standard null instead of negativ ages
int *ageinweeksthresholdnulliso(ISC_QUAD * date1, ISC_QUAD * date2,
    int *min, int *usemin, int *max, int *usemax)
{
    if (!date1 || !date2 || !min || !usemin || !max || !usemax) {
	return NULL;
    } else {
	int age = intern_ageinweeksiso(date1, date2);
	if (*usemin == 1 && age < *min) {
	    age = *min;
	} else if (*usemax == 1 && age > *max) {
	    age = *max;
	}
	if (age < 0) {
	    return NULL;
	} else {
	    int *result = MALLOC(sizeof(int));
	    *result = age;
	    return result;
	}
    }
}

//  return age in days
int *ageindays(ISC_QUAD * date1, ISC_QUAD * date2)
{
    if (!date1 || !date2) {
	return NULL;
    } else {
	int *result = MALLOC(sizeof(int));
	*result = intern_dtime(date2) - intern_dtime(date1);
	return result;
    }
}

//  return null instead of negativ age
int *ageindaysnull(ISC_QUAD * date1, ISC_QUAD * date2)
{
    if (!date1 || !date2) {
	return NULL;
    } else {
	int res = intern_dtime(date2) - intern_dtime(date1);
	if (res < 0) {
	    return NULL;
	} else {
	    int *result = MALLOC(sizeof(int));
	    *result = res;
	    return result;
	}
    }
}

//  return age in days with threshold
int *ageindaysthreshold(ISC_QUAD * date1, ISC_QUAD * date2,
    int *min, int *usemin, int *max, int *usemax)
{
    if (!date1 || !date2 || !min || !usemin || !max || !usemax) {
	return NULL;
    } else {
	int *result = MALLOC(sizeof(int));
	int age = intern_dtime(date2) - intern_dtime(date1);
	if (*usemin == 1 && age < *min) {
	    age = *min;
	} else if (*usemax == 1 && age > *max) {
	    age = *max;
	}
	*result = age;
	return result;
    }
}

//  return null instead of negativ age
int *ageindaysthresholdnull(ISC_QUAD * date1, ISC_QUAD * date2,
    int *min, int *usemin, int *max, int *usemax)
{
    if (!date1 || !date2) {
	return NULL;
    } else {
	int age = intern_dtime(date2) - intern_dtime(date1);
	if (*usemin == 1 && age < *min) {
	    age = *min;
	} else if (*usemax == 1 && age > *max) {
	    age = *max;
	}
	if (age < 0) {
	    return NULL;
	} else {
	    int *result = MALLOC(sizeof(int));
	    *result = age;
	    return result;
	}
    }
}

// intern: calculate difference between date1 and date 2
static double intern_zeitdifferenz(ISC_QUAD * date1, ISC_QUAD * date2, char *sz)
{
    struct tm d1, d2;
    int aid;
    int secdiff;
    double res = 0;

    isc_decode_date(date1, &d1);
    isc_decode_date(date2, &d2);

    aid = intern_dtime(date1) - intern_dtime(date2);
    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':
	    res = aid + (double) secdiff / 86400.0;
	    break;
	case 'h':
	    res = aid * 24 + (double) secdiff / 3600.0;
	    break;
	case 'm':
	    res = (double) aid *1440.0 + (double) secdiff / 60.0;
	    break;
	case 's':
	    res = (double) aid *86400.0 + secdiff;
	    break;
	}
    }

    return res;
}

//  return difference between date1 and date 2
double *zeitdifferenz(ISC_QUAD * date1, ISC_QUAD * date2, char *sz)
{
    if (!date1 || !date2 || !sz) {
	return NULL;
    } else {
	double *result = MALLOC(sizeof(double));
	*result = intern_zeitdifferenz(date1, date2, sz);
	return result;
    }
}


//  return age in hours
int *ageinhours(ISC_QUAD * date1, ISC_QUAD * date2)
{
    if (!date1 || !date2) {
	return NULL;
    } else {
	int *result = MALLOC(sizeof(int));
	*result = (int) intern_zeitdifferenz(date2, date1, "h");
	return result;
    }
}

//  return null instead of negativ age
int *ageinhoursnull(ISC_QUAD * date1, ISC_QUAD * date2)
{
    if (!date1 || !date2) {
	return NULL;
    } else {
	int res = (int) intern_zeitdifferenz(date2, date1, "h");
	if (res < 0) {
	    return NULL;
	} else {
	    int *result = MALLOC(sizeof(int));
	    *result = res;
	    return result;
	}
    }
}

//  return age in hours with threshold
int *ageinhoursthreshold(ISC_QUAD * date1, ISC_QUAD * date2,
    int *min, int *usemin, int *max, int *usemax)
{
    if (!date1 || !date2 || !min || !usemin || !max || !usemax) {
	return NULL;
    } else {
	int *result = MALLOC(sizeof(int));
	int age = (int) intern_zeitdifferenz(date2, date1, "h");
	if (*usemin == 1 && age < *min) {
	    age = *min;
	} else if (*usemax == 1 && age > *max) {
	    age = *max;
	}
	*result = age;
	return result;
    }
}

//  return null instead of negativ age
int *ageinhoursthresholdnull(ISC_QUAD * date1, ISC_QUAD * date2,
    int *min, int *usemin, int *max, int *usemax)
{
    if (!date1 || !date2) {
	return NULL;
    } else {
	int age = (int) intern_zeitdifferenz(date2, date1, "h");
	if (*usemin == 1 && age < *min) {
	    age = *min;

	} else if (*usemax == 1 && age > *max) {
	    age = *max;
	}
	if (age < 0) {
	    return NULL;
	} else {
	    int *result = MALLOC(sizeof(int));
	    *result = age;
	    return result;
	}
    }
}

//  return age in minutes
int *ageinminutes(ISC_QUAD * date1, ISC_QUAD * date2)
{
    if (!date1 || !date2) {
	return NULL;
    } else {
	int *result = MALLOC(sizeof(int));
	*result = (int) intern_zeitdifferenz(date2, date1, "m");
	return result;
    }
}

//  return null instead of negativ age
int *ageinminutesnull(ISC_QUAD * date1, ISC_QUAD * date2)
{
    if (!date1 || !date2) {
	return NULL;
    } else {
	int res = (int) intern_zeitdifferenz(date2, date1, "m");
	if (res < 0) {
	    return NULL;
	} else {
	    int *result = MALLOC(sizeof(int));
	    *result = res;
	    return result;
	}
    }
}

//  return age in minutes with threshold
int *ageinminutesthreshold(ISC_QUAD * date1, ISC_QUAD * date2,
    int *min, int *usemin, int *max, int *usemax)
{
    if (!date1 || !date2 || !min || !usemin || !max || !usemax) {
	return NULL;
    } else {
	int *result = MALLOC(sizeof(int));
	int age = (int) intern_zeitdifferenz(date2, date1, "m");
	if (*usemin == 1 && age < *min) {
	    age = *min;
	} else if (*usemax == 1 && age > *max) {
	    age = *max;
	}
	*result = age;
	return result;
    }
}

//  return null instead of negativ age
int *ageinminutesthresholdnull(ISC_QUAD * date1, ISC_QUAD * date2,
    int *min, int *usemin, int *max, int *usemax)
{
    if (!date1 || !date2) {
	return NULL;
    } else {
	int age = (int) intern_zeitdifferenz(date2, date1, "m");
	if (*usemin == 1 && age < *min) {
	    age = *min;
	} else if (*usemax == 1 && age > *max) {
	    age = *max;
	}
	if (age < 0) {
	    return NULL;
	} else {
	    int *result = MALLOC(sizeof(int));
	    *result = age;
	    return result;
	}
    }
}

//  return age in seconds
int *ageinseconds(ISC_QUAD * date1, ISC_QUAD * date2)
{
    if (!date1 || !date2) {
	return NULL;
    } else {
	int *result = MALLOC(sizeof(int));
	*result = (int) intern_zeitdifferenz(date2, date1, "s");
	return result;
    }
}

//  return null instead of negativ age
int *ageinsecondsnull(ISC_QUAD * date1, ISC_QUAD * date2)
{
    if (!date1 || !date2) {
	return NULL;
    } else {
	int res = (int) intern_zeitdifferenz(date2, date1, "s");
	if (res < 0) {
	    return NULL;
	} else {
	    int *result = MALLOC(sizeof(int));
	    *result = res;
	    return result;
	}
    }
}

//  return age in seconds with threshold
int *ageinsecondsthreshold(ISC_QUAD * date1, ISC_QUAD * date2,
    int *min, int *usemin, int *max, int *usemax)
{
    if (!date1 || !date2 || !min || !usemin || !max || !usemax) {
	return NULL;
    } else {
	int *result = MALLOC(sizeof(int));
	int age = (int) intern_zeitdifferenz(date2, date1, "s");
	if (*usemin == 1 && age < *min) {
	    age = *min;
	} else if (*usemax == 1 && age > *max) {
	    age = *max;
	}
	*result = age;
	return result;
    }
}

//  return null instead of negativ age
int *ageinsecondsthresholdnull(ISC_QUAD * date1, ISC_QUAD * date2,
    int *min, int *usemin, int *max, int *usemax)
{
    if (!date1 || !date2 || !min || !usemin || !max || !usemax) {
	return NULL;
    } else {
	int age = (int) intern_zeitdifferenz(date2, date1, "s");
	if (*usemin == 1 && age < *min) {
	    age = *min;
	} else if (*usemax == 1 && age > *max) {
	    age = *max;
	}
	if (age < 0) {
	    return NULL;
	} else {
	    int *result = MALLOC(sizeof(int));
	    *result = age;
	    return result;
	}
    }
}

// intern
// pm 2004-08-21
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) / 3;
    }
}

// pm 2004-08-21
// ct 2006-11-23 implementation of NULL for FB 2.0
char *cdowlonglang(ISC_QUAD * ib_date, char *language)
{
    if (!ib_date || !language)
	return NULL;
    else {
	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 2004-08-21
// ct 2006-11-23 implementation of NULL for FB 2.0
char *cdowlong(ISC_QUAD * ib_date)
{
    if (!ib_date)
	return NULL;
    else
	return cdowlonglang(ib_date, "us");
}

// pm 2004-08-21
// ct 2006-11-23 implementation of NULL for FB 2.0
// ct 2007-07-22 own table for shortnames
// old code takes only first 3 leters from longname
char *cdowshortlang(ISC_QUAD * ib_date, char *language)
{
    if (!ib_date || !language)
	return NULL;
    else {
	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, DOWSHORT[lang * 7 + t.tm_wday]);

	result[4] = '\0';
	return result;
    }
}

// pm 2004-08-21
// ct 2006-11-23 implementation of NULL for FB 2.0
char *cdowshort(ISC_QUAD * ib_date)
{
    if (!ib_date)
	return NULL;
    else
	return cdowshortlang(ib_date, "us");
}

// pm 2004-08-21 optimized
// ct 2006-11-23 implementation of NULL for FB 2.0
char *cmonthlonglang(ISC_QUAD * ib_date, char *language)
{
    if (!ib_date || !language)
	return NULL;
    else {
	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 2004-08-21 optimized
// ct 2006-11-23 implementation of NULL for FB 2.0
char *cmonthlong(ISC_QUAD * ib_date)
{
    if (!ib_date)
	return NULL;
    else
	return cmonthlonglang(ib_date, "us");
}

// pm 2004-08-21 optimized
// ct 2006-11-23 implementation of NULL for FB 2.0
char *cmonthshortlang(ISC_QUAD * ib_date, char *language)
{
    if (!ib_date || !language)
	return NULL;
    else {
	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 2004-08-21 optimized
// ct 2006-11-23 implementation of NULL for FB 2.0
char *cmonthshort(ISC_QUAD * ib_date)
{
    if (!ib_date)
	return NULL;
    else
	return cmonthshortlang(ib_date, "us");
}

// ct 2006-11-23 implementation of NULL for FB 2.0
int *dayofmonth(ISC_QUAD * date)
{
    if (!date)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	struct tm t;
	isc_decode_date(date, &t);

	*result = t.tm_mday;
	return result;
    }
}

// intern
static int intern_dayofweek(ISC_QUAD * date)
{
	struct tm t;
	isc_decode_date(date, &t);
	return t.tm_wday + 1;
}

// ct 2006-11-23 implementation of NULL for FB 2.0
int *dayofweek(ISC_QUAD * date)
{
    if (!date)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	*result = intern_dayofweek(date);
	return result;
    }
}

// ct 2007-01-27
int *r_weekday(ISC_QUAD * date)
{
    if (!date) {
	return NULL;
    }
    else
    {
	int *result = MALLOC(sizeof(int));
	*result = intern_dayofweek(date) - 1;
	return result;
    }
}

// ct 2007-01-27
int *r_dow(ISC_QUAD * date)
{
    if (!date) {
	return NULL;
    }
    else
    {
	int *result = MALLOC(sizeof(int));
	*result = intern_dayofweek(date) - 1 == 0 ? 7 : intern_dayofweek(date) - 1;
	return result;
    }
}

// intern
static int intern_dayofyear(ISC_QUAD * date)
{
	struct tm t;
	isc_decode_date(date, &t);
	return t.tm_yday + 1;
}

// ct 2006-11-23 implementation of NULL for FB 2.0
int *dayofyear(ISC_QUAD * date)
{
    if (!date) {
	return NULL;
    }
    else
    {
	int *result = MALLOC(sizeof(int));
	*result = intern_dayofyear(date);
	return result;
    }
}

// ct 2007-01-27
int *r_yearday(ISC_QUAD * date)
{
    if (!date) {
	return NULL;
    }
    else
    {
	int *result = MALLOC(sizeof(int));
	*result = intern_dayofyear(date) - 1;
	return result;
    }
}

// rl 2001
// pm 2004-08-21
// ct 2006-11-23 implementation of NULL for FB 2.0
char *gformatd(char *format, ISC_QUAD * ib_date)
{
    if (!format || !ib_date)
	return NULL;
    else {
	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;
    }
}

// ct 2006-11-23 implementation of NULL for FB 2.0
int *isleapyear(ISC_QUAD * date)
{
    if (!date)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	struct tm t;
	isc_decode_date(date, &t);

	*result = isleap(t.tm_year + 1900);
	return result;
    }
}

// ct 2006-11-23 implementation of NULL for FB 2.0
int *r_isleapyear(int * year)
{
    if (!year)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	*result = isleap(* year);
	return result;
    }
}

// ct 2006-11-23 implementation of NULL for FB 2.0
ISC_QUAD *maxdate(ISC_QUAD * ib_date_1, ISC_QUAD * ib_date_2)
{
    if (!ib_date_1 || !ib_date_2)
	return NULL;
    else {
	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;
    }
}

// ct 2006-11-23 implementation of NULL for FB 2.0
ISC_QUAD *mindate(ISC_QUAD * ib_date_1, ISC_QUAD * ib_date_2)
{
    if (!ib_date_1 || !ib_date_2)
	return NULL;
    else {
	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;
    }
}

// ct 2006-11-23 implementation of NULL for FB 2.0
int *month(ISC_QUAD * date)
{
    if (!date)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	struct tm t;
	isc_decode_date(date, &t);

	*result = t.tm_mon + 1;
	return result;
    }
}

// pm 2004-08-21 bug fixed
// ct 2006-11-23 implementation of NULL for FB 2.0
int *quarter(ISC_QUAD * date)
{
    if (!date)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	struct tm t;
	isc_decode_date(date, &t);

	*result = t.tm_mon / 3 + 1;
	return result;
    }
}

// ct 2006-11-23 implementation of NULL for FB 2.0
ISC_QUAD *stripdate(ISC_QUAD * ib_date)
{
    if (!ib_date)
	return NULL;
    else {
	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 (ISC_QUAD *) gen_ib_date(&t);
    }
}

// ct 2006-11-23 implementation of NULL for FB 2.0
ISC_QUAD *striptime(ISC_QUAD * ib_date)
{
    if (!ib_date)
	return NULL;
    else {
	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 (ISC_QUAD *) gen_ib_date(&t);
    }
}

// pm 2005-10-16 returntyp TIME instead of TIMESTAMP
// ct 2006-11-23 implementation of NULL for FB 2.0
ISC_TIME *strtotime(char *sz)
{
    if (!sz)
	return NULL;
    else {
	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;
    }
}

// ct 2006-11-23 implementation of NULL for FB 2.0
int *week(ISC_QUAD * date)
{
    if (!date)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	struct tm t;
	int dow_ybeg, /*yr, */ wk;

	isc_decode_date(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)
	    *result = wk - 1;
	else
	    *result = wk;
	return result;
    }
}

// ct 2006-11-23 implementation of NULL for FB 2.0
int *weekofyear(ISC_QUAD * ib_date)
{
    if (!ib_date)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	int week, year;

	i_week_of_year(ib_date, &week, &year);
	*result = week;
	return result;
    }
}

// ct 2006-11-23 implementation of NULL for FB 2.0
// ct 2007-01-18 single figures with leading 0
char *woy(ISC_QUAD * ib_date)
{
    if (!ib_date)
	return NULL;
    else {
	char *result = (char *) MALLOC(LOC_STRING_SIZE + 1);
	int week, year;

	i_week_of_year(ib_date, &week, &year);

	sprintf(result, "%d%02d", year, week);
	return result;
    }
}

static int intern_kalenderwoche(ISC_QUAD * date);

// gh 2008-02-12
// week of year with year according to ISO
char *woyiso(ISC_QUAD * date)
{
    if (!date)
	return NULL;
    else {
	char *result = MALLOC(7);
	struct tm t;
        int kw = intern_kalenderwoche(date);

	isc_decode_date(date, &t);

        if (kw > 51 && t.tm_mon == 0) {
            t.tm_year -= 1;
        }
	sprintf(result, "%04d%02d", t.tm_year + 1900, kw);
	return result;
    }
}

// ct 2006-11-23 implementation of NULL for FB 2.0
int *year(ISC_QUAD * date)
{
    if (!date)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	struct tm t;
	isc_decode_date(date, &t);

	*result = t.tm_year + 1900;
	return result;
    }
}

// ct 2006-11-23 implementation of NULL for FB 2.0
int *yearofyear(ISC_QUAD * date)
{
    if (!date)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	int week, year;

	i_week_of_year(date, &week, &year);
	*result = year;
	return result;
    }
}

// ct 2006-11-23 implementation of NULL for FB 2.0
int *hour(ISC_QUAD * date)
{
    if (!date)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	struct tm t;
	isc_decode_date(date, &t);
	*result = t.tm_hour;
	return result;
    }
}

// ct 2006-11-23 implementation of NULL for FB 2.0
int *minute(ISC_QUAD * date)
{
    if (!date)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	struct tm t;
	isc_decode_date(date, &t);
	*result = t.tm_min;
	return result;
    }
}

// ct 2006-11-23 implementation of NULL for FB 2.0
int *second(ISC_QUAD * date)
{
    if (!date)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	struct tm t;
	isc_decode_date(date, &t);
	*result = t.tm_sec;
	return result;
    }
}

// ct 2007-02-01
int *millisecond(ISC_QUAD * date)
{
    if (!date)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	div_t x;
	x = div(date->gds_quad_low, ISC_TIME_SECONDS_PRECISION);
	*result = x.rem;
	return result;
    }
}

//  return days of month m in year y
int *daysofmonth(int *m, int *y)
{
    if (!m || !y) {
	return NULL;
    } else {
	int *result = MALLOC(sizeof(int));
	*result = intern_daysofmonth(*m, *y);
	return result;
    }
}

//  same as daysofmonth() but with swapped paramaters
int *lastday(int *y, int *m)
{
    return daysofmonth(m, y);
}


// generate interbase date from struct tm
ISC_QUAD * gen_ib_date(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(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 2005-10-03
// ct 2006-11-23 implementation of NULL for FB 2.0
int *equaldate(ISC_QUAD * date1, ISC_QUAD * date2)
{
    if (!date1 || !date2)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	struct tm d1, d2;

	isc_decode_date(date1, &d1);
	isc_decode_date(date2, &d2);

	*result = (d1.tm_year == d2.tm_year && d1.tm_mon == d2.tm_mon
		   && d1.tm_mday == d2.tm_mday);
	return result;
    }
}

// pm 2005-10-03
// ct 2006-11-23 implementation of NULL for FB 2.0
int *equaldatetime(ISC_QUAD * date1, ISC_QUAD * date2)
{
    if (!date1 || !date2)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	struct tm d1, d2;

	isc_decode_date(date1, &d1);
	isc_decode_date(date2, &d2);

	*result = (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);
	return result;
    }
}

// pm 2005-10-03
// ct 2006-11-23 implementation of NULL for FB 2.0
ISC_QUAD *osterdatum(int *year)
{
    if (!year)
	return NULL;
    else {
	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 2005-10-16
// ct 2006-11-23 implementation of NULL for FB 2.0
int *yearsbetween(ISC_QUAD * d1, ISC_QUAD * d2)
{
    if (!d1 || !d2) {
	return NULL;
    } else {
	int *result = ageinyears(d1, d2);
	*result = abs(*result);
	return result;
    }
}

// ct 2006-11-23 implementation of NULL for FB 2.0
int *monthsbetween(ISC_QUAD * d1, ISC_QUAD * d2)
{
    if (!d1 || !d2) {
	return NULL;
    } else {
	int *result = ageinmonths(d1, d2);
	*result = abs(*result);
	return result;
    }
}

// ct 2006-11-23 implementation of NULL for FB 2.0
int *weeksbetween(ISC_QUAD * d1, ISC_QUAD * d2)
{
    if (!d1 || !d2) {
	return NULL;
    } else {
	int *result = ageinweeks(d1, d2);
	*result = abs(*result);
	return result;
    }
}

// ct 2008-02-18
// ISO-version of weeksbetween
int *weeksbetweeniso(ISC_QUAD * d1, ISC_QUAD * d2)
{
    if (!d1 || !d2) {
	return NULL;
    } else {
	int *result = ageinweeksiso(d1, d2);
	*result = abs(*result);
	return result;
    }
}

// ct 2006-11-23 implementation of NULL for FB 2.0
int *daysbetween(ISC_QUAD * d1, ISC_QUAD * d2)
{
    if (!d1 || !d2) {
	return NULL;
    } else {
	int *result = ageindays(d1, d2);
	*result = abs(*result);
	return result;
    }
}

// ct 2006-11-23 implementation of NULL for FB 2.0
int *hoursbetween(ISC_QUAD * d1, ISC_QUAD * d2)
{
    if (!d1 || !d2) {
	return NULL;
    } else {
	int *result = ageinhours(d1, d2);
	*result = abs(*result);
	return result;
    }
}

// ct 2006-11-23 implementation of NULL for FB 2.0
int *minutesbetween(ISC_QUAD * d1, ISC_QUAD * d2)
{
    if (!d1 || !d2) {
	return NULL;
    } else {
	int *result = ageinminutes(d1, d2);
	*result = abs(*result);
	return result;
    }
}

// ct 2006-11-23 implementation of NULL for FB 2.0
int *secondsbetween(ISC_QUAD * d1, ISC_QUAD * d2)
{
    if (!d1 || !d2) {
	return NULL;
    } else {
	int *result = ageinseconds(d1, d2);
	*result = abs(*result);
	return result;
    }
}

// pm 2005-10-16
// ct 2006-11-23 implementation of NULL for FB 2.0
ISC_DATE *encodedate(int *year, int *month, int *day)
{
    if (!year || !month || !day) {
	return NULL;
    } else {
	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;
    }
}

// gh 2006-12-01
ISC_DATE *encodedatenull(int *year, int *month, int *day)
{
    if (!year || !month || !day || *month > 12 || *day > 31) {
	return NULL;
    } else {
	ISC_DATE dummy;
	struct tm t1, t2;

	t1.tm_year = *year - 1900;
	t1.tm_mon = *month - 1;
	t1.tm_mday = *day;
	t1.tm_wday = 0;
	t1.tm_yday = 0;
	isc_encode_sql_date(&t1, &dummy);
	isc_decode_sql_date(&dummy, &t2);
	if (t1.tm_mon != t2.tm_mon) {
	    return NULL;
	} else {
	    ISC_DATE *result = (ISC_DATE *) MALLOC(sizeof(ISC_DATE));
	    memcpy(result, &dummy, sizeof(ISC_DATE));
	    return result;
	}
    }
}

// ct 2007-01-27
ISC_QUAD *r_encodedate(int *day, int *month, int *year)
{
    if (!year || !month || !day ) {
	return NULL;
    } else {
	struct tm t;

	t.tm_year = *year - 1900;
	t.tm_mon = *month - 1;
	t.tm_mday = *day;
	t.tm_hour = 0;
	t.tm_min = 0;
	t.tm_sec = 0;

	t.tm_wday = 0;
	t.tm_yday = 0;

	return gen_ib_date(&t);
    }
}

// pm 2005-10-16
// ct 2006-11-23 implementation of NULL for FB 2.0
ISC_TIME *encodetime(int *hour, int *minute, int *second)
{
    if (!hour || !minute || !second)
	return NULL;
    else {
	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;
    }
}

// ct 2006-12-01
ISC_TIME *encodetimenull(int *hour, int *minute, int *second)
{
    if (!hour || !minute || !second || *hour > 23 || *minute > 59
	    || *second > 59) {
	return NULL;
    } else {
	ISC_TIME dummy;
	struct tm t1, t2;

	t1.tm_hour = *hour;
	t1.tm_min = *minute;
	t1.tm_sec = *second;

	isc_encode_sql_time(&t1, &dummy);
	isc_decode_sql_time(&dummy, &t2);
	if (t1.tm_hour != t2.tm_hour) {
	    return NULL;
	} else {
	    ISC_TIME *result = (ISC_TIME *) MALLOC(sizeof(ISC_TIME));
	    memcpy(result, &dummy, sizeof(ISC_TIME));
	    return result;
	}
    }
}

// pm 2005-10-16
// ct 2006-11-23 implementation of NULL for FB 2.0
ISC_QUAD *encodetimestamp(int *year, int *month, int *day, int *hour,
    int *minute, int *second)
{
    if (!year || !month || !day || !hour || !minute || !second) {
	return NULL;
    } else {
	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);
    }
}

// ct 2007-01-27
ISC_QUAD *r_encodedatetime(int *day, int *month, int *year, int *hour,
    int *minute, int *second)
{
    if (!year || !month || !day || !hour || !minute || !second) {
	return NULL;
    } else {
	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);
    }
}

// intern
// gh 2007-01-30
/* convert a period in format "[-][d:]hh:mm:ss" into seconds.
   return 0 on success, -1 on error. */
static int period_to_time(char *p, int *t)
{
    int neg, n, d, h, m, s;
    char *pc;

    /* check if negative */
    if (*p == '-') {
	p++;
	neg = 1;
    } else {
	neg = 0;
    }

    /* count number of elements */
    pc = p;
    n = 1;
    while (*pc) {
	if (*pc++ == ':') {
	    n++;
	}
    }

    /* scan elements and check if all are positive */
    if (n == 3) {
	d = 0;
	n = sscanf(p, "%d:%d:%d", &h, &m, &s);
	if (n != 3 || h < 0 || m < 0 || s < 0) {
	    return -1;
	}
    } else if (n == 4) {
	n = sscanf(p, "%d:%d:%d:%d", &d, &h, &m, &s);
	if (n != 4 || d < 0 || h < 0 || m < 0 || s < 0) {
	    return -1;
	}
    } else {
	return -1;
    }

    /* calculate seconds */
    *t = d * 24 * 3600 + h * 3600 + m * 60 + s;
    if (neg) {
	*t = -*t;
    }

    return 0;
}


// intern
// gh 2007-01-30
// convert seconds into a period
static char *time_to_period(int t)
{
    int d, h, m, s, neg;
    char *p = MALLOC(LOC_STRING_SIZE);

    if (t < 0) {
	t = -t;
	neg = 1;
    } else {
	neg = 0;
    }

    d = t / (24 * 3600);
    t -= d * 24 * 3600;
    h = t / 3600;
    t -= h * 3600;
    m = t / 60;
    s = t - m * 60;

    if (d) {
	sprintf(p, "%s%02d:%02d:%02d:%02d", neg ? "-" : "", d, h, m, s);
    } else {
	sprintf(p, "%s%02d:%02d:%02d", neg ? "-" : "", h, m, s);
    }

    return p;
}

// gh 2007-01-30
// return p1 + p2
char *addperiod(char *p1, char *p2)
{
    int t1, t2;

    if (!p1 || !p2 || period_to_time(p1, &t1) < 0 || period_to_time(p2, &t2) < 0) {
	return NULL;
    } else {
	return time_to_period(t1 + t2);
    }
}

// gh 2007-01-30
// p1 - p2
char *subperiod(char *p1, char *p2)
{
    int t1, t2;

    if (!p1 || !p2 || period_to_time(p1, &t1) < 0 || period_to_time(p2, &t2) < 0) {
	return NULL;
    } else {
	return time_to_period(t1 - t2);
    }
}

// gh 2007-01-30
// convert a period into seconds
int *period2seconds(char *p)
{
    int t;

    if (!p || period_to_time(p, &t) < 0) {
	return NULL;
    } else {
	int *i = MALLOC(sizeof(int));
	*i = t;
	return i;
    }
}

// gh 2007-01-30
// convert seconds into a period
char *seconds2period(int *t)
{
    if (!t) {
	return NULL;
    } else {
	return time_to_period(*t);
    }
}

// ct 2007-01-28
char* datetostr(ISC_QUAD *date, char *pat)
{
    if (!date || !pat)
	return NULL;
    else {
        char *result = (char *) MALLOC (LOC_STRING_SIZE);
	struct tm t;
	isc_decode_date(date, &t);
	if (!strftime(result, LOC_STRING_SIZE - 1, pat, &t)) result[0] = '\0';
	return result;
    }
}

// gh 2008-02-19
static char *replstr(char *s, char *subs, char *replby)
{
    char *sz_result;
    char *pd;

    int sl = strlen(subs);
    int rl = strlen(replby);
    sz_result = malloc(LOC_STRING_SIZE);

    pd = sz_result;
    while (*s) {
	if (strncmp(s, subs, sl) == 0) {
	    strcpy(pd, replby);
	    pd += rl;
	    s += sl;
	} else {
	    *pd++ = *s++;
	}
    }
    *pd = 0;
    return sz_result;
}

// gh 2008-02-19
// uk de fr it es pt nl no se dk fi hu ie ee is al va v1 c1 s1 s2 w1 b1 b2 n1 za fo lu w2
char *datetostrlang(ISC_QUAD *date, char *pat, char *language)
{
    if (!date || !pat || !language) {
	return NULL;
    } else {
        char *result = (char *) MALLOC (LOC_STRING_SIZE);
	struct tm t;
        int lang;

	isc_decode_date(date, &t);
	lang = decode_language(language);

	if (lang < 0) {
	    strcpy(result, "???");
	} else {
	    char *r1 = malloc(LOC_STRING_SIZE), *r2, *p;
	    int i;
	    char monthshort1[4], monthshort2[4];

	    if (!strftime(r1, LOC_STRING_SIZE - 1, pat, &t)) {
		r1[0] = '\0';
	    }
	    for (i = 0; i < 7; i++) {
		if (strstr(r1, DOW[i])) {
		    r2 = replstr(r1, DOW[i], DOW[lang * 7 + i]);
		    free(r1);
		    r1 = r2;
		}
		p = strstr(r1, DOWSHORT[i]);
		if (p && strncmp(p, DOW[lang * 7 + i], strlen(DOW[lang * 7 + i]))) {
		    r2 = replstr(r1, DOWSHORT[i], DOWSHORT[lang * 7 + i]);
		    free(r1);
		    r1 = r2;
		}
	    }
	    for (i = 0; i < 12; i++) {
		if (strstr(r1, MONTH[i])) {
		    r2 = replstr(r1, MONTH[i], MONTH[lang * 12 + i]);
		    free(r1);
		    r1 = r2;
		}
		strncpy(monthshort1, MONTH[i], 3);
		monthshort1[3] = '\0';
		if (!strcmp(language, "fr") && monthshort1[1] == 'u') {
		    /* Juin -> Jun, Juillet -> Jul */
		    monthshort1[2] = MONTH[i][3];
		}
		p = strstr(r1, monthshort1);
		if (p && strncmp(p, MONTH[lang * 12 + i], strlen(MONTH[lang * 12 + i]))) {
		    strncpy(monthshort2, MONTH[lang * 12 + i], 3);
		    monthshort2[3] = '\0';
		    if (!strcmp(language, "fr") && monthshort2[1] == 'u') {
			/* Juin -> Jun, Juillet -> Jul */
			monthshort2[2] = MONTH[lang * 12 + i][3];
		    }
		    r2 = replstr(r1, monthshort1, monthshort2);
		    free(r1);
		    r1 = r2;
		}
	    }
	    strcpy(result, r1);
	    free(r1);
        }
	return result;
    }
}

// ct 2007-01-28
ISC_QUAD *firstdaymonth(ISC_QUAD * ib_date)
{
    if (!ib_date)
	return NULL;
    else {
	struct tm t;
	isc_decode_date(ib_date, &t);
	t.tm_mday = 1;
	t.tm_sec = 0;
	t.tm_min = 0;
	t.tm_hour = 0;
	t.tm_isdst = 0;
	return gen_ib_date(&t);
    }
}

// ct 2007-01-28
ISC_QUAD *lastdaymonth(ISC_QUAD * ib_date)
{
    if (!ib_date)
	return NULL;
    else {
	struct tm t;
	isc_decode_date(ib_date, &t);
	t.tm_mday = intern_daysofmonth(t.tm_mon + 1, t.tm_year + 1900);
	t.tm_sec = 0;
	t.tm_min = 0;
	t.tm_hour = 0;
	t.tm_isdst = 0;
	return gen_ib_date(&t);
    }
}

const double msec_in_day = 24. * 60. * 60. * ISC_TIME_SECONDS_PRECISION;

// ct 2007-02-01
double *timetodouble(ISC_QUAD * time)
{
    if (!time)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
        *result = (double) time->gds_quad_low / msec_in_day;
        return result;
    }
}

// ct 2007-02-01
double *datetodouble(ISC_QUAD * date)
{
    if (!date)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
        *result = (double) date->gds_quad_high + (double) date->gds_quad_low / msec_in_day;
        return result;
    }
}

// ct 2007-02-01
ISC_QUAD * doubletodate(double * d)
{
    if (!d)
	return NULL;
    else {
	ISC_QUAD *result = (ISC_QUAD *) MALLOC (sizeof(ISC_QUAD));
	result->gds_quad_high = *d;
	*d = (*d - result->gds_quad_high) * msec_in_day;
	result->gds_quad_low = intern_zahlrunden(*d, 0);

	return result;
    }
}

// ct 2007-02-01
ISC_QUAD * doubletotime(double * d)
{
    if (!d)
	return NULL;
    else {
	ISC_QUAD *result = (ISC_QUAD *) MALLOC(sizeof(ISC_QUAD));
	result->gds_quad_high = *d;
	*d = (*d - result->gds_quad_high) * msec_in_day;
	result->gds_quad_high = 0;
	result->gds_quad_low = intern_zahlrunden(*d, 0);

	return result;
    }
}

// ct 2007-02-02
ISC_QUAD * incdate (ISC_QUAD *date, int *d, int *m, int *y)
{
  if (!date || !d || !m || !y)
    return NULL;
  else
  {
    ISC_QUAD *result, *result1;
    struct tm t;
    int tm_mon, tm_year;

    isc_decode_date(date, &t);
    tm_mon = t.tm_mon + 12 * t.tm_year + *m;
    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;

    t.tm_year += *y;

    /*
     * 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;

    result = gen_ib_date(&t);
    result1 = addseconds(result, 24 * 60 * 60 * *d);
    free(result);
    return result1;
  }
}

// ct 2007-02-02
ISC_QUAD * incdatetime (ISC_QUAD *date, int *d, int *m, int *y, int *h, int *min, int *s)
{
  if (!date || !d || !m || !y || !h || !min || !s)
    return NULL;
  else
  {
    ISC_QUAD *result, *result1;
    struct tm t;
    int tm_mon, tm_year;

    isc_decode_date(date, &t);
    tm_mon = t.tm_mon + 12 * t.tm_year + *m;
    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;

    t.tm_year += *y;

    /*
     * 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;

    result = gen_ib_date(&t);
    result1 = addseconds(result, (24 * 60 * 60 * *d) + (3600 * *h) + (60 * *min) + *s);
    free(result);
    return result1;
  }
}

// gh 2007-08-09
// weekday of 1st january
static int intern_wd11(ISC_QUAD *date, int k)
{
    struct tm t;
    ISC_QUAD d;

    isc_decode_date(date, &t);
    t.tm_mday = 1;
    t.tm_mon = 0;
    t.tm_year = t.tm_year + k;
    isc_encode_date(&t, &d);
    isc_decode_date(&d, &t);
    return t.tm_wday + 1;
}

// ct 2007-08-09
// gh 2008-02-12 made from old kalenderwoche
// calc week of year (german KW) ISO 8601
static int intern_kalenderwoche(ISC_QUAD * date)
{
        int dayofyear, weekday11, weekday11ly, weekday11ny, week;

        /* calc day of year, 1st Jan = 1 ... */
        dayofyear = intern_dayofyear(date) - 1;

        /* calc weekday of 1st Jan of this year, 1 = Sunday, 2 = Monday  ... */
        weekday11 = intern_wd11(date, 0);
        // change to 0 = Monday, 1 = Thuesday ... 6 = Sunday
        weekday11 = weekday11 == 1 ? 6 : weekday11 - 2;

        /* calc weekday of 1st Jan last year, 1 = Sunday, 2 = Monday  ... */
        weekday11ly = intern_wd11(date, -1);
        // change to 0 = Monday, 1 = Thuesday ... 6 = Sunday
        weekday11ly = weekday11ly == 1 ? 6 : weekday11ly - 2;

        /* calc weekday of 1st Jan next year, 1 = Sunday, 2 = Monday  ... */
        weekday11ny = intern_wd11(date, 1);
        // change to 0 = Monday, 1 = Thuesday ... 6 = Sunday
        weekday11ny = weekday11ny == 1 ? 6 : weekday11ny - 2;

        if (weekday11 > 3)
        {
           dayofyear -= (7 - weekday11);
        }
        else
        {
           dayofyear += weekday11;
        }
        if (dayofyear < 0)
        {
          if (   (weekday11 == 4) || (weekday11ly == 3))
          {
             week = 53;
          }
          else
          {
             week = 52;
          }
        }
        else
        {
             week = (dayofyear / 7) + 1;
        }
        if ((dayofyear > 360) && (week > 52))
        {
          if (weekday11 == 3)
          {
             week = 53;
          }
          else
          {
              if (weekday11ny == 4)
              {
                week = 53;
              }
              else
              {
                week = 1;
              }
          }
        }
        return week;
}

// gh 2008-02-12
int *kalenderwoche(ISC_QUAD * date)
{
    if (!date)
    {
	return NULL;
    }
    else
    {
	int *result = MALLOC(sizeof(int));
        *result = intern_kalenderwoche(date);
        return result;
    }
}

// christian floating holidays

// ct 2007-07-22
// Weiberfastnacht /       = 52 days before easter sunday
ISC_QUAD *weiberfastnacht(int *year)
{
     if (!year)
	return NULL;
     else {
        ISC_QUAD *ostern, *result;
        ostern = osterdatum(year);
        result = addseconds(ostern, 24 * 60 * 60 * -52);
        free(ostern);
        return result;
     }
}

// ct 2007-07-22
// Carnival Monday / Rosenmontag / Veille du Mardi Gras = 48 days before easter sunday
ISC_QUAD *rosenmontag(int *year)
{
     if (!year)
	return NULL;
     else {
        ISC_QUAD *ostern, *result;
        ostern = osterdatum(year);
        result = addseconds(ostern, 24 * 60 * 60 * -48);
        free(ostern);
        return result;
     }
}

// ct 2007-07-22
//  Mardi Gras / Karnevalsdienstag / Mardi Gras            =  -47 days before easter sunday
ISC_QUAD *karnevalsdienstag(int *year)
{
     if (!year)
	return NULL;
     else {
        ISC_QUAD *ostern, *result;
        ostern = osterdatum(year);
        result = addseconds(ostern, 24 * 60 * 60 * -47);
        free(ostern);
        return result;
     }
}

// ct 2007-07-22
//  Ash Wednesday / Aschermittwoch / Mercredi des Cendres  =  -46 days before easter sunday
ISC_QUAD *aschermittwoch(int *year)
{
     if (!year)
	return NULL;
     else {
        ISC_QUAD *ostern, *result;
        ostern = osterdatum(year);
        result = addseconds(ostern, 24 * 60 * 60 * -46);
        free(ostern);
        return result;
     }
}

// ct 2007-07-22
//  Palm Sunday / Palmsonntag / Dimanche des Rameaux       =   -7 days before easter sunday
ISC_QUAD *palmsonntag(int *year)
{
     if (!year)
	return NULL;
     else {
        ISC_QUAD *ostern, *result;
        ostern = osterdatum(year);
        result = addseconds(ostern, 24 * 60 * 60 * -7);
        free(ostern);
        return result;
     }
}

// ct 2007-07-22
//  Easter Thursday / Gründonnerstag /             =   -3 days before easter sunday
ISC_QUAD *gruendonnerstag(int *year)
{
     if (!year)
	return NULL;
     else {
        ISC_QUAD *ostern, *result;
        ostern = osterdatum(year);
        result = addseconds(ostern, 24 * 60 * 60 * -3);
        free(ostern);
        return result;
     }
}

// ct 2007-07-22
//  Easter Friday / Karfreitag / Vendredi Saint            =   -2 days before easter sunday
ISC_QUAD *karfreitag(int *year)
{
     if (!year)
	return NULL;
     else {
        ISC_QUAD *ostern, *result;
        ostern = osterdatum(year);
        result = addseconds(ostern, 24 * 60 * 60 * -2);
        free(ostern);
        return result;
     }
}

// ct 2007-07-22
//  Easter Saturday / Ostersamstag / Samedi de Paques      =   -1 day before easter sunday
ISC_QUAD *ostersamstag(int *year)
{
     if (!year)
	return NULL;
     else {
        ISC_QUAD *ostern, *result;
        ostern = osterdatum(year);
        result = addseconds(ostern, 24 * 60 * 60 * -1);
        free(ostern);
        return result;
     }
}

// ct 2007-07-22
//  Easter Monday / Ostermontag / Lundi de Paques          =   +1 day after easter sunday
ISC_QUAD *ostermontag(int *year)
{
     if (!year)
	return NULL;
     else {
        ISC_QUAD *ostern, *result;
        ostern = osterdatum(year);
        result = addseconds(ostern, 24 * 60 * 60 * 1);
        free(ostern);
        return result;
     }
}

// ct 2007-07-22
//  Ascension of Christ / Christi Himmelfahrt / Ascension  =  +39 days after easter sunday
ISC_QUAD *himmelfahrt(int *year)
{
     if (!year)
	return NULL;
     else {
        ISC_QUAD *ostern, *result;
        ostern = osterdatum(year);
        result = addseconds(ostern, 24 * 60 * 60 * 39);
        free(ostern);
        return result;
     }
}

// ct 2007-07-22
//  Whitsunday / Pfingstsonntag / Dimanche de Pentecote    =  +49 days after easter sunday
ISC_QUAD *pfingstsonntag(int *year)
{
     if (!year)
	return NULL;
     else {
        ISC_QUAD *ostern, *result;
        ostern = osterdatum(year);
        result = addseconds(ostern, 24 * 60 * 60 * 49);
        free(ostern);
        return result;
     }
}

// ct 2007-07-22
//  Whitmonday / Pfingstmontag / Lundi de Pentecote        =  +50 days after easter sunday
ISC_QUAD *pfingstmontag(int *year)
{
     if (!year)
	return NULL;
     else {
        ISC_QUAD *ostern, *result;
        ostern = osterdatum(year);
        result = addseconds(ostern, 24 * 60 * 60 * 50);
        free(ostern);
        return result;
     }
}

// ct 2007-07-22
//  Feast of Corpus Christi / Fronleichnam / Fete-Dieu     =  +60 days after easter sunday
ISC_QUAD *fronleichnam(int *year)
{
     if (!year)
	return NULL;
     else {
        ISC_QUAD *ostern, *result;
        ostern = osterdatum(year);
        result = addseconds(ostern, 24 * 60 * 60 * 60);
        free(ostern);
        return result;
     }
}

                                                  date_functions.h                                                                                    0000744 0000000 0000764 00000016030 10756252336 013060  0                                                                                                    ustar   root                            adhoc                                                                                                                                                                                                                  /*****************************************************************************
 * FreeAdhocUDF - copyright (c) 2004 - 2008 adhoc dataservice GmbH
 * Christoph Theuring / Peter Mandrella / Georg Horn
 * <http://www.udf.adhoc-data.de> eMail <udf@adhoc-data.de>
 * based on FreeUDFLibC - copyright (c) 1999 Gregory Deatz
 * altered by Robert Loipfinger copyright (c) 2001 ADITO Software GmbH
 *
 * File Name:	date_functions.h
 * Description: This header contains the prototype definitions
 *
 * This file is part of FreeAdhocUDF.
 * FreeAdhocUDF is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * FreeAdhocUDF is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with FreeAdhocUDF.  If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/

#ifndef isleap
#define isleap(y) ((((y) % 4) == 0 && ((y) % 100) != 0) || ((y) % 400) == 0)
#endif

ISC_QUAD * addday (ISC_QUAD *, int *);
ISC_QUAD * addhour (ISC_QUAD *, int *);
ISC_QUAD * addminute (ISC_QUAD *, int *);
ISC_QUAD * addmonth (ISC_QUAD *, int *);
ISC_QUAD * addweek (ISC_QUAD *, int *);
ISC_QUAD * addsecond (ISC_QUAD *, int *);
ISC_QUAD * addyear (ISC_QUAD *, int *);
int * ageinyears (ISC_QUAD *, ISC_QUAD *);
int * ageinyearsnull (ISC_QUAD *, ISC_QUAD *);
int * ageinyearsthreshold (ISC_QUAD *, ISC_QUAD *, int *, int *, int *, int *);
int * ageinyearsthresholdnull (ISC_QUAD *, ISC_QUAD *, int *, int *, int *, int *);
int * ageinmonths (ISC_QUAD *, ISC_QUAD *);
int * ageinmonthsnull (ISC_QUAD *, ISC_QUAD *);
int * ageinmonthsthreshold (ISC_QUAD *, ISC_QUAD *, int *, int *, int *, int *);
int * ageinmonthsthresholdnull (ISC_QUAD *, ISC_QUAD *, int *, int *, int *, int *);
int * countweekdays(ISC_QUAD *, ISC_QUAD *, int *);
int * ageinweeks (ISC_QUAD *, ISC_QUAD *);
int * ageinweeksiso (ISC_QUAD *, ISC_QUAD *);
int * ageinweeksnull (ISC_QUAD *, ISC_QUAD *);
int * ageinweeksnulliso (ISC_QUAD *, ISC_QUAD *);
int * ageinweeksthreshold (ISC_QUAD *, ISC_QUAD *, int *, int *, int *, int *);
int * ageinweeksthresholdiso (ISC_QUAD *, ISC_QUAD *, int *, int *, int *, int *);
int * ageinweeksthresholdnull (ISC_QUAD *, ISC_QUAD *, int *, int *, int *, int *);
int * ageinweeksthresholdnulliso (ISC_QUAD *, ISC_QUAD *, int *, int *, int *, int *);
int * ageindays (ISC_QUAD *, ISC_QUAD *);
int * ageindaysnull (ISC_QUAD *, ISC_QUAD *);
int * ageindaysthreshold (ISC_QUAD *, ISC_QUAD *, int *, int *, int *, int *);
int * ageindaysthresholdnull (ISC_QUAD *, ISC_QUAD *, int *, int *, int *, int *);
int * ageinhours (ISC_QUAD *, ISC_QUAD *);
int * ageinhoursnull (ISC_QUAD *, ISC_QUAD *);
int * ageinhoursthreshold (ISC_QUAD *, ISC_QUAD *, int *, int *, int *, int *);
int * ageinhoursthresholdnull (ISC_QUAD *, ISC_QUAD *, int *, int *, int *, int *);
int * ageinminutes (ISC_QUAD *, ISC_QUAD *);
int * ageinminutesnull (ISC_QUAD *, ISC_QUAD *);
int * ageinminutesthreshold (ISC_QUAD *, ISC_QUAD *, int *, int *, int *, int *);
int * ageinminutesthresholdnull (ISC_QUAD *, ISC_QUAD *, int *, int *, int *, int *);
int * ageinseconds (ISC_QUAD *, ISC_QUAD *);
int * ageinsecondsnull (ISC_QUAD *, ISC_QUAD *);
int * ageinsecondsthreshold (ISC_QUAD *, ISC_QUAD *, int *, int *, int *, int *);
int * ageinsecondsthresholdnull (ISC_QUAD *, ISC_QUAD *, int *, int *, int *, int *);
char * cdowlong (ISC_QUAD *);
char * cdowlonglang (ISC_QUAD *, char *);
char * cdowshort (ISC_QUAD *);
char * cdowshortlang (ISC_QUAD *, char *);
char * cmonthlong (ISC_QUAD *);
char * cmonthlonglang (ISC_QUAD *, char *);
char * cmonthshort (ISC_QUAD *);
char * cmonthshortlang (ISC_QUAD *, char *);
int * dayofmonth (ISC_QUAD *);
int * dayofweek (ISC_QUAD *);
int * dayofyear (ISC_QUAD *);
ISC_DATE * encodedate (int *, int *, int *);
ISC_DATE * encodedatenull (int *, int *, int *);
ISC_TIME * encodetime (int *, int *, int *);
ISC_TIME * encodetimenull (int *, int *, int *);
ISC_QUAD * encodetimestamp (int *, int *, int *, int *, int *, int *);
char * gformatd (char *, ISC_QUAD *);
int * hour (ISC_QUAD *);
int * isleapyear (ISC_QUAD *);
int * lastday (int *, int *);
ISC_QUAD * maxdate (ISC_QUAD *, ISC_QUAD *);
ISC_QUAD * mindate (ISC_QUAD *, ISC_QUAD *);
int * minute (ISC_QUAD *);
int * month (ISC_QUAD *);
int * quarter (ISC_QUAD *);
int * second (ISC_QUAD *);
int * millisecond (ISC_QUAD *);
ISC_QUAD * stripdate (ISC_QUAD *);
ISC_QUAD * striptime (ISC_QUAD *);
ISC_TIME * strtotime (char *);
int * week (ISC_QUAD *);
int * weekofyear (ISC_QUAD *);
char * woy (ISC_QUAD *);
char * woyiso(ISC_QUAD *);
int * year (ISC_QUAD *);
int * yearofyear (ISC_QUAD *);
int * yearsbetween (ISC_QUAD *, ISC_QUAD *);
int * monthsbetween (ISC_QUAD *, ISC_QUAD *);
int * weeksbetween (ISC_QUAD *, ISC_QUAD *);
int * weeksbetweeniso (ISC_QUAD *, ISC_QUAD *);
int * daysbetween (ISC_QUAD *, ISC_QUAD *);
int * hoursbetween (ISC_QUAD *, ISC_QUAD *);
int * minutesbetween (ISC_QUAD *, ISC_QUAD *);
int * secondsbetween (ISC_QUAD *, ISC_QUAD *);
char * addperiod(char *, char *);
char * subperiod(char *, char *);
int * period2seconds(char *);
char * seconds2period(int *);
char * datetostr(ISC_QUAD *, char *);
char * datetostrlang(ISC_QUAD *, char *, char *);
ISC_QUAD * firstdaymonth(ISC_QUAD *);
ISC_QUAD * lastdaymonth(ISC_QUAD *);
double * timetodouble(ISC_QUAD *);
double * datetodouble(ISC_QUAD *);
ISC_QUAD * doubletodate(double *);
ISC_QUAD * doubletotime(double *);
ISC_QUAD * incdate (ISC_QUAD *, int *, int *, int *);
ISC_QUAD * incdatetime (ISC_QUAD *, int *, int *, int *, int *, int *, int *);

// internal functions
int * daysofmonth (int *, int *);
int * dtime (ISC_QUAD *);
ISC_QUAD *gen_ib_date(struct tm *t);
int decode_language(char *);

int * equaldate (ISC_QUAD *, ISC_QUAD *);
int * equaldatetime (ISC_QUAD *, ISC_QUAD *);
double * zeitdifferenz (ISC_QUAD *, ISC_QUAD *, char *);
ISC_QUAD * osterdatum (int *);
int * kalenderwoche(ISC_QUAD *);
ISC_QUAD * weiberfastnacht(int *);
ISC_QUAD * rosenmontag(int *);
ISC_QUAD * karnevalsdienstag(int *);
ISC_QUAD * aschermittwoch(int *);
ISC_QUAD * palmsonntag(int *);
ISC_QUAD * gruendonnerstag(int *);
ISC_QUAD * karfreitag(int *);
ISC_QUAD * ostersamstag(int *);
ISC_QUAD * ostermontag(int *);
ISC_QUAD * himmelfahrt(int *);
ISC_QUAD * pfingstsonntag(int *);
ISC_QUAD * pfingstmontag(int *);
ISC_QUAD * fronleichnam(int *);

// rFunc
int * r_yearday(ISC_QUAD *);
int * r_weekday(ISC_QUAD *);
int * r_dow(ISC_QUAD *);
int * r_isleapyear(int *);
ISC_QUAD * r_encodedate(int *, int *, int *);
ISC_QUAD * r_encodedatetime(int *, int *, int *, int *, int *, int *);
// Integer-Parameter sind Zeiger !!!

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        global.h                                                                                            0000744 0000000 0000764 00000004023 10756255152 011311  0                                                                                                    ustar   root                            adhoc                                                                                                                                                                                                                  /*****************************************************************************
 * FreeAdhocUDF - copyright (c) 2004 - 2008 adhoc dataservice GmbH
 * Christoph Theuring ct / Peter Mandrella pm / Georg Horn gh
 * <http://www.udf.adhoc-data.de> eMail <udf@adhoc-data.de>
 * based on FreeUDFLibC - copyright (c) 1999 Gregory Deatz
 *
 * File Name:	global.h
 * Description: This header contains the global prototype definitions
 *  
 * This file is part of FreeAdhocUDF.
 * FreeAdhocUDF is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * FreeAdhocUDF is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with FreeAdhocUDF.  If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/

#include "ibase.h"

#define LOC_STRING_SIZE 256
#define MAX_STRINGBUFFER_SIZE 32768

#if defined(__BORLANDC__) || defined(__MSVC__)
#define WINDOWS
#endif

// ct 2007-12-03 readded ib_util for ib_util_malloc because of memory leak under windows ???
// we don't understand this :-(
#include "ib_util.h"
//#define MALLOC ib_util_malloc
// pm 2006-09-24
// Workaround for Firebird bug (buffer overflow):
// Firebird writes data after end of returned UDF data.
// Allocation of the string buffer maximum of >= 32762 Bytes
// for all strings solves this problem.
// n is dummy referenced to avoid "unused variable" warning.
// FB_API_VER is only defined in ibase.h of FireBird
#ifdef FB_API_VER
#define MALLOC(n) (ib_util_malloc((n) - (n) + MAX_STRINGBUFFER_SIZE))
#else
#define MALLOC ib_util_malloc
#endif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             Makefile                                                                                            0000744 0000000 0000764 00000013117 10714336671 011344  0                                                                                                    ustar   root                            adhoc                                                                                                                                                                                                                  # ---------------------------------------------------------------------
# Linux Makefile for FreeAdhocUDF
# This file is part of FreeAdhocUDF.
# ---------------------------------------------------------------------
# FreeAdhocUDF - copyright (c) 2004 - 2007 adhoc dataservice GmbH
# Christoph Theuring / Peter Mandrella / Georg Horn
# <http://www.udf.adhoc-data.de> eMail <udf@adhoc-data.de>
# based on FreeUDFLibC - copyright (c) 1999 Gregory Deatz
# changes by adhoc dataservice GmbH
# ---------------------------------------------------------------------
#
# ---------------------------------------------------------------------
# InterBase/FireBird Installation Directory
# uncomment your choice to point to your InterBase/FireBird installation directory
# copies the FreeAdhocUDF.so to the .../UDF directory
# only for "make install" 
# ---------------------------------------------------------------------
#DBDIR=/opt/firebird
#DBDIR=/opt/interbase

# ----------------------------------------------------------------------
# uncomment your choice of the DB-system
# for InterBase you can normally choose the newest version for all ib versions
# for FireBird 1.x you must choose firebird_1_5
# for FireBird 2.x you must choose firebird_2_1
# for FireBird64 2.x you must choose firebird_2_1_64  
# ----------------------------------------------------------------------
#DBSYSTEM=interbase_6_0_2
#DBSYSTEM=interbase_7_1
#DBSYSTEM=interbase_7_5
DBSYSTEM=interbase_2007
#DBSYSTEM=firebird_1_5
#DBSYSTEM=firebird_2_0
#DBSYSTEM=firebird_2_0_64
#DBSYSTEM=firebird_2_1
#DBSYSTEM=firebird_2_1_64

# ----------------------------------------------------------------------
# set the output name
# ----------------------------------------------------------------------
ifeq (interbase, $(findstring interbase, $(DBSYSTEM)))
  FAU=FreeAdhocUDF_ib.so
endif
ifeq (firebird_1_5, $(DBSYSTEM))
  FAU=FreeAdhocUDF_fb15.so
endif
ifeq (firebird_2_, $(findstring firebird_2_, $(DBSYSTEM)))
  ifeq (_64, $(findstring _64, $(DBSYSTEM)))
    FAU=FreeAdhocUDF_fb2x64.so
  else
    FAU=FreeAdhocUDF_fb2x.so
  endif 
endif
  
# ----------------------------------------------------------------------
# Location of header files and libraries
# ----------------------------------------------------------------------
# set the directory for the associated libraries
LIB=../linux/$(DBSYSTEM)/lib

# set the directory for the associated header files
INCLUDE=../linux/$(DBSYSTEM)/include

# ----------------------------------------------------------------------
# set compiler and linker options
# ----------------------------------------------------------------------
# set the associated clientlib to the DB-system
# gds for InterBase, fbclient for FireBird   
# ----------------------------------------------------------------------
ifeq (firebird, $(findstring firebird, $(DBSYSTEM)))		
  CLIENTLIB=fbclient
else 
  CLIENTLIB=gds
endif

# ----------------------------------------------------------------------
# potential set flag for a 32 bit FreeAdhocUDF compile on a 64 bit system
# ----------------------------------------------------------------------
# point to the 32bit libraries on a 64bit system
LIB32=/usr/lib32
ifneq ($(wildcard i*86), $(findstring $(wildcard i*86), $(shell uname -a)))
	SYSTEM='the system is 64bit'
  ifneq (_64, $(findstring _64, $(DBSYSTEM)))
    CF=-m32
    LF=-mi386linux -L$(LIB32)
	  FREEADHOCUDF='the FreeAdhocUDF is 32bit'
  else
    CF=-m64
    LF=
	  FREEADHOCUDF='the FreeAdhocUDF is 64bit'
  endif  
else
	SYSTEM='the system is 32bit'
  ifneq (_64, $(findstring _64, $(DBSYSTEM)))
	  FREEADHOCUDF='the FreeAdhocUDF is 32bit'
    CF=
    LF=    
  else
    $(error no 64bit compiling on a 32bit system!)
  endif
endif
 
# ---------------------------------------------------------------------
# Compiler and linker Defines
# ---------------------------------------------------------------------
CC=gcc
LINK=gcc
LIB_LINK=ld
CFLAGS=-DIB55 -fpic -O -c -w $(CF) -I$(INCLUDE)
LIB_LINK_FLAGS=-G -Bsymbolic $(LF) -L$(LIB) -lm -lc -lib_util 

# ---------------------------------------------------------------------
# Generic Compilation Rules
#
# Do NOT change anything below this point.
# ---------------------------------------------------------------------
.SUFFIXES: .o .c .e

# .e.c:
# 	$(GPRE) $< -d $(DB)

.c.o:
	$(CC) $< $(CFLAGS) -o $@

.o:
	$(LINK) -o $@ $< $(LINK_FLAGS)

# ---------------------------------------------------------------------
# The UDF objects
# ---------------------------------------------------------------------
UDF_OBJs = date_functions.o math_functions.o string_functions.o blob_functions.o md5c.o sysdep.o uuid.o uuid_functions.o const_functions.o conv_functions.o

all: clean $(FAU)

$(FAU): $(UDF_OBJs)
	$(LIB_LINK) $(UDF_OBJs) -o $@ $(LIB_LINK_FLAGS) -l$(CLIENTLIB)
  
clean:
	rm -f *.o *~
	@echo clean done
  
new:	clean $(FAU)
	@echo chosen $(DBSYSTEM)
	@echo libs are located $(LIB)
	@echo headers are located $(INCLUDE)
	@echo clientlib is $(CLIENTLIB)
	@echo $(SYSTEM)
	@echo $(FREEADHOCUDF)
	@echo libname is $(FAU)

install:
	cp $(FAU) $(DBDIR)/UDF/FreeAdhocUDF.so

date_functions.o: date_functions.h global.h
math_functions.o: math_functions.h global.h
string_functions.o: string_functions.h global.h md5_global.h md5.h
blob_functions.o: blob_functions.h global.h
md5c.o: md5.h md5_global.h
sysdep.o: sysdep.h
uuid.o: sysdep.h uuid.h
uuid_functions.o: global.h sysdep.h uuid.h date_functions.h uuid_functions.h
const_functions.o: const_functions.h
conv_functions.o: conv_functions.h global.h


                                                                                                                                                                                                                                                                                                                                                                                                                                                 math_functions.c                                                                                    0000744 0000000 0000764 00000057677 10754320154 013105  0                                                                                                    ustar   root                            adhoc                                                                                                                                                                                                                  /*****************************************************************************
 * FreeAdhocUDF - copyright (c) 2004 - 2007 adhoc dataservice GmbH
 * Christoph Theuring ct / Peter Mandrella pm / Georg Horn gh
 * <http://www.udf.adhoc-data.de> eMail <udf@adhoc-data.de>
 * based on FreeUDFLibC - copyright (c) 1999 Gregory Deatz
 *
 * File Name:	math_functions.c
 * Description: this module contains UDFs to generate/manipulate math functions
 * for exported functions list see math_functions.h
 *
 * This file is part of FreeAdhocUDF.
 * FreeAdhocUDF is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * FreeAdhocUDF is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with FreeAdhocUDF.  If not, see <http://www.gnu.org/licenses/>. 
*****************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#ifdef __BORLANDC__
#include <process.h>
#else
pid_t getpid(void);
#endif

#include "global.h"
#include "math_functions.h"
#include "date_functions.h"

// 2007-07-22 ct add more languages
// uk de fr it es pt nl no se dk fi hu ie ee is al va v1 c1 s1 s2 w1 b1 b2 n1 za fo lu w2
static const char * NUM[] =
{
 "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".",
 "zero", "one","two","three","four","five","six","seven", "eight", "nine", "dot",
 "null","eins","zwei","drei","vier","fünf","sechs", "sieben", "acht", "neun", "Komma",
 "zéro", "un", "deux", "trois", "quatre", "cinq", "six", "sept", "huit", "neuf", "virgule",
 "zero", "uno", "due", "tre", "quattro", "cinque", "sei", "sette", "otto", "nove", "virgola",
 "cero", "uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "coma",
 "zero", "um", "duas", "três", "quatro", "cinco", "seis", "sete", "oito", "nove", ",",
 "nul", "een", "twee", "drie", "vier", "vijf", "zes", "zeven", "acht", "negen", ",",
 "null", "en", "to", "tre", "fire", "fem", "seks", "syv", "åtte", "ni", ",",
 "noll", "en", "två", "tre", "fyra", "fem", "sex", "sju", "åtta", "nio", ",",
 "nul", "en", "to", "tre", "fire", "fem", "seks", "syv", "otte", "ni", ",",
 "nolla", "yksi", "kaksi", "kolme", "neljä", "viisi", "kuusi", "seitsemän", "kahdeksan", "yhdeksän", ",",
 "nulla", "egy", "ketto~", "három", "négy", "öt", "hat", "hét", "nyolc", "kilenc", ",",
 "náid", "a haon", "a dó", "a trí", "a ceathair", "a cúig", "a sé", "a seacht", "a hocht", "a naoi", ",",
 "null", "üks", "kaks", "kolm", "neli", "viis", "kuus", "seitse", "kaheksa", "üheksa", ",",
 "núll", "einn", "tveir", "þrír", "fjórir", "fimm", "sex", "sjö", "átta", "níu", ",",
 "zero", "një", "dy", "tre", "katër", "pesë", "gjashtë", "shtatë", "tetë", "nëntë", ",",
 "NVLLVS", "VNVS", "DVO", "TRES", "QVATTVOR", "QVINQVE", "SEX", "SEPTEM", "OCTO", "NOVEM", ",",
 "nullus", "unus", "duo", "tres", "quattuor", "quinque", "sex", "septem", "octo", "novem", ",",
 "zero", "un", "dos", "tres", "quatre", "cinc", "sis", "set", "vuit", "nou", ",",
 "nocht", "ane", "twa", "three", "fower", "five", "sax", "sieven", "aicht", "nine", ",",
 "neoni", "aon", "dhà", "trì", "ceithir", "còig", "sia", "seachd", "ochd", "naoi", ",",
 "dim", "un", "dau", "tri", "pedwar", "pump", "chwech", "saith", "wyth", "naw", ",",
 "mann", "unan", "daou", "tri", "pevar", "pemp", "c’hwec’h", "seizh", "eizh", "nav", ",",
 "zero", "bat", "bi", "hiru", "lau", "bost", "sei", "zazpi", "zortzi", "bederatzi", ",",
 "null", "ein", "to", "tri", "fire", "fem", "seks", "syv", "åtte", "ni", ",",
 "nul", "een", "twee", "drie", "vier", "vyf", "ses", "sewe", "agt", "nege", ",",
 "null", "ein", "tveir", "tríggir", "fýra", "fimm", "seks", "sjey", "átta", "níggju", ",",
 "eent", "zwee", "dräi", "véier", "fënnef", "sechs", "siwen", "aacht", "néng", "zéng", ",",
 "zérô", "onk", "deus", "troes", "cwate", "cénk", "shîjh", "set", "ût", "noûv", ","
};

// ct 2006-11-26 implementation of NULL for FB 2.0
char *converttodollar(double *value)
{
    if (!value)
	return NULL;
    else {
	char *sz_result = (char *) MALLOC(LOC_STRING_SIZE + 1);
	sprintf(sz_result, "$%.2f", (*value));
	return sz_result;
    }
}


// ct 2006-11-26 implementation of NULL for FB 2.0
double *doubleabs(double *value)
{
    if (!value)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	if (*value < 0)
	    *result = -*value;
	else
	    *result = *value;
	return result;
    }
}


// ct 2006-11-26 implementation of NULL for FB 2.0
char *fixedpoint(double *value, int *decimals)
{
    if (!value || !decimals)
	return NULL;
    else {
	char *sz_result = MALLOC(LOC_STRING_SIZE + 1);
	sprintf(sz_result, "%.*f", *decimals, *value);
	return sz_result;
    }
}


#ifndef __BORLANDC__
double trunc(double x);
#endif

// intern: round d1 with precision nk
double intern_zahlrunden(double d1, int nk)
{
    int sign = (d1 < 0.0);
    int n;

    if (sign) {
	d1 *= -1.0;
    }
    n = nk;
    while (n--) {
	d1 *= 10.0;
    }
#ifdef __BORLANDC__
    d1 = floor(d1 + 0.5);
#else
    d1 = trunc(d1 + 0.5);
#endif
    n = nk;
    while (n--) {
	d1 /= 10.0;
    }
    if (sign) {
	d1 *= -1.0;
    }

    return d1;
}

// pm 2005-10-xx
// gh 2008-01-
// round value with precision nk, using comma as decimal separator and tsep for thousands grouping.
char *fixedpointlang(double *value, int *nk, char *comma, char *tsep)
{
    if (!value || !nk || !comma || !tsep) {
	return NULL;
    } else {
	char buffer[128];
	double val;
	char *sz_result = malloc(LOC_STRING_SIZE + 1);
	char *resp = sz_result;
	char *pc;
	int i, bl, offset;
	
	if (*nk < 0) {
	    *nk = 0;
	}
	val = intern_zahlrunden(*value, *nk);
	offset = (*nk > 0) ? 2 : 1;

	bl = sprintf(buffer, "%.*f", *nk, val);
	for (i = 0; i < bl; i++) {
	    if (buffer[i] == '.' || buffer[i] == ',') {
		// Dezimalpunkt
		pc = comma;
		while (*pc) {
		    *resp++ = *pc++;
		}
	    } else {
		*resp++ = buffer[i];
	    }
	    if (*tsep && (i < bl - offset - *nk) && (((bl - offset - *nk - i) % 3) == 0)) {
		// Tausender-Separator
		pc = tsep;
		while (*pc) {
		    *resp++ = *pc++;
		}
	    }
	}
	*resp = '\0';
	return sz_result;
    }
}

// ct 2006-11-26 implementation of NULL for FB 2.0
int *integerabs(int *value)
{
    if (!value)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	if (*value < 0)
	    *result = -*value;
	else
	    *result = *value;
	return result;
    }
}


// pm 21.08.04
// ct 2006-11-26 implementation of NULL for FB 2.0
double *maxnum(double *d1, double *d2)
{
    if (!d1 || !d2)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	if (*d1 >= *d2)
	    *result = *d1;
	else
	    *result = *d2;
	return result;
    }
}


// pm 21.08.04
// ct 2006-11-26 implementation of NULL for FB 2.0
double *minnum(double *d1, double *d2)
{
    if (!d1 || !d2)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	if (*d1 <= *d2)
	    *result = *d1;
	else
	    *result = *d2;
	return result;
    }
}


// ct 2006-11-26 implementation of NULL for FB 2.0
int *modulo(int *numerator, int *denominator)
{
    if (!numerator || !denominator)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	if (*denominator == 0)
	    *result = 0;
	else
	    *result = *numerator % *denominator;
	return result;
    }
}


// pm 21.08.04
// ct 2006-11-26 implementation of NULL for FB 2.0
int *isdivisibleby(int *numerator, int *denominator)
{
    if (!numerator || !denominator)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	if (*denominator == 0)
	    *result = 0;
	else
	    *result = ((*numerator % *denominator) == 0);
	return result;
    }
}


// ct 2006-11-14
// ct 2006-11-26 implementation of NULL for FB 2.0
int *evenodd(int *numerator)
{
    if (!numerator)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	*result = ((*numerator % 2) == 0);
	return result;
    }
}


// ct 2006-11-26 implementation of NULL for FB 2.0
// ct 2006-12-15 changed name from round to f_round because of function name in c
int *f_round(double *value)
{
    if (!value)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	if (*value < 0)
	    *result = (int) (*value - 0.5);
	else
	    *result = (int) (*value + 0.5);
	return result;
    }
}


// ct 2006-11-26 implementation of NULL for FB 2.0
// ct 2006-12-15 changed name from truncate to f_truncate because of function name in c
int * f_truncate(double *value)
{
    if (!value)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	*result = (int) (*value);
	return result;
    }
}


// pm 21.08.04
// ct 2006-11-26 implementation of NULL for FB 2.0
double *fact(int *n)
{
    if (!n)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	if (*n < 1 || *n > 100)
	    *result = 0.0;
	else {
	    int i;
	    double f = 1.0;
	    for (i = 2; i <= *n; i++)
		f *= i;
	    *result = f;
	}
	return result;
    }
}


// pm 03.10.05
// ct 2006-11-26 implementation of NULL for FB 2.0
int *equalfloat(double *d1, double *d2)
{
    if (!d1 || !d2)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	*result = (*d1 == *d2);
	return result;
    }
}


// pm 03.10.05
// ct 2006-11-26 implementation of NULL for FB 2.0
int *equalinteger(int *i1, int *i2)
{
    if (!i1 || !i2)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	*result = (*i1 == *i2);
	return result;
    }
}


// udf: round d1 with precision nk.
double *zahlrunden(double *d1, int *nk)
{
    if (!d1 || !nk) {
	return NULL;
    } else {
	double *result = MALLOC(sizeof(double));
	*result = intern_zahlrunden(*d1, *nk);
	return result;
    }
}

// ct 2007-01-24
double *roundtoeven(double *d1, int *nk)
{
    if (!d1 || !nk) {
	return NULL;
    } else {
	double *result = MALLOC(sizeof(double));
	double res = *d1;
	int n = *nk;
	int sign = (res < 0.0);

	if (sign) {
	    res *= -1.0;
	}
	while (n--) {
	    res *= 10.0;
	}
#ifdef __BORLANDC__
        if (res + 0.5 - floor(res + 0.5) == 0 && (((int) floor(res) % 2) == 0))
          res = floor(res);
        else
	  res = floor(res + 0.5);
#else
        if (res + 0.5 - trunc(res + 0.5) == 0 && (((int) trunc(res) % 2) == 0))
          res = trunc(res);
        else
  	  res = trunc(res + 0.5);
#endif
	n = *nk;
	while (n--) {
	    res /= 10.0;
	}
	if (sign) {
	    res *= -1.0;
	}

	*result = res;
	return result;
    }
}

// ct 2006-12-21 similar to zahlrunden and softround from rfunc
double *softround(double *d1, int *nk)
{
    if (!d1 || !nk)
	return NULL;
    else {
   	double *result = MALLOC(sizeof(double));
	double res = *d1;
	int n = *nk;
	int sign = (res < 0.0);

        if(*d1 * pow(10, *nk) >= 1) {
	    if (sign) {
	        res *= -1.0;
	    }
	    while (n--) {
	        res *= 10.0;
	    }
#ifdef __BORLANDC__
	    res = floor(res + 0.5);
#else
	    res = trunc(res + 0.5);
#endif
	    n = *nk;
	    while (n--) {
	        res /= 10.0;
	    }
	    if (sign) {
	        res *= -1.0;
	    }

	    *result = res;
        }
        else {
            *result = *d1;
        }
	return result;
    }
}

// pm 22.10.05
// ct 2006-11-26 implementation of NULL for FB 2.0
double *roundfloat(double *d1, double *d2)
{
    if (!d1 || !d2)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	if (*d2 == 0)
	    *result = 0;
	else
	    *result = floor((*d1 / *d2) + 0.5) * *d2;
	return result;
    }
}


// pm 03.10.05
// ct 2006-11-26 implementation of NULL for FB 2.0
// ct2006-12-10 bug
double *prozente(double *d1, double *d2)
{
    if (!d1 || !d2)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = *d1 * *d2 / 100.0;
	return result;
    }
}


// gh 14.10.06
/* integer random number in range a <= x <= e */
// ct 2006-11-26 implementation of NULL for FB 2.0
int *intrandom(int *a, int *e)
{
    if (!a || !e)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	static time_t t = 0;
	double r = *e - *a + 1;

	if (t == 0)
	    srand((unsigned) time(&t) + getpid());
	*result = *a + (int) (r * rand() / (RAND_MAX + 1.0));
	return result;
    }
}

// ct 2007-02-05
int *getrandom(int *e)
{
    if (!e)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	static time_t t = 0;
	double r = *e + 1;

	if (t == 0)
	    srand((unsigned) time(&t) + getpid());
	*result = (int) (r * rand() / (RAND_MAX + 1.0));
	return result;
    }
}

// ct 2006-12-15
double *doublerandom(int *a, int *e)
{
    if (!a || !e)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	static time_t t = 0;
	double r = *e - *a + 1;

	if (t == 0)
	    srand((unsigned) time(&t) + getpid());
	*result = *a + (double) (r * rand() / (RAND_MAX + 1.0));
	return result;
    }
}

// ct 2006-12-15
double * sin_rad(double *a)
{
    if (!a)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = sin(*a);
        return result;
    }
}

// ct 2006-12-15
double * cos_rad(double *a)
{
    if (!a)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = cos(*a);
        return result;
    }
}

// ct 2006-12-15
double * tan_rad(double *a)
{
    if (!a)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = tan(*a);
        return result;
    }
}

// ct 2006-12-15
double *cot_rad(double *a)
{
    if (!a)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = 1.0 / (tan(*a));
        return result;
    }
}

// ct 2006-12-15
double * arcsin_rad(double *a)
{
    if (!a || *a < -1 || *a > 1)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = asin(*a);
        return result;
    }
}

// ct 2006-12-15
double * arccos_rad(double *a)
{
    if (!a || *a < -1 || *a > 1)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = acos(*a);
        return result;
    }
}

// ct 2006-12-15
double * arctan_rad(double *a)
{
    if (!a)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = atan(*a);
        return result;
    }
}

// ct 2006-12-15
double * arctan2_rad(double *a, double *b)
{
    if (!a || !b)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = atan2(*a, *b);
        return result;
    }
}

// ct 2006-12-15
double * arccot_rad(double *a)
{
    if (!a)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = 1.0 / atan(*a);
        return result;
    }
}

// ct 2006-12-15
double * sin_deg(double *a)
{
    if (!a)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = sin(*a / 180.0 * M_PI);
        return result;
    }
}

// ct 2006-12-15
double * cos_deg(double *a)
{
    if (!a)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = cos(*a / 180.0 * M_PI);
        return result;
    }
}

// ct 2006-12-15
double * tan_deg(double *a)
{
    if (!a)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = tan(*a / 180.0 * M_PI);
        return result;
    }
}

// ct 2006-12-15
double * cot_deg(double *a)
{
    if (!a)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = 1.0 / (tan(*a / 180.0 * M_PI));
        return result;
    }
}

// ct 2006-12-15
double * arcsin_deg(double *a)
{
    if (!a || *a < -1 || *a > 1)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = asin(*a) / M_PI * 180.0;
        return result;
    }
}

// ct 2006-12-15
double * arccos_deg(double *a)
{
    if (!a || *a < -1 || *a > 1)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = acos(*a) / M_PI * 180.0;
        return result;
    }
}

// ct 2006-12-15
double * arctan_deg(double *a)
{
    if (!a)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = atan(*a) / M_PI * 180.0;
        return result;
    }
}

// ct 2006-12-15
double * arccot_deg(double *a)
{
    if (!a)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = (1.0 / atan(*a)) / M_PI * 180.0;
        return result;
    }
}

// ct 2006-12-15
double * sinhyp(double *a)
{
    if (!a)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = sinh(*a);
        return result;
    }
}

// ct 2006-12-15
double * coshyp(double *a)
{
    if (!a)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = cosh(*a);
        return result;
    }
}

// ct 2006-12-15
double * tanhyp(double *a)
{
    if (!a)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = tanh(*a);
        return result;
    }
}

// ct 2006-12-15
double *cothyp(double *a)
{
    if (!a || *a == 0)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = 1.0 / (tanh(*a));
        return result;
    }
}

// ct 2006-12-15
double * arsinh(double *a)
{
    if (!a)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = log(*a + sqrt((*a * *a) + 1));
        return result;
    }
}

// ct 2006-12-15
double * arcosh(double *a)
{
    if (!a || *a < 1)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = log(*a + sqrt((*a * *a) - 1));
        return result;
    }
}

// ct 2006-12-15
double * artanh(double *a)
{
    if (!a || *a <= -1 || *a >= 1)
	return NULL;
    else {
        double *result = MALLOC(sizeof(double));
        *result = (log((1 + *a) / (1 - *a))) / 2;
        return result;
    }
}

// ct 2006-12-15
double * arcoth(double *a)
{
    if (!a || (*a >= -1 && *a <= 1))
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));

	*result = (log((*a + 1) / (*a - 1))) / 2;
        return result;
    }
}

// ct 2006-12-15
double * f_rand()
{
    double *result = MALLOC(sizeof(double));
    static time_t t = 0;

    if (t == 0) {
	srand((unsigned) time(&t) + getpid());
    }
    *result = (double) rand() / (double) RAND_MAX;
    return result;
}

// ct 2006-12-15
int * f_sign( double *a)
{
    if (!a)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	if (*a == 0) {
	    *result = 0;
        }
	if (*a > 0) {
	    *result = 1;
        }
	if (*a < 0) {
            *result = -1;
        }
        return result;
    }
}

// ct 2006-12-15
double * f_sqrt( double *a)
{
    if (!a)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = sqrt(*a);
        return result;
    }
}

// ct 2006-12-15
double * f_ln( double *a)
{
    if (!a)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = log(*a);
        return result;
    }
}

// ct 2006-12-15
double * f_log( double *a, double *b)
{
    if (!a || !b)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = log(*a) / log(*b);
        return result;
    }
}

// ct 2006-12-15
double * f_log10( double *a)
{
    if (!a)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = log10(*a);
        return result;
    }
}

// ct 2006-12-15
double * f_floor( double *a)
{
    if (!a)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = floor(*a);
        return result;
    }
}

// ct 2006-12-15
double * f_ceiling( double *a)
{
    if (!a)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = ceil(*a);
        return result;
    }
}

// ct 2006-12-15
double * f_frac( double *a)
{
    if (!a)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	if (*a > 0)
	    *result = *a - floor(*a);
	if (*a < 0)
	    *result = *a - ceil(*a);
	if (*a == 0)
  	    *result = 0;
        return result;
    }
}

// ct 2006-12-15
int * f_bin_and(int *a, int *b)
{
    if (!a || !b)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	*result = (*a & *b);
        return result;
    }
}

// ct 2006-12-15
int * f_bin_or(int *a, int *b)
{
    if (!a || !b)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	*result = (*a | *b);
        return result;
    }
}

// ct 2006-12-15
int * f_bin_xor(int *a, int *b)
{
    if (!a || !b)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	*result = (*a ^ *b);
        return result;
    }
}

// ct 2006-12-15
int * f_bin_not(int *a)
{
    if (!a)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	*result = ~(*a);
        return result;
    }
}

// ct 2006-12-15
int * f_bin_shl(int *a, int *b)
{
    if (!a || !b)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	*result = (*a << *b);
        return result;
    }
}

// ct 2006-12-15
int * f_bin_shr(int *a, int *b)
{
    if (!a || !b)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	*result = (*a >> *b);
        return result;
    }
}

// ct 2007-02-05
int * r_getbit(int * num, int * shift)
{
    if (!num || !shift)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	if ((*shift<0) || (*shift>31))
		*result = -1;
	if(((1<<*shift)&(*num))==0)
		*result = 0;
	else
		*result = 1;
        return result;
    }
}

// ct 2007-02-05
int * r_setbit(int * num, int * shift, int * val)
{
    if (!num || !shift || !val)
	return NULL;
    else {
	int *result = MALLOC(sizeof(int));
	if((*shift<0) || (*shift>31) || (*val<0) || (*val>1))
		*result = *num;
	else
	{
		if(*val==1)
			*result = (*num) | (1<<*shift);
		else
			*result = (*num) & (~(1<<*shift));
	}
        return result;
    }
}

// ct 2006-12-15
double * f_power(double *a, double *b)
{
    if (!a || !b)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = pow(*a, *b);
        return result;
    }
}

// ct 2006-12-15
double * f_exp(double *a)
{
    if (!a)
	return NULL;
    else {
	double *result = MALLOC(sizeof(double));
	*result = exp(*a);
        return result;
    }
}

// gh 2007-01-22
char *numinwords(double *value, int *precision, char *language)
{
    if (!value || !precision || !language) {
	return NULL;
    } else {
	char *result = (char *) MALLOC(MAX_STRINGBUFFER_SIZE);
	char num[32], *p;
	int lang, i;

	if (*precision > 10) *precision = 10;
	if (*precision < 0) *precision = 0;
	sprintf(num, "%.10f", *value);
	p = strchr(num, '.');
	if (*precision > 0) {
	    p += (*precision + 1);
	}
	*p = '\0';

	lang = decode_language(language);
	if (lang < 0) {
	    strcpy(result, "???");
	} else {
	    strcpy(result, "***");
	    for (i = 0; num[i]; i++) {
		if (num[i] == '.' || num[i] == ',') {
		    strcat(result, NUM[(11 * (lang + 1)) + 10]);
		} else {
		    strcat(result, NUM[(11 * (lang + 1)) + num[i] - '0']);
		}
		if (num[i + 1]) {
		    strcat(result, "-");
		}
	    }
	    strcat(result, "***");
	}
	return result;
    }
}


// ct 2007-01-28
int * r_div(int *q, int *r)
{
    if (!q || !r) {
	return NULL;
    }
    else {
	int *result = MALLOC(sizeof(int));
        div_t x;
        if (*r == 0)
          *result = 0;
        else {
           x = div(*q, *r);
           *result = x.quot;
        }
        return result;
    }
}

// ct 2007-02-05
double r_z(double * a)
{
  return *a;
}

// ct 2007-02-05
double r_dividezero(double * a, double * b, double * def)
{
  return (*b) ? (*a / *b) : *def;
}

                                                                 math_functions.h                                                                                    0000744 0000000 0000764 00000006750 10756255166 013110  0                                                                                                    ustar   root                            adhoc                                                                                                                                                                                                                  /*****************************************************************************
 * FreeAdhocUDF - copyright (c) 2004 - 2008 adhoc dataservice GmbH
 * Christoph Theuring / Peter Mandrella / Georg Horn
 * <http://www.udf.adhoc-data.de> eMail <udf@adhoc-data.de>
 * based on FreeUDFLibC - copyright (c) 1999 Gregory Deatz
 *
 * File Name:	math_functions.h
 * Description: This header contains the prototype definitions
 *
 * This file is part of FreeAdhocUDF.
 * FreeAdhocUDF is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * FreeAdhocUDF is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with FreeAdhocUDF.  If not, see <http://www.gnu.org/licenses/>. 
*****************************************************************************/

double intern_zahlrunden(double d1, int nk);
char * converttodollar (double *);
double * doubleabs (double *);
double * fact (int *);
char * fixedpoint (double *, int *);
char * fixedpointlang (double *, int *, char *, char *);
int * integerabs (int *);
double * maxnum (double *, double *);
double * minnum (double *, double *);
int * modulo (int *, int *);
int * f_round (double *);
int * f_truncate (double *);
int * isdivisibleby (int*, int*);
int * evenodd (int *);
int * equalfloat (double *, double *);
int * equalinteger (int *, int *);
double * prozente (double *, double *);
double * zahlrunden (double *, int *);
double * roundtoeven (double *, int *);
double * softround (double *, int *);
int * intrandom (int *, int *);
double * doublerandom (int *, int *);
double * sin_rad (double *);
double * cos_rad (double *);
double * tan_rad (double *);
double * cot_rad (double *);
double * arcsin_rad (double *);
double * arccos_rad (double *);
double * arctan_rad (double *);
double * arctan2_rad (double *, double *);
double * arccot_rad (double *);
double * sin_deg (double *);
double * cos_deg (double *);
double * tan_deg (double *);
double * cot_deg (double *);
double * arcsin_deg (double *);
double * arccos_deg (double *);
double * arctan_deg (double *);
double * arccot_deg (double *);
double * sinhyp (double *);
double * coshyp (double *);
double * tanhyp (double *);
double * cothyp (double *);
double * arsinh (double *);
double * arcosh (double *);
double * artanh (double *);
double * arcoth (double *);
double * f_rand();
int * f_sign( double *);
double * f_sqrt( double *);
double * f_ln( double *);
double * f_log( double *, double *);
double * f_log10( double *);
double * f_floor( double *);
double * f_frac( double *);
double * f_ceiling( double *);
int * f_bin_and(int *, int *);
int * f_bin_or(int *, int *);
int * f_bin_xor(int *, int *);
int * f_bin_not(int *);
int * f_bin_shl(int *, int *);
int * f_bin_shr(int *, int *);
double * f_power( double *, double *);
double * f_exp( double *);
char * numinwords(double *, int *, char *);
int * r_div(int *q, int *r);
double r_z(double *);
double r_dividezero(double *, double *, double *);
int * r_getbit(int *, int *);
int * r_setbit(int *, int *, int *);
int *getrandom(int *);
                        md5c.c                                                                                              0000744 0000000 0000764 00000027346 10756254746 010721  0                                                                                                    ustar   root                            adhoc                                                                                                                                                                                                                  /*****************************************************************************
 * FreeAdhocUDF - copyright (c) 2004 - 2008 adhoc dataservice GmbH
 * Christoph Theuring ct / Peter Mandrella pm / Georg Horn gh
 * <http://www.udf.adhoc-data.de> eMail <udf@adhoc-data.de>
 * based on FreeUDFLibC - copyright (c) 1999 Gregory Deatz
 * Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991.
 * All rights reserved.
 *  
 * File Name: md5c.c
 * Description: this module contains MD5 message-digest algorithm
 * for exported functions list see md5c.h 
 * 
 * This file is part of FreeAdhocUDF.
 * FreeAdhocUDF is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * FreeAdhocUDF is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with FreeAdhocUDF.  If not, see <http://www.gnu.org/licenses/>
 * 
 * Additional license of md5c.c   
 * License to copy and use this software is granted provided that it
 * is identified as the "RSA Data Security, Inc. MD5 Message-Digest
 * Algorithm" in all material mentioning or referencing this software
 * or this function.
 *  
 * License is also granted to make and use derivative works provided
 * that such works are identified as "derived from the RSA Data
 * Security, Inc. MD5 Message-Digest Algorithm" in all material
 * mentioning or referencing the derived work.
 *  
 * RSA Data Security, Inc. makes no representations concerning either
 * the merchantability of this software or the suitability of this
 * software for any particular purpose. It is provided "as is"
 * without express or implied warranty of any kind.
 *
 * These notices must be retained in any copies of any part of this
 * documentation and/or software. 
 ***************************************************************************/

#include "md5_global.h"
#include "md5.h"

/* Constants for MD5Transform routine. */

#define S11 7
#define S12 12
#define S13 17
#define S14 22
#define S21 5
#define S22 9
#define S23 14
#define S24 20
#define S31 4
#define S32 11
#define S33 16
#define S34 23
#define S41 6
#define S42 10
#define S43 15
#define S44 21

static void MD5Transform (UINT4 [4], unsigned char [64]);
static void Encode (unsigned char *, UINT4 *, unsigned int);
static void Decode (UINT4 *, unsigned char *, unsigned int);
static void MD5_memcpy (POINTER, POINTER, unsigned int);
static void MD5_memset (POINTER, int, unsigned int);

static unsigned char PADDING[64] = {
  0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};

/* F, G, H and I are basic MD5 functions.
 */
#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
#define G(x, y, z) (((x) & (z)) | ((y) & (~z)))
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define I(x, y, z) ((y) ^ ((x) | (~z)))

/* ROTATE_LEFT rotates x left n bits.
 */
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))

/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
   Rotation is separate from addition to prevent recomputation.
 */
#define FF(a, b, c, d, x, s, ac) { \
 (a) += F ((b), (c), (d)) + (x) + (UINT4)(ac); \
 (a) = ROTATE_LEFT ((a), (s)); \
 (a) += (b); \
  }
#define GG(a, b, c, d, x, s, ac) { \
 (a) += G ((b), (c), (d)) + (x) + (UINT4)(ac); \
 (a) = ROTATE_LEFT ((a), (s)); \
 (a) += (b); \
  }
#define HH(a, b, c, d, x, s, ac) { \
 (a) += H ((b), (c), (d)) + (x) + (UINT4)(ac); \
 (a) = ROTATE_LEFT ((a), (s)); \
 (a) += (b); \
  }
#define II(a, b, c, d, x, s, ac) { \
 (a) += I ((b), (c), (d)) + (x) + (UINT4)(ac); \
 (a) = ROTATE_LEFT ((a), (s)); \
 (a) += (b); \
  }

/* MD5 initialization. Begins an MD5 operation, writing a new context. */
void MD5Init (context)
MD5_CTX *context;                                        /* context */
{
  context->count[0] = context->count[1] = 0;
  /* Load magic initialization constants. */
  context->state[0] = 0x67452301;
  context->state[1] = 0xefcdab89;
  context->state[2] = 0x98badcfe;
  context->state[3] = 0x10325476;
}

/* MD5 block update operation. Continues an MD5 message-digest
   operation, processing another message block, and updating the
   context. */
void MD5Update (context, input, inputLen)
MD5_CTX *context;                                        /* context */
unsigned char *input;                                /* input block */
unsigned int inputLen;                     /* length of input block */
{
  unsigned int i, index, partLen;

  /* Compute number of bytes mod 64 */
  index = (unsigned int)((context->count[0] >> 3) & 0x3F);

  /* Update number of bits */
  if ((context->count[0] += ((UINT4)inputLen << 3))
   < ((UINT4)inputLen << 3))
    context->count[1]++;
  context->count[1] += ((UINT4)inputLen >> 29);

  partLen = 64 - index;

  /* Transform as many times as possible. */
  if (inputLen >= partLen) {
    MD5_memcpy
      ((POINTER)&context->buffer[index], (POINTER)input, partLen);
    MD5Transform (context->state, context->buffer);

    for (i = partLen; i + 63 < inputLen; i += 64)
      MD5Transform (context->state, &input[i]);

    index = 0;
  }
  else
    i = 0;

  /* Buffer remaining input */
  MD5_memcpy
    ((POINTER)&context->buffer[index], (POINTER)&input[i],
     inputLen-i);
}

/* MD5 finalization. Ends an MD5 message-digest operation, writing the
   the message digest and zeroizing the context. */
void MD5Final (digest, context)
unsigned char digest[16];                         /* message digest */
MD5_CTX *context;                                       /* context */
{
  unsigned char bits[8];
  unsigned int index, padLen;

  /* Save number of bits */
  Encode (bits, context->count, 8);

  /* Pad out to 56 mod 64. */
  index = (unsigned int)((context->count[0] >> 3) & 0x3f);
  padLen = (index < 56) ? (56 - index) : (120 - index);
  MD5Update (context, PADDING, padLen);

  /* Append length (before padding) */
  MD5Update (context, bits, 8);

  /* Store state in digest */
  Encode (digest, context->state, 16);

  /* Zeroize sensitive information. */
  MD5_memset ((POINTER)context, 0, sizeof (*context));
}

/* MD5 basic transformation. Transforms state based on block. */
static void MD5Transform (state, block)
UINT4 state[4];
unsigned char block[64];
{
  UINT4 a = state[0], b = state[1], c = state[2], d = state[3], x[16];

  Decode (x, block, 64);

  /* Round 1 */
  FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
  FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
  FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
  FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
  FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
  FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
  FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
  FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
  FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
  FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
  FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
  FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
  FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
  FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
  FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
  FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */

  /* Round 2 */
  GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
  GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
  GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
  GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
  GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
  GG (d, a, b, c, x[10], S22,  0x2441453); /* 22 */
  GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
  GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
  GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
  GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
  GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
  GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
  GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
  GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
  GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
  GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */

  /* Round 3 */
  HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
  HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
  HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
  HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
  HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
  HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
  HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
  HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
  HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
  HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
  HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
  HH (b, c, d, a, x[ 6], S34,  0x4881d05); /* 44 */
  HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
  HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
  HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
  HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */

  /* Round 4 */
  II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
  II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
  II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
  II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
  II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
  II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
  II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
  II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
  II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
  II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
  II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
  II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
  II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
  II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
  II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
  II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */

  state[0] += a;
  state[1] += b;
  state[2] += c;
  state[3] += d;

  /* Zeroize sensitive information. */
  MD5_memset ((POINTER)x, 0, sizeof (x));
}

/* Encodes input (UINT4) into output (unsigned char). Assumes len is
  a multiple of 4. */
static void Encode (output, input, len)
unsigned char *output;
UINT4 *input;
unsigned int len;
{
  unsigned int i, j;

  for (i = 0, j = 0; j < len; i++, j += 4) {
 output[j] = (unsigned char)(input[i] & 0xff);
 output[j+1] = (unsigned char)((input[i] >> 8) & 0xff);
 output[j+2] = (unsigned char)((input[i] >> 16) & 0xff);
 output[j+3] = (unsigned char)((input[i] >> 24) & 0xff);
  }
}

/* Decodes input (unsigned char) into output (UINT4). Assumes len is
  a multiple of 4.
 */
static void Decode (output, input, len)
UINT4 *output;
unsigned char *input;
unsigned int len;
{
  unsigned int i, j;

  for (i = 0, j = 0; j < len; i++, j += 4)
 output[i] = ((UINT4)input[j]) | (((UINT4)input[j+1]) << 8) |
   (((UINT4)input[j+2]) << 16) | (((UINT4)input[j+3]) << 24);
}

/* Note: Replace "for loop" with standard memcpy if possible.
 */

static void MD5_memcpy (output, input, len)
POINTER output;
POINTER input;
unsigned int len;
{
  unsigned int i;

  for (i = 0; i < len; i++)
    output[i] = input[i];
}

/* Note: Replace "for loop" with standard memset if possible.
 */
static void MD5_memset (output, value, len)
POINTER output;
int value;
unsigned int len;
{
  unsigned int i;

  for (i = 0; i < len; i++)
 ((char *)output)[i] = (char)value;
}
                                                                                                                                                                                                                                                                                          md5_global.h                                                                                        0000744 0000000 0000764 00000004616 10756254626 012073  0                                                                                                    ustar   root                            adhoc                                                                                                                                                                                                                  /*****************************************************************************
 * FreeAdhocUDF - copyright (c) 2004 - 2008 adhoc dataservice GmbH
 * Christoph Theuring / Peter Mandrella / Georg Horn
 * <http://www.udf.adhoc-data.de> eMail <udf@adhoc-data.de>
 * based on FreeUDFLibC - copyright (c) 1999 Gregory Deatz
 * Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991.
 * All rights reserved.
 *  
 * File Name: md5_global.h
 * Description: this module contains RSAREF types and constants
 * 
 * This file is part of FreeAdhocUDF.
 * FreeAdhocUDF is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * FreeAdhocUDF is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with FreeAdhocUDF.  If not, see <http://www.gnu.org/licenses/>
 * 
 * Additional license of md5_global.h  
 * License to copy and use this software is granted provided that it
 * is identified as the "RSA Data Security, Inc. MD5 Message-Digest
 * Algorithm" in all material mentioning or referencing this software
 * or this function.
 *  
 * License is also granted to make and use derivative works provided
 * that such works are identified as "derived from the RSA Data
 * Security, Inc. MD5 Message-Digest Algorithm" in all material
 * mentioning or referencing the derived work.
 *  
 * RSA Data Security, Inc. makes no representations concerning either
 * the merchantability of this software or the suitability of this
 * software for any particular purpose. It is provided "as is"
 * without express or implied warranty of any kind.
 *
 * These notices must be retained in any copies of any part of this
 * documentation and/or software. 
 ***************************************************************************/

/* POINTER defines a generic pointer type */
typedef unsigned char *POINTER;

/* UINT2 defines a two byte word */
typedef unsigned short int UINT2;

/* UINT4 defines a four byte word */
typedef unsigned long int UINT4;
                                                                                                                  md5.h                                                                                               0000744 0000000 0000764 00000004760 10756254656 010556  0                                                                                                    ustar   root                            adhoc                                                                                                                                                                                                                  /*****************************************************************************
 * FreeAdhocUDF - copyright (c) 2004 - 2008 adhoc dataservice GmbH
 * Christoph Theuring / Peter Mandrella / Georg Horn
 * <http://www.udf.adhoc-data.de> eMail <udf@adhoc-data.de>
 * based on FreeUDFLibC - copyright (c) 1999 Gregory Deatz
 * Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991.
 * All rights reserved.
 *  
 * File Name: md5c.h
 * Description: this module contains header file for md5c.c
 * 
 * This file is part of FreeAdhocUDF.
 * FreeAdhocUDF is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * FreeAdhocUDF is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with FreeAdhocUDF.  If not, see <http://www.gnu.org/licenses/>
 * 
 * Additional license of md5c.h   
 * License to copy and use this software is granted provided that it
 * is identified as the "RSA Data Security, Inc. MD5 Message-Digest
 * Algorithm" in all material mentioning or referencing this software
 * or this function.
 *  
 * License is also granted to make and use derivative works provided
 * that such works are identified as "derived from the RSA Data
 * Security, Inc. MD5 Message-Digest Algorithm" in all material
 * mentioning or referencing the derived work.
 *  
 * RSA Data Security, Inc. makes no representations concerning either
 * the merchantability of this software or the suitability of this
 * software for any particular purpose. It is provided "as is"
 * without express or implied warranty of any kind.
 *
 * These notices must be retained in any copies of any part of this
 * documentation and/or software. 
 ***************************************************************************/

/* MD5 context. */
typedef struct {
  UINT4 state[4];		/* state (ABCD) */
  UINT4 count[2];		/* number of bits, modulo 2^64 (lsb first) */
  unsigned char buffer[64];	/* input buffer */
} MD5_CTX;

void MD5Init (MD5_CTX *);
void MD5Update (MD5_CTX *, unsigned char *, unsigned int);
void MD5Final (unsigned char [16], MD5_CTX *);
                string_functions.c                                                                                  0000744 0000000 0000764 00000151747 10756537222 013463  0                                                                                                    ustar   root                            adhoc                                                                                                                                                                                                                  /*****************************************************************************
 * FreeAdhocUDF - copyright (c) 2004 - 2008 adhoc dataservice GmbH
 * Christoph Theuring ct / Peter Mandrella pm / Georg Horn gh
 * <http://www.udf.adhoc-data.de> eMail <udf@adhoc-data.de>
 * based on FreeUDFLibC - copyright (c) 1999 Gregory Deatz
 * some code from Robert Loipfinger rl copyright (c) 2000 ADITO Software GmbH
 * some code from rFunc UDF library copyright (c) 1998-2003 Polaris Software
 *
 * File Name:	string_functions.c
 * Description: this module contains UDFs to generate and manipulate strings
 * for exported functions list see string_functions.h
 *
 * This file is part of FreeAdhocUDF.
 * FreeAdhocUDF is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * FreeAdhocUDF is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *                                   
 * You should have received a copy of the GNU Lesser General Public License
 * along with FreeAdhocUDF.  If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include "md5_global.h"
#include "global.h"
#include "md5.h"
#include "string_functions.h"

// intern
// ----------

// ISO-8859-1 to upper case table
static unsigned char StringUpTab [256] =
           {  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
             16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
             32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
             48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
             64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
             80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
             96,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O',
            'P','Q','R','S','T','U','V','W','X','Y','Z',123,124,125,126,127,
            128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
            144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
            160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
            176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
            192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
            208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
            192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
            240,209,210,211,212,213,214,247,216,217,218,219,220,221,222,255 };

// ISO-8859-1 to lower case table
static unsigned char StringLoTab [256] =
           {  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
             16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
             32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
             48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
             64,'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o',
            'p','q','r','s','t','u','v','w','x','y','z', 91, 92, 93, 94, 95,
             96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111,
            112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
            128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
            144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
            160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
            176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
            224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
            208,241,242,243,244,245,246,215,248,249,250,251,252,253,254,223,
            224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
            240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255 };

// rFunc 1999-11-27
// WIN-1251 upper case table
static unsigned char upper_win1251[256] =
       {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,
        0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f,
        0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2a,0x2b,0x2c,0x2d,0x2e,0x2f,
        0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x3b,0x3c,0x3d,0x3e,0x3f,
        0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,
        0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x5b,0x5c,0x5d,0x5e,0x5f,
        0x60,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,
        0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x7b,0x7c,0x7d,0x7e,0x7f,
        0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8a,0x8b,0x8c,0x8d,0x8e,0x8f,
        0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0x9b,0x9c,0x9d,0x9e,0x9f,
        0xa0,0xa1,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xab,0xac,0xad,0xae,0xaf,
        0xb0,0xb1,0xb2,0xb2,0xb4,0xb5,0xb6,0xb7,0xa8,0xb9,0xaa,0xbb,0xbc,0xbd,0xbe,0xaf,
        0xc0,0xc1,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xcb,0xcc,0xcd,0xce,0xcf,
        0xd0,0xd1,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xdb,0xdc,0xdd,0xde,0xdf,
        0xc0,0xc1,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xcb,0xcc,0xcd,0xce,0xcf,
        0xd0,0xd1,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xdb,0xdc,0xdd,0xde,0xdf };

// rFunc 1999-11-27
// WIN-1251 lower case table
static unsigned char lower_win1251[256] =
       {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,
        0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f,
        0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2a,0x2b,0x2c,0x2d,0x2e,0x2f,
        0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x3b,0x3c,0x3d,0x3e,0x3f,
        0x40,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x6b,0x6c,0x6d,0x6e,0x6f,
        0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x5b,0x5c,0x5d,0x5e,0x5f,
        0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x6b,0x6c,0x6d,0x6e,0x6f,
        0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x7b,0x7c,0x7d,0x7e,0x7f,
        0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8a,0x8b,0x8c,0x8d,0x8e,0x8f,
        0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0x9b,0x9c,0x9d,0x9e,0x9f,
        0xa0,0xa1,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xb8,0xa9,0xba,0xab,0xac,0xad,0xae,0xbf,
        0xb0,0xb1,0xb3,0xb3,0xb4,0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xbb,0xbc,0xbd,0xbe,0xbf,
        0xe0,0xe1,0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xeb,0xec,0xed,0xee,0xef,
        0xf0,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa,0xfb,0xfc,0xfd,0xfe,0xff,
        0xe0,0xe1,0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xeb,0xec,0xed,0xee,0xef,
        0xf0,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa,0xfb,0xfc,0xfd,0xfe,0xff };


// rFunc 2001-05-31
// WIN-1251 latin table
static unsigned char latin_win1251[256] =
       {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,
        0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f,
        0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2a,0x2b,0x2c,0x2d,0x2e,0x2f,
        0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x3b,0x3c,0x3d,0x3e,0x3f,
        0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,
        0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x5b,0x5c,0x5d,0x5e,0x5f,
        0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x6b,0x6c,0x6d,0x6e,0x6f,
        0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x7b,0x7c,0x7d,0x7e,0x7f,
        0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8a,0x8b,0x8c,0x8d,0x8e,0x8f,
        0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0x9b,0x9c,0x9d,0x9e,0x9f,
        0xa0,0xa1,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0x45,0xa9,0x45,0xab,0xac,0xad,0xae,0x49,
        0xb0,0xb1,0x49,0x69,0xb4,0xb5,0xb6,0xb7,0x65,0xb9,0x65,0xbb,0xbc,0xbd,0xbe,0x69,
        0x41,0x42,0x56,0x47,0x44,0x45,0x4a,0x5a,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,0x50,
        0x52,0x53,0x54,0x55,0x46,0x48,0x43,0x43,0x53,0x53,0x5f,0x49,0x5f,0x45,0x55,0x4a,
        0x61,0x62,0x76,0x67,0x64,0x65,0x6a,0x7a,0x69,0x6a,0x6b,0x6c,0x6d,0x6e,0x6f,0x70,
        0x72,0x73,0x74,0x75,0x66,0x68,0x63,0x63,0x73,0x73,0x5f,0x69,0x5f,0x65,0x75,0x6a };

// used in gsoundex
static char * TabGruppenVon    = "SCSZCZTZTSDSKSQUPFPHUEAEOEEIEYEUAUOU";
static char * TabGruppenNach   = "C C C C C C X KVV V Y E Ö AYAYOYA@@ ";
static char * TabErsVon        = "ZKGQÄÜIJßFWPT@ÁÀÈÉÚÙÒÓÍÌ";
static char * TabErsNach       = "CCCCEYYYSVVBDUAAEEUUOOYY";
static char * GueltigeZeichen1 = "ABCDLMNORSUVWXYÖ";
static char * GueltigeZeichen2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÜ";

// pm 2005-10-03
// used in stripstring and stripstringhold
int findchar (char c, char *sz)
{
  int i;
  int len = strlen(sz);

  for (i = 0 ;
     (i < len) && (c != sz[i]) ;
     i++) ;

  if (i == len)
    return 0;
  else
    return -1;
}

// pm 2005-10-03
// used in replacestring
static int strincomp(char *s1, char *s2, int nmax)
{
  while (*s1 && StringUpTab[(int) *s1] == StringUpTab[(int) *s2] && nmax)
    s1++, s2++, nmax--;

  if (nmax == 0)
    return 0;
  else
    return (StringUpTab[(int) *s1] - StringUpTab[(int) *s2]);
}

// Implementations
// ----------

// ct 2006-11-20 implementation of NULL for FB 2.0
char * character (int *c)
{
  if (!c)
    return NULL;
  else
  {
    char *sz = (char *) MALLOC (2);
    sz[0] = (char) *c;
    sz[1] = (char) 0;

    return sz;
  }
}

char * crlf ()
{
  char * sz = (char *) MALLOC (3);
  sz[0] = (char) 13;
  sz[1] = (char) 10;
  sz[2] = (char) 0;
  return sz;
}

// ct 2006-02-22
char * lf ()
{
  char * sz = (char *) MALLOC (2);
  sz[0] = (char) 10;
  sz[1] = (char) 0;
  return sz;
}

// ct 2006-10-05
char * tab ()
{
  char * sz = (char *) MALLOC (2);
  sz[0] = (char) 9;
  sz[1] = (char) 0;
  return sz;
}

// ct 2006-10-05
char * nbsp ()
{
  char * sz = (char *) MALLOC (2);
  sz[0] = (char) 160;
  sz[1] = (char) 0;
  return sz;
}

// ct 2006-10-05
char * dqm ()
{
  char * sz = (char *) MALLOC (2);
  sz[0] = (char) 34;
  sz[1] = (char) 0;
  return sz;
}

// ct 2006-10-05
char * sqm ()
{
  char * sz = (char *) MALLOC (2);
  sz[0] = (char) 39;
  sz[1] = (char) 0;
  return sz;
}

// ct 2006-11-20 implementation of NULL for FB 2.0
char * encryptmd5 (char *sz)
{
  if(!sz)
    return NULL;
  else
  {
    MD5_CTX context;
    unsigned char digest[16];
    int len = strlen (sz);
    unsigned int i;
    char * sz_return = (char *) MALLOC (33);

    sz_return[32] = (char) 0;

    /* Compute the hash */
    MD5Init (&context);
    MD5Update (&context, (unsigned char*) sz, len);
    MD5Final (digest, &context);

    for (i = 0; i < 16; i++)
      sprintf (&sz_return[i*2], "%02x", digest[i]);
    return sz_return;
  }
}

// ct 2006-11-20 implementation of NULL for FB 2.0
// gh 2007-01-17 intercept negativ values for count 
char * left (char *sz, int *count)
{
  if(!sz || !count)
    return NULL;
  else
  {
    int i;
    int c = (*count > 0) ? *count : 0;
    int len = (strlen(sz) < c) ? strlen(sz) : c;
    char * sz_result = (char *) MALLOC (len + 1);

    for (i = 0 ; i < len ; i++)
      sz_result[i] = sz[i];

    sz_result[len] = (char) 0;
    return sz_result;
  }
}

// ct 2006-11-20 implementation of NULL for FB 2.0 
// ct 2007-01-22 intercept negativ values for count
char * right (char *sz, int *count)
{
  if(!sz || !count)
    return NULL;
  else
  {
    int c = (*count > 0) ? *count : 0;
    int len = strlen(sz);
    char * sz_result = (char *) MALLOC (c + 1);
    int i, j;

    for (j = 0, i = (c > len) ? 0 : len - c ;
        i < len ; i++, j++)
      sz_result[j] = sz[i];

    sz_result[j] = (char) 0;
    return sz_result;
  }
}

// ct 2006-11-20 implementation of NULL for FB 2.0
// gh 2007-01-17 intercept negativ values for count 
char * mid (char *sz, int *index, int *count)
{
  if(!sz || !index || !count)
    return NULL;
  else
  {
    int ind = (*index > 0) ? *index : 0;
    int c = (*count > 0 && *index >= 0) ? *count : 0;
    int len = strlen(sz);
    char * sz_result = (char *) MALLOC (c + 1);
    int i;

    for (i = ind ; (i < len) && (i - ind < c); i++)
      sz_result[i - ind] = sz[i];
    sz_result[i - ind] = (char) 0;

    return sz_result;
  }
}

// pm 2005-10-03
// f_mid1 = f_copy = f_mid with turned parameters
char * mid1 (char *sz, int *from, int *count)
{
  int f = *from - 1;
  return mid(sz, &f, count);
}


// pm 2005-10-03
char * space (int *n)
{
  return strofchar(" ", n);
}

// ct 2006-11-20 implementation of NULL for FB 2.0
// line_wrap algorithm
/*
 * 1. Get the length of the string.
 * 2. If "the rest" of the string is smaller than col_width, just return
 *    it.
 * 3. Otherwise, let 'j' be the end of the column, and decrement j to
 *    a word boundary.
 *    a. Find a word boundary.
 *    b. If j = i (meaning the word is too long), then the word has
 *       has to be chopped.
 */
char * linewrap (char *sz, int *index, int *col_width)
{
  if(!sz || !index || !col_width)
    return NULL;
  else
  {
    int len = strlen(sz); /* (1) */
    int i = *index;
    int j;
    char * sz_result;

    if ((len - i) <= *col_width) /* (2) */
      j = len - i;
    else {
      j = i + *col_width - 1;
      while (j > i && !isspace(sz[j]))
        j--; /* (2a) */
      if (j == i)
        j = *col_width;
      else
        j = j - i + 1;
    }

    sz_result = (char *) MALLOC(j + 1);
    for (i = 0 ; i < j ; i++)
      sz_result[i] = sz[i + *index];
    sz_result[j] = '\0';
    return sz_result;
  }
}

// ct 2006-11-20 implementation of NULL for FB 2.0
char * ltrim (char *sz)
{
  if(!sz)
    return NULL;
  else
  {
    int len = strlen(sz);
    char * sz_result = (char *) MALLOC (len + 1);
    int i;

    for (i = 0 ;
       (i < len) && isspace(sz[i]) ;
       i++) ;

    sprintf(sz_result, "%s", &sz[i]);
    return sz_result;
  }
}

// ct 2006-11-20 implementation of NULL for FB 2.0 
char * rtrim (char *sz)
{
  if(!sz)
    return NULL;
  else
  {

    int len = strlen(sz);
    char * sz_result = (char *) MALLOC (len + 1);
    int i, j;

    for (i = len - 1 ;
       (i >= 0) && isspace(sz[i]) ;
       i--) ;

    for (j = 0 ; j <= i ; j++)
      sz_result[j] = sz[j];
    sz_result[j] = (char) 0;

    return sz_result;
  }
}

// ct 2006-11-20 implementation of NULL for FB 2.0
char * lrtrim (char *sz)
{
  if(!sz)
    return NULL;
  else
  {
    int len = strlen(sz);
    char * sz_result = (char *) MALLOC (len + 1);
    int i, j, k;

    for (i = 0 ;
       (i < len) && isspace(sz[i]) ;
       i++) ;

    for (j = len - 1 ;
       (j >= 0) && isspace(sz[j]) ;
       j--) ;

    for (k = i ; k <= j ; k++)
      sz_result[k - i] = sz[k];
    sz_result[k - i] = (char) 0;

    return sz_result;
  }
}

// ct 2006-11-20 implementation of NULL for FB 2.0
char * padleft (char *sz, char *sz_pad, int *size)
{
  if(!sz || !sz_pad || !size)
    return NULL;
  else
  {
    int len_sz = strlen(sz);
    int len_sz_pad = strlen(sz_pad);
    int len_sz_result = *size > len_sz ? *size : len_sz;
    char * sz_result = (char *) MALLOC (len_sz_result + 1);
    int i, j;

    sz_result[len_sz_result] = (char) 0;

    for (i = len_sz - 1 ; i >= 0 ; i--)
      sz_result[len_sz_result - (len_sz - i - 1) - 1] = sz[i];

    for (i = len_sz_result - (len_sz - i - 1) - 1 ;
       i >= 0 ;
       ) {
      for (j = len_sz_pad - 1 ;
	 (j >= 0) && (i >= 0) ;
	 j--, i--)
      sz_result[i] = sz_pad[j];
    }

    return sz_result;
  }
}

// ct 2007-02-03 version for rfunc with swapped parameter 2 and 3
char * r_padleft (char *sz, int *size, char *sz_pad)
{
  if(!sz || !sz_pad || !size)
    return NULL;
  else
  {
    int len_sz = strlen(sz);
    int len_sz_pad = strlen(sz_pad);
    int len_sz_result = *size > len_sz ? *size : len_sz;
    char * sz_result = (char *) MALLOC (len_sz_result + 1);
    int i, j;

    sz_result[len_sz_result] = (char) 0;

    for (i = len_sz - 1 ; i >= 0 ; i--)
      sz_result[len_sz_result - (len_sz - i - 1) - 1] = sz[i];

    for (i = len_sz_result - (len_sz - i - 1) - 1 ;
       i >= 0 ;
       ) {
      for (j = len_sz_pad - 1 ;
	 (j >= 0) && (i >= 0) ;
	 j--, i--)
      sz_result[i] = sz_pad[j];
    }

    return sz_result;
  }
}

// ct 2006-11-20 implementation of NULL for FB 2.0 
char * padright (char *sz, char *sz_pad, int *size)
{
  if(!sz || !sz_pad || !size)
    return NULL;
  else
  {
    int len_sz = strlen(sz);
    int len_sz_pad = strlen(sz_pad);
    int len_sz_result = *size > len_sz ? *size : len_sz;
    char * sz_result = (char *) MALLOC (len_sz_result + 1);
    int i, j;

    sz_result[len_sz_result] = (char) 0;

    for (i = 0 ; i < len_sz ; i++)
      sz_result[i] = sz[i];

    while (i < len_sz_result)
      for (j = 0 ;
	 (j < len_sz_pad) && (i < len_sz_result) ;
	 j++, i++)
        sz_result[i] = sz_pad[j];

    return sz_result;
  }
}

// ct 2007-02-03 version for rfunc with swapped parameter 2 and 3
char * r_padright (char *sz, int *size, char *sz_pad)
{
  if(!sz || !sz_pad || !size)
    return NULL;
  else
  {
    int len_sz = strlen(sz);
    int len_sz_pad = strlen(sz_pad);
    int len_sz_result = *size > len_sz ? *size : len_sz;
    char * sz_result = (char *) MALLOC (len_sz_result + 1);
    int i, j;

    sz_result[len_sz_result] = (char) 0;

    for (i = 0 ; i < len_sz ; i++)
      sz_result[i] = sz[i];

    while (i < len_sz_result)
      for (j = 0 ;
	 (j < len_sz_pad) && (i < len_sz_result) ;
	 j++, i++)
        sz_result[i] = sz_pad[j];

    return sz_result;
  }
}

// gh 2006-11-23
// gh 2006-11-23 implementation of NULL for FB 2.0 
char *padcenter(char *sz, char *sz_pad, int *size)
{
    if (!sz || !sz_pad || !size) {
	return NULL;
    } else {
	int len_sz = strlen(sz);
	int len_sz_pad = strlen(sz_pad);
	int len_sz_result = *size > len_sz ? *size : len_sz;
	char *sz_result = (char *) MALLOC(len_sz_result + 1);
	char *p = sz_result;
	int left, right;

	if (len_sz >= *size) {
	    /* nothing to pad at all */
	    strcpy(sz_result, sz);
	    return sz_result;
	}

	if (((*size - len_sz) % 2) == 0) {
	    /* even number of chars to pad */
	    left = (*size - len_sz) / 2;
	    right = left;
	} else {
	    /* odd: one more char on the left side */
	    left = (*size - len_sz + 1) / 2;
	    right = left - 1;
	}

	/* pad left */
	while (left > 0) {
	    int l = (len_sz_pad < left) ? len_sz_pad : left;
	    strncpy(p, sz_pad, l);
	    left -= l;
	    p += l;
	}

	/* copy string */
	strcpy(p, sz);
	p += len_sz;

	/* pad right */
	while (right > 0) {
	    int l = (len_sz_pad < right) ? len_sz_pad : right;
	    strncpy(p, sz_pad, l);
	    right -= l;
	    p += l;
	}
        *p = '\0';

	/* faedisch */
	return sz_result;
    }
}

// gh 2006-04-26
// ct 2006-11-20 implementation of NULL for FB 2.0 
/* replace -
 *   I'm sure there is a *much* more efficient way to do this, but
 *   I don't really care that much because this should be fast enough.
 *   If anybody cares to provide me with some faster/more efficient code,
 *   I'd be glad to include it here. */
char * replace (char *sz, char *sz_replace, char *sz_with)
{
  if(!sz || !sz_replace || !sz_with)
    return NULL;
  else
  {

    int len_sz = strlen(sz);
    int len_sz_replace = strlen(sz_replace);
    int len_sz_with = strlen(sz_with);
    int i, j;
    int k = 0;
    char sz_res[MAX_STRINGBUFFER_SIZE];
    char * sz_result;

    for (i = 0 ; i < len_sz ; ) {
      if (strncmp(&sz[i], sz_replace, len_sz_replace) == 0) {
        for (j = 0 ; j < len_sz_with ; j++, k++)
	  sz_res[k] = sz_with[j];
        i += len_sz_replace;
      }
      else {
        sz_res[k++] = sz[i];
        i++;
      }
    }
    sz_res[k] = (char) 0;
    sz_result = (char *) MALLOC (strlen(sz_res) + 1);
    sprintf(sz_result, "%s", sz_res);
    return sz_result;
  }
}

// ct 2006-11-20 implementation of NULL for FB 2.0
char * soundex (char *sz)
{
  if(!sz)
    return NULL;
  else
  {

    int i, j;
    char code;
    int len = strlen(sz);
    char * sz_result = (char *) MALLOC (6);
    sz_result[0] = ' ';
    sz_result[1] = '0';
    sz_result[2] = '0';
    sz_result[3] = '0';
    sz_result[4] = '0';
    sz_result[5] = (char) 0;

    if (strlen(sz) != 0) {
      sz_result[0] = toupper(sz[0]);

      j = 1;
      i = 1;
      while (i < len && j < 5) {
        switch(sz[i]) {
        case 'B':
        case 'F':
        case 'P':
        case 'V':
        case 'b':
        case 'f':
        case 'p':
        case 'v':
	  code = '1'; break;
        case 'C':
        case 'G':
        case 'J':
        case 'K':
        case 'Q':
        case 'S':
        case 'X':
        case 'Z':
        case 'c':
        case 'g':
        case 'j':
        case 'k':
        case 'q':
        case 's':
        case 'x':
        case 'z':
	  code = '2'; break;
        case 'D':
        case 'T':
        case 'd':
        case 't':
	  code = '3'; break;
        case 'L':
        case 'l':
	  code = '4'; break;
        case 'M':
        case 'N':
        case 'm':
        case 'n':
	  code = '5'; break;
        case 'R':
        case 'r':
	  code = '6'; break;
        default:
	  code = '0';
        }

        if (code != '0' && code != sz_result[j - 1])
	  sz_result[j++] = code;
        i++;
      }
    }
    return sz_result;
  }
}

// rl 2000
// pm 2005-10-22 fixed memory leaks
// ct 2006-11-20 implementation of NULL for FB 2.0
// ct 2007-11-13 bug in upper: missed 0-byte
// gh 2007-11-23 fixed more memory leaks
char *gsoundex(char *sz)
{
    if (!sz) {
	return NULL;
    } else {
	int i, j, len;
	char *ps, *pd;
	char sz_subs[3];
	char *sz_result = upper(sz);

	// ---> folgende Zeilen ersetzen stripstringhold:
	ps = sz_result;
	pd = sz_result;
	while (*ps) {
	    if (strchr(GueltigeZeichen2, *ps) != NULL) {
		*pd++ = *ps;
	    }
	    ps++;
	}
	*pd = 0;
	// <---

	len = strlen(sz_result);
	for (i = 0; i < len; i++) {
	    strncpy(sz_subs, sz_result + i, 2);
	    sz_subs[2] = 0;
	    ps = strstr(TabGruppenVon, sz_subs);
	    j = ps ? (ps - TabGruppenVon) : -1;
	    if (j % 2 == 0 && strlen(sz_subs) == 2) {
		sz_result[i] = TabGruppenNach[j];
		sz_result[i + 1] = TabGruppenNach[j + 1];
	    }
	}

	len = strlen(sz_result);
	for (i = 0; i < len; i++) {
	    sz_subs[0] = sz_result[i];
	    sz_subs[1] = 0;
	    ps = strstr(TabErsVon, sz_subs);
	    j = ps ? (ps - TabErsVon) : -1;
	    if (j != -1) {
		sz_result[i] = TabErsNach[j];
	    }
	}

	// ---> folgende Zeilen ersetzen stripstringhold:
	ps = sz_result;
	pd = sz_result;
	while (*ps) {
	    if (strchr(GueltigeZeichen1, *ps) != NULL) {
		*pd++ = *ps;
	    }
	    ps++;
	}
	*pd = 0;
	// <---

	// ---> folgende Zeilen ersetzen die nachfolgende Schleife
	ps = sz_result;
	pd = sz_result;
	while (*ps) {
	    if (*ps != *(ps + 1))
		*pd++ = *ps;
	    ps++;
	}
	*pd = 0;
	// <---

	/* for (i = 0; i < strlen(sz_result) - 1; i++) {
	    if (sz_result[i] == sz_result[i + 1]) {
		sz_result = strrm(sz_result, &i);
	    }
	} */

	return sz_result;
    }
}

// ct 2006-11-20 implementation of NULL for FB 2.0
int * stringlength (char *sz)
{
  if(!sz)
    return NULL;
  else
  {
//    int *result = MALLOC(sizeof(int));
    int *result = MALLOC(sizeof(int));
    *result = strlen(sz);
    return result;
  }
}

// ct 2006-11-20 implementation of NULL for FB 2.0
char * stripstring (char *sz, char *sz_strip_chars)
{
  if(!sz || !sz_strip_chars)
    return NULL;
  else
  {

    int i;
    int j = 0;
    int len = strlen(sz);
    char * sz_result = (char *) MALLOC (len + 1);

    for (i = 0 ; i < len ; i++)
      if (!findchar(sz[i], sz_strip_chars))
      {
        sz_result[j] = sz[i];
        j++;
      }
    sz_result[j] = (char) 0;
    return sz_result;
  }
}

// rl 2000
// ct 2006-11-20 implementation of NULL for FB 2.0 
char * stripstringhold (char *sz, char *sz_strip_chars)
{
  if(!sz || !sz_strip_chars)
    return NULL;
  else
  {

    int i;
    int j = 0;
    int len = strlen(sz);
    char * sz_result = (char *) MALLOC (len + 1);

    for (i = 0 ; i < len ; i++)
      if (findchar(sz[i], sz_strip_chars))
      {
        sz_result[j] = sz[i];
        j++;
      }
    sz_result[j] = (char) 0;
    return sz_result;
  }
}

// pm 2005-10-16
char * digits(char *sz)
{
  return stripstringhold(sz,"0123456789");
}

// pm 2004-08-21 rewritten; swapped parameters
// ct 2006-11-20 implementation of NULL for FB 2.0
int * substr (char *sz_search, char *sz)
{
  if(!sz_search || !sz)
    return NULL;
  else
  {
    int *result = MALLOC(sizeof(int));
    char * pc = strstr(sz_search,sz);
    if (pc == NULL)
      *result = -1;
    else
      *result = pc - sz_search;
    return result;
  }
}

// ct 2006-11-30 version with NULL instead of -1
int *substrnull(char *sz_search, char *sz)
{
    if (!sz_search || !sz) {
	return NULL;
    } else {
	char *pc = strstr(sz_search, sz);
	if (pc == NULL) {
	    return NULL;
	} else {
	    int *result = MALLOC(sizeof(int));
	    *result = pc - sz_search;
	    return result;
	}
    }
}

// gh 2006-03-06 the same as above only swapped parameters
// ct 2006-11-20 implementation of NULL for FB 2.0 
int *strsub(char *sz, char *sz_search)
{
    if (!sz || !sz_search) {
	return NULL;
    } else {
	int *result = MALLOC(sizeof(int));
	char *pc = strstr(sz_search, sz);
	if (pc == NULL) {
	    *result = -1;
	} else {
	    *result = pc - sz_search;
	}
	return result;
    }
}

// ct 2007-02-03
int *strpos(char *sz, char *sz_search)
{
    if (!sz || !sz_search) {
	return NULL;
    } else {
	int *result = MALLOC(sizeof(int));
	char *pc = strstr(sz_search, sz);
	if (pc == NULL) {
	    *result = 0;
	} else {
	    *result = pc - sz_search + 1;
	}
	return result;
    }
}

// ct 2006-11-30 version with NULL instead of -1
int *strsubnull(char *sz, char *sz_search)
{
    if (!sz || !sz_search) {
	return NULL;
    } else {
	char *pc = strstr(sz_search, sz);
	if (pc == NULL) {
	    return NULL;
	} else {
	    int *result = MALLOC(sizeof(int));
	    *result = pc - sz_search;
	    return result;
	}
    }
}

// rl 2000
// pm 2004-08-23 rewritten
// ct 2006-11-20 implementation of NULL for FB 2.0
// ct 2007-11-13 bug: missed 0-byte
char * lower (char *sz)
{
  if(!sz)
    return NULL;
  else
  {

    int len = strlen(sz);
    char * sz_result = (char *) MALLOC (len + 1);
    int i;

    for (i=0; i <= len; i++)
      sz_result[i] = StringLoTab[(unsigned char)sz[i]];

    sz_result[len] = (char) 0;
    return sz_result;
  }
}

// rl 2000
// pm 2004-08-23 rewritten
// ct 2006-11-20 implementation of NULL for FB 2.0
// ct 2007-11-13 bug: missed 0-byte
char * upper (char *sz)
{
  if(!sz)
    return NULL;
  else
  {
    int len = strlen(sz);
    char * sz_result = (char *) MALLOC (len + 1);
    int i;

    for (i=0; i <= len; i++)
      sz_result[i] = StringUpTab[(unsigned char)sz[i]];

    sz_result[len] = (char) 0;
    return sz_result;
  }
}

// ct 2007-11-28
// only to use with win1251
// similar to rFunc fn_rupper
char * rupper (char *sz)
{
  if(!sz)
    return NULL;
  else
  {
    int len = strlen(sz);
    char * sz_result = (char *) MALLOC (len + 1);
    int i;

    for (i=0; i <= len; i++)
      sz_result[i] = upper_win1251[(unsigned char)sz[i]];

    sz_result[len] = (char) 0;
    return sz_result;
  }
}

// ct 2007-11-28
// only to use with win1251
// similar to rFunc fn_rlower
char * rlower (char *sz)
{
  if(!sz)
    return NULL;
  else
  {

    int len = strlen(sz);
    char * sz_result = (char *) MALLOC (len + 1);
    int i;

    for (i=0; i <= len; i++)
      sz_result[i] = lower_win1251[(unsigned char)sz[i]];

    sz_result[len] = (char) 0;
    return sz_result;
  }
}

// ct 2007-11-28
// only to use with win1251
// similar to rFunc fn_rlatin
char * rlatin (char *sz)
{
  if(!sz)
    return NULL;
  else
  {

    int len = strlen(sz);
    char * sz_result = (char *) MALLOC (len + 1);
    int i;

    for (i=0; i <= len; i++)
      sz_result[i] = latin_win1251[(unsigned char)sz[i]];

    sz_result[len] = (char) 0;
    return sz_result;
  }
}

// pm 2004-08-21 special characters enabled
// ct 2006-11-20 implementation of NULL for FB 2.0
// ct 2007-01-18 bug with input upper characters
char * propercase (char *sz)
{
  if(!sz)
    return NULL;
  else
  {

    int len = strlen(sz);
    char * sz_result = (char *) MALLOC (len + 1);
    int i;
    int word_begin = 1;

    for (i = 0 ; i < len ; i++)
    {
      if ((isalnum(sz[i]) || (unsigned char)(sz[i])>=192) && word_begin)
      {
        word_begin = 0;
        sz_result[i] = StringUpTab [(unsigned char)sz[i]];
      }
      else
      if (!isalnum(sz[i]) && (unsigned char)(sz[i])<192)
      {
        word_begin = 1;
        sz_result[i] = sz[i];
      }
      else
      {
        sz_result[i] = StringLoTab [(unsigned char)sz[i]];
      }
    }
    sz_result[len] = (char) 0;
    return sz_result;
  }
}

// rl 2000
// pm 2004-08-21 changed
// ct 2006-11-20 implementation of NULL for FB 2.0 
char * telefonnr (char *sz, int *asterisk)
{
  if(!sz || !asterisk)
    return NULL;
  else
  {
    int len = strlen(sz);
    char * sz_result = (char *) MALLOC (len + 1);
    int m = 0;
    int i;
    int a = *asterisk;
    for (i = 0; i < len; i++)
    {
      if ((sz[i] >= '0' && sz[i] <= '9') || (sz[i] == '+' && m==0))
      {
        sz_result[m] = sz[i];
        m++;
      }
    }

    if (m < a) m = a;
    while (a)
    {
      sz_result[m-a] = '*';
      a--;
    }

    sz_result[m] = (char) 0;
    return sz_result;
  }
}

// rl 2001
// ct 2006-11-20 implementation of NULL for FB 2.0 
char * aif (char *p1, char *o, char *p2, char *t, char *e)
{
  if(!p1 || !o || !p2 || !t || !e)
    return NULL;
  else
  {

        int len = (strlen(t) > strlen(e)) ? strlen(t) : strlen(e);
        char * sz_result = (char *) MALLOC (len+1);
        float w1, w2;
        int erg;
        int ergebnis = 0;

        if (o[0] == 'n'){

                w1 = atof(p1);
                w2 = atof(p2);

                if (strcmp(o,"n=") == 0){
                        if (w1 == w2)
                                ergebnis = 1;
                }
                else if (strcmp(o, "n<>") == 0){
                        if (w1 != w2)
                                ergebnis = 1;
                }
                else if (strcmp(o, "n<") == 0){
                        if (w1 < w2)
                                ergebnis = 1;
                }
                else if (strcmp(o, "n>") == 0){
                        if (w1 > w2)
                                ergebnis = 1;
                }
                else if (strcmp(o, "n<=") == 0){
                        if (w1 <= w2)
                                ergebnis = 1;
                }
                else if (strcmp(o, "n>=") == 0){
                        if (w1 >= w2)
                                ergebnis = 1;
                }
        }
        else{
                erg = strcmp(p1, p2);

                if (strcmp(o,"=") == 0){
                        if (erg == 0)
                                ergebnis = 1;
                }
                else if (strcmp(o, "<>") == 0){
                        if (erg != 0)
                                ergebnis = 1;
                }
                else if (strcmp(o, ">") == 0){
                        if (erg > 0)
                                ergebnis = 1;
                }
                else if (strcmp(o, "<") == 0){
                        if (erg < 0)
                                ergebnis = 1;
                }
                else if (strcmp(o, ">=") == 0){
                        if (erg >= 0)
                                ergebnis = 1;
                }
                else if (strcmp(o, "<=") == 0){
                        if (erg <= 0)
                                ergebnis = 1;
                }
        }


        if (ergebnis == 1){
                strcpy(sz_result,t);
                len = strlen(t);
        }
        else{
                strcpy(sz_result,e);
                len = strlen(e);
        }

        sz_result[len] = (char) 0;

    return sz_result;
  }
}

// ct 2006-11-20 implementation of NULL for FB 2.0 
// ct 2007-01-17 intercept negativ values for anz 
char * strcopy (char *sz, int *indx, int *anz)
{
  if(!sz || !indx || !anz)
    return NULL;
  else
  {

    int c = (*anz > 0) ? *anz : 0;
    int i;
    char * sz_result = (char *) MALLOC (c + 1);

    if (strlen(sz) < *indx + c)
      c = strlen(sz) - *indx;

    for (i=*indx; i < *indx + c; i++)
      sz_result[i-*indx] = sz[i];

    sz_result[c] = (char) 0;

    return sz_result;
  }
}

// ct 2006-11-20 implementation of NULL for FB 2.0 
char * strrm(char *sz, int *indx)
{
  if(!sz || !indx || *sz == 0)
    return NULL;
  else
  {
        int i,j;
        char * sz_result = (char *) MALLOC (strlen(sz));
        j=0;

        for (i=0; i<strlen(sz);i++){
                if (i != *indx)
                {
                        sz_result[j] = sz[i];
                        j++;
                }
        }

    sz_result[strlen(sz)-1] = (char) 0;

    return sz_result;
  }
}


// pm 2005-10-03
// ct 2006-11-20 implementation of NULL for FB 2.0
int * equalstring (char *sz1, char *sz2)
{
  if(!sz1 || !sz2)
    return NULL;
  else
  {
    int *result = MALLOC(sizeof(int));
    *result = (strcmp(sz1,sz2) == 0);
    return result;
  }
}


// pm 2005-10-03
// gh 2006-03-02 edit for äöü
// ct 2006-11-20 implementation of NULL for FB 2.0
char * findword (char *sz, int *n)
{
  if(!sz || !n)
    return NULL;
  else {
    char *sz_result;
    char *last;

    if (*n < 0 || *n >= strlen(sz))
      return NULL;
    else {
      sz += *n;
      while (*sz != 0 && *sz == ' ')
        sz++;
      last = sz;
      while (*last != 0 && *last != ' ')
        last++;

      sz_result = (char*) MALLOC(last - sz + 1);
      strncpy(sz_result, sz, last-sz);
      sz_result[last-sz] = 0;
    }

    return sz_result;
  }
}

// pm 2005-10-03
// gh 2006-03-01 added do_malloc
// ct 2006-11-20 implementation of NULL for FB 2.0
// gh 2007-08-22 removed do_malloc in call intern_replacestring
// ct 2007-12-03 (re)added do_malloc 
char *replacestring(char *s, char *subs, char *replby, int *all, int *case_insensitive)
{
  if(!s || !subs || !replby || !all || !case_insensitive)
    return NULL;
  else
    return intern_replacestring(s, subs, replby, all, case_insensitive, 1);
}

// gh 2007-08-22 removed do_malloc
// ct 2007-12-03 (re)added do_malloc 
char *intern_replacestring (char *s, char *subs, char *replby, int *all, int *case_insensitive, int do_MALLOC)
{
  char *sz_result;
  char *pd;

  int sl = strlen(s);
  int ssl = strlen(subs);
  int rl = strlen(replby);
  int done = 0;

  if (ssl == 0) {
    sz_result = do_MALLOC ? MALLOC(1) : malloc(1);
    *sz_result = 0;
  } else {
    int len = (sl / ssl + 1) * (rl + 1) + 1;
    sz_result = do_MALLOC ? MALLOC(len) : malloc(len);

    pd = sz_result;
    while (*s)
      if ( (!done || *all) &&
           ((!*case_insensitive && strncmp(s, subs, ssl) == 0) ||
            (*case_insensitive && strincomp(s, subs, ssl) == 0)) ) {

        strcpy(pd, replby);
        pd += rl;
        s += ssl;
        done = 1;
      } else {
        *pd++ = *s++;
      }
    *pd = 0;
  }
  return sz_result;
}

// pm 2005-10-03
// ct 2006-11-20 implementation of NULL for FB 2.0 
char * dollarval (double *value)
{
  if(!value)
    return NULL;
  else
  {
    char * sz_result = (char *) MALLOC (35);
    sprintf(sz_result, "$%.2f", *value);
    return sz_result;
  }
}

// pm 2005-10-03
// ct 2006-11-20 implementation of NULL for FB 2.0
char * euroval (double *value)
{
  if(!value)
    return NULL;
  else
  {
    char * sz_result = (char *) MALLOC (35);
    sprintf(sz_result, "%.2f EUR", *value);
    return sz_result;
  }
}

// pm 2005-10-03
// gh 2006-03-02 edit for äöü
// ct 2006-11-20 implementation of NULL for FB 2.0
// ct 2006-11-30 returns NULL insted of 0 if not found
char *findnthword(char *sz, int *n)
{
    if (!sz || !n) {
	return NULL;
    } else {
	char *pw;
	int len;

	while (*sz && *n >= 0) {
	    while (*sz && *sz == ' ')
		sz++;
	    if (*n > 0)
		while (*sz && *sz != ' ')
		    sz++;
	    (*n)--;
	}

	pw = sz;
	while (*pw && *pw != ' ')
	    pw++;

	len = pw - sz;
	if (len == 0) {
	    return NULL;
	} else {
	    char *sz_result = (char *) MALLOC(len + 1);
	    strncpy(sz_result, sz, len);
	    sz_result[len] = 0;
	    return sz_result;
	}
    }
}

// 1999 Gregory Deatz
// pm 2005-10-03
#define iswordchar(sz, i, start)       \
          (isalnum(sz[i]) ||           \
	   ((i > start) &&             \
	    !isspace(sz[i-1]) &&       \
	    (sz[i] == '\'')))          \

// ct 2006-11-20 implementation of NULL for FB 2.0
int * findwordindex (char *sz, int *index)
{
  if(!sz || !index)
    return NULL;
  else
  {
    int *result = MALLOC(sizeof(int));
    int i = *index;
    int len = strlen(sz);

    while (i < len && !iswordchar(sz, i, *index))
      i++;

    *result = (i >= len) ? -1 : i;
    return result;
  }
}

// ct 2006-11-30 returns null instead of 0 if not found
int *findwordindexnull(char *sz, int *index)
{
    if (!sz || !index) {
	return NULL;
    } else {
	int i = *index;
	int len = strlen(sz);

	while (i < len && !iswordchar(sz, i, *index))
	    i++;

	if (i >= len) {
	    return NULL;
	} else {
	    int *result = MALLOC(sizeof(int));
	    *result = i;
	    return result;
	}
    }
}

// pm 2005-10-03
// ct 2006-11-20 implementation of NULL for FB 2.0 
char * collatebr (char *sz)
{
  if(!sz)
    return NULL;
  else
  {

    char *sz_return = (char*) MALLOC (strlen(sz) + 1);
    char *pd = sz_return;

    while (*sz)
    {
      switch (*sz)
      {
        case 'á': case 'â': case 'ã': case 'à': case 'ä': case 'å': case 'Á': case 'Â': case 'Ã': case 'À': case 'Ä': case 'Å':
          *pd++ = 'A'; break;
        case 'é': case 'ê': case 'è': case 'ë': case 'É': case 'Ê': case 'È': case 'Ë':
          *pd++ = 'E'; break;
        case 'í': case 'î': case 'ì': case 'ï': case 'Í': case 'Î': case 'Ì': case 'Ï':
          *pd++ = 'I'; break;
        case 'ó': case 'ô': case 'õ': case 'ò': case 'ö': case 'Ó': case 'Ô': case 'Õ': case 'Ò': case 'Ö':
          *pd++ = 'O'; break;
        case 'ú': case 'û': case 'ù': case 'ü': case 'Ú': case 'Û': case 'Ù': case 'Ü':
          *pd++ = 'U'; break;
        case 'ç': case 'Ç':
          *pd++ = 'C'; break;
        case 'ñ': case 'Ñ':
          *pd++ = 'N'; break;
        case 'ý': case 'ÿ': case 'Ý':
          *pd++ = 'Y'; break;
        default:
          *pd++ = *sz;
      }
      sz++;
    }

    *pd = 0;
    return sz_return;
  }
}

// pm 2005-10-03
// ct 2006-11-20 implementation of NULL for FB 2.0
// ct 2006-11-30 intercept negativ n
char * strofchar (char *sz, int *n)
{
  if(!sz || !n)
    return NULL;
  else
  {
    int c = (*n > 0) ? *n : 0;
    char * sz_return = (char*) MALLOC (c + 1);
    char * pd = sz_return;

    if(*n < 0) *n = 0;

    while ((*n)--)
      *pd++ = *sz;

    *pd = 0;

    return sz_return;
  }
}

// gh 2006-02-21
// base on GrUDF in Delphi by Torsten Grundke / Gerd Kroll
// ct 2006-11-20 implementation of NULL for FB 2.0 
char *stringlistitem(char *stringlist, char *item)
{
    if (!stringlist || !item) {
	return NULL;
    } else {
	char *search = MALLOC(strlen(item) + 3);
	char *pos, *end, *result;

	sprintf(search, "\"%s=", item);
	pos = strstr(stringlist, search);
	if (pos) {
	    pos++;
	    end = strchr(pos, '"');
	    if (end) {
		*end = '\0';
	    }
	    result = MALLOC(strlen(pos) + 1);
	    strcpy(result, pos);
	    if (end) {
		*end = '"';
	    }
	} else {
	    result = NULL;
	}

	free(search);
	return result;
    }
}

// gh 2006-02-21
// gh 2006-02-28 added MAXSTRLEN
// gh 2006-03-01 added do_MALLOC
// ct 2006-11-20 implementation of NULL for FB 2.0 
// ct 2007-11-23 changed MAXSTRLEN from 32758
#define MAXSTRLEN (MAX_STRINGBUFFER_SIZE - 3)
char *intern_excelstring(char *string, int do_MALLOC)
{
  if(!string)
    return NULL;
  else {
    char *p = string, *q, *result;
    int len = 0;

    /* Count length of string, double count quotes */
    while (*p && len < MAXSTRLEN) {
	if (*p == '"') {
	    len++;
	}
	if (len < MAXSTRLEN) {
	    len++;
	    p++;
	}
    }
    result = do_MALLOC ? MALLOC(len + 3) : malloc(len + 3);
    p = string;
    q = result;

    /* Start with double quote */
    *q++ = '"';
    len = 0;

    /* Copy the string, omitting CRs and doubling double quotes */
    while (*p && len < MAXSTRLEN) {
	if (*p != 13) {
	    if (*p == '"') {
		*q++ = '"';
		len++;
	    }
	    if (len < MAXSTRLEN) {
		*q++ = *p++;
		len++;
	    }
	} else {
	    p++;
	}
    }
    *q++ = '"';
    *q = '\0';
    return result;
  }
}

// gh 2006-02-21
char *excelstring(char *string)
{
    return intern_excelstring(string, 1);
}

// ct 2006-11-15
// ct 2006-11-20 implementation of NULL for FB 2.0
char * predecessor (char *sz, int *n)
{
  if(!sz || !n)
    return NULL;
  else
  {

    char * sz_return = (char*) MALLOC (2);
    sz_return[0] = *sz + *n;
    sz_return[1] = '\0';
    return sz_return;
  }
}

// ct 2006-11-15
// ct 2006-11-20 implementation of NULL for FB 2.0 
char * successor (char *sz, int *n)
{
  if(!sz || !n)
    return NULL;
  else
  {
    char * sz_return = (char*) MALLOC (2);
    sz_return[0] = *sz - *n;
    sz_return[1] = '\0';
    return sz_return;
  }
}

// ct 2006-11-16
// ct 2006-11-20 implementation of NULL for FB 2.0 
char * reverse (char *sz)
{
  if(!sz)
    return NULL;
  else
  {
    int i;
    int j;
    int len = strlen(sz);
    char * sz_return = (char *) MALLOC (len + 1);

    for (i = len - 1, j = 0; i >= 0 ; i--, j++)
      sz_return[j] = sz[i];

    sz_return[len] = '\0';

    return sz_return;
  }
}

// ct 2006-11-17
// ct 2006-11-20 implementation of NULL for FB 2.0 
int * wordcount (char *sz)
{
  if(!sz)
    return NULL;
  else
  {
    int *result = MALLOC(sizeof(int));
    int wort = 0;
    int count = 0;
    while (*sz)
    {
      if(isspace(*sz))
        wort = 0;
      else
      {
        if(wort == 0)
        {
          wort = 1;
          count++;
        }
      }
      sz++;
    }
    *result = count;
    return result;
  }
}

// ct 2006-11-17
// ct 2006-11-20 implementation of NULL for FB 2.0 
short * ord(unsigned char *sz)
{
  if(!sz)
    return NULL;
  else
  {
    short *result = MALLOC(sizeof(short));
    *result = sz[0];
    return result;
  }
}

// ct 2006-11-17
// ct 2006-11-20 implementation of NULL for FB 2.0 
int * stringcount(char *sz, char *sz_in)
{
  if(!sz || !sz_in || *sz == 0 || *sz_in == 0)
    return NULL;
  else
  {
    int *result = MALLOC(sizeof(int));
    char *str = sz;
    int len = strlen(sz_in);
    int count = 0;
    while ((str = strstr(str, sz_in)) != NULL )
    {
      str +=len;
      count++;
    }
    *result = count;
    return result;
  }
}

// ct 2007-02-03 version with swapped parameters for rFunc
int * r_stringcount(char *sz_in, char *sz)
{
  if(!sz || !sz_in || *sz == 0 || *sz_in == 0)
    return NULL;
  else
  {
    int *result = MALLOC(sizeof(int));
    char *str = sz;
    int len = strlen(sz_in);
    int count = 0;
    while ((str = strstr(str, sz_in)) != NULL )
    {
      str +=len;
      count++;
    }
    *result = count;
    return result;
  }
}

// ct 2007-02-03
int * r_strcmp(char *s1, char *s2)
{
  if(!s1 || !s2)
    return NULL;
  else
  {
    int *result = MALLOC(sizeof(int));
    *result = strcmp(s1, s2);
    return result;
  }
}

// ct 2007-02-03
int * r_wordcount(char *s, char *delim, int *flag)
{
  if(!s || !delim || !flag)
    return NULL;
  else
  {
      int *result = MALLOC(sizeof(int));

      char *c = s;
      int r = 0;
      int d = 1;

      while (*c)
	 if (strchr(delim, *c++))
	    d++; // counting words
	 else {
	    while (*c && !strchr(delim, *c)) c++;
	       r++; // counting full words
	 }
	if (*flag)
		*result = d;
	else
		*result = r;
      return result;
  }
}

// ct 2007-02-03
char * wordnum(char *s, int *n, char *delim, int *flag)
{
  if(!s || !n || !delim || !flag)
    return NULL;
  else
  {
      int len = strlen(s);
      char * result = (char*) MALLOC (len + 1);

	char *c = s, *ptr;
	int r = 1;

	if (!*c) return c;
	while (*c && r!=*n)
		if (strchr(delim, *c++)) {
			if (*flag)
				r++;
			else
				while (*c && strchr(delim, *c)) c++;
		} else {
			while (*c && !strchr(delim, *c)) c++;
			if (!*flag) r++;
		}
	if (!*flag)
		while (*c && strchr(delim, *c)) c++;
	ptr = c;
	while (*ptr && !strchr(delim, *ptr)) ptr++;
	*ptr = '\0';

	strcpy(result, c);
        return result;
  }      
}

// gh 2007-02-05
// Convert to uppercase, but copy only alphanumeric characters,
// german umlauts and characters with accents. Convert umlauts and accents
// into their accordant "normal" character, for example ö into O. 
char *keyup(char *key, int *len)
{
    char *res, *pc1, *pc2;
    int i;
    char c;

    res = MALLOC(*len + 1);
    pc1 = key;
    pc2 = res;
    i = 0;
    while (*pc1 && i < *len) {
	c = StringUpTab[(unsigned char)*pc1++];
	if ((c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
	    *pc2++ = c;
	    i++;
	} else {
	    switch (c) {
	    case 'È': case 'É': case 'Ê': case 'Ë':
		*pc2++ = 'E';
		i++;
		break;
	    case 'À': case 'Á': case 'Â': case 'Ä': case 'Ã': case 'Å':
		*pc2++ = 'A';
		i++;
		break;
	    case 'Ù': case 'Ú': case 'Û': case 'Ü':
		*pc2++ = 'U';
		i++;
		break;
	    case 'Ò': case 'Ó': case 'Ô': case 'Õ': case 'Ö':
		*pc2++ = 'O';
		i++;
		break;
	    case 'Ì': case 'Í': case 'Î': case 'Ï':
		*pc2++ = 'I';
		i++;
		break;
	    case 'Ç':
		*pc2++ = 'C';
		i++;
		break;
	    case 'Ø':
		*pc2++ = 'O';
		i++;
		if (i < *len) {
		    *pc2++ = 'E';
		    i++;
		}
		break;
	    case 'ß':
		*pc2++ = 'S';
		i++;
		if (i < *len) {
		    *pc2++ = 'S';
		    i++;
		}
		break;
	    case 'Æ':
		*pc2++ = 'A';
		i++;
		if (i < *len) {
		    *pc2++ = 'E';
		    i++;
		}
		break;
	    case 'Ð':
		*pc2++ = 'D';
		i++;
		break;
	    case 'Ý' :
		*pc2++ = 'Y';
		i++;
		break;
	    case 'Ñ':
		*pc2++ = 'N';
		i++;
		break;
	    }
	}
    }
    *pc2 = 0;
    return res;
}

// ct 2007-02-05
char * r_c(char * s)
{
  return s;
}

// gh 2007-02-06
char *convertsymbols(char *s, char *source, char *target)
{
    if (!s || !source || !target || (strlen(source) > strlen(target))) {
	return NULL;
    } else {
	int len = strlen(s);
	char *result = (char *) MALLOC(len + 1);
	char *p1 = s, *p2 = result, *p;

	while (*p1) {
	    if ((p = strchr(source, *p1)) != NULL) {
		*p2++ = target[p - source];
		p1++;
	    } else {
		*p2++ = *p1++;
	    }
	}
	*p2 = '\0';
	return result;
    }
}

// gh 2007-07-04: repeattrim
// Output is a trimmed string of all repeats 
// only the first character of trim is used
char *repeattrim(char *string, char *trim)
{
    if (!string) {
	return NULL;
    } else {
	char *result = MALLOC(strlen(string) + 1);
	char *s1 = string, *s2 = result;
	if (!trim || !trim[0]) {
	    strcpy(result, string);
	} else {
	    while (*s1) {
		while (*s1 && (*s1 != trim[0])) {
		    *s2++ = *s1++;
		}
		*s2++ = *s1++;
		while (*s1 == trim[0]) {
		    s1++;
		}
	    }
	    *s2 = '\0';
	}
	return result;
    }
}

// gh 2007-07-04
// Output ist string, count mal wiederholt mit maximaler Länge maxlen.
char *strrepeat(char *string, int *count)
{
    if (!string || !count) {
	return NULL;
    } else {
	int i = 0, j = 0;
	int len = *count * strlen(string) + 1;
	char *result = MALLOC(len);

	if (*string) {
	    while (i < len - 1) {
		result[i++] = string[j++];
		if (!string[j]) {
		    j = 0;
		}
	    }
	}
	result[i] = '\0';
	return result;
    }
}

// gh 2007-07-04
// replaces parts of strings: form pos count characters are replaced
// example:
/*
SELECT F_STRSTUFF('1234567890', 3, 2, 'abc') FROM RDB$DATABASE
result: 12abc567890 */

char *strstuff(char *string, int *pos, int *count, char *repl)
{
    if (!string || !pos || !count || !repl) {
	return NULL;
    } else {
	int i = 0, j = 0, l = 0, n;
	int slen = strlen(string);
	int len = slen + strlen(repl) + 1;
	char *result = MALLOC(len);

	n = (*pos > slen) ? slen : ((*pos > 0) ? *pos - 1 : 0);
	while (l < n) {
	    result[l++] = string[j++];
	}
	while (repl[i]) {
	    result[l++] = repl[i++];
	}
	j = (j + *count < slen) ? (j + *count) : slen;
	while (string[j] && l < len) {
	    result[l++] = string[j++];
	}
	result[l] = '\0';
	return result;
    }
}

// gh 2007-07-04
// Conversion of double d to string using format fmt.
/*
Formatting strings (as in c-function sprintf):
% [flags] [width] [.prec] type_char
flags:
- 	left justify
+ 	begin with plus or minus sign
blank 	blank instead of a plus
# 	alternate conversion:
0x (0X) before for x,X type_char
always a decimal point for e,E,f
width:
n 	at least n chars, padded by blanks
0n 	at least n chars, padded by zeros
prec:
(none) 	1 for d,i,o,u,x,X types
6 for e,E,f types
all significant digits for g,G
.0 	for d,i,o,u,x types, precision set to default
for e,E,f types, no decimal point
.n 	for d,i,o,u,x types, at least n digits
for e,E,f types, n digits after the decimal point
for g,G, at most n significant digits
type_char:
d,i 	signed decimal integer
o 	unsigned octal integer
u 	unsigned decimal integer
x,X 	unsigned hexadecimal int
f 	signed value of the form [-]dddd.dddd
e 	signed value of the form [-]d.dddd or e[+/-]ddd
g 	signed value in either e or f form, based on given value and precision
E,G 	same as e,g, but with E for exponent
Beispiele:
FloatToStr(13.5, '%7.3e') = '1.350e+01'
FloatToStr(13.5, '%+7.3f') = ' +13.500'
FloatToStr(13.5345, '%.5g') = '13.534'
FloatToStr(13.5345, '%.5f') = '13.53450'
FloatToStr(13, '%05X') = '0000D'
FloatToStr(13, '%#04x') = '0x0d' */
char *floattostr(double *d, char *fmt)
{
    if (!d || !fmt) {
	return NULL;
    } else {
	char *result = MALLOC(64);
	char *s, slong[32];
	long i;

	result[0] = '\0';

        if ((s = strstr(fmt, "%")) != NULL) {
	    i = 1;
	    while (strchr("+- #", s[i]))
		i++;
	    while (strchr("0123456789", s[i]))
		i++;
	    while (strchr(".", s[i]))
		i++;
	    while (strchr("0123456789", s[i]))
		i++;
	    if (strchr("diouxX", s[i])) {
		sprintf(slong, "%.0f", *d);
		i = atoi(slong);
		sprintf(result, fmt, i);
	    } else {
		sprintf(result, fmt, *d);
	    }
	} else {
	    sprintf(result, fmt, *d);
	}
	return result;
    }
}

// gh 2007-07-04
// Conversion of integer d to string using format fmt (See FloatToStr)
char *inttostr(int *i, char *fmt)
{
    char *buffer = MALLOC(32);

    sprintf(buffer, fmt, *i);
    return buffer;
}

// gh 2008-02-12
// extracts domain from email-adress
char *domainfromemail (char * email)
{
    if (!email) {
	return NULL;
    } else {
        char *result = MALLOC(strlen(email));
        char *p = strchr(email, '@');
        if (p) {
            int l;
            strcpy(result, p + 1);
            l = strlen(result);
            while (l && isspace(result[l - 1])) {
                l--;
            }
            result[l] = '\0';
        } else {
            strcpy(result, "");
        }
        return result;
    }
}

// gh 2008-02-14
char *rot13(char *string)
{
    if (!string) {
	return NULL;
    } else {
	char *result = MALLOC(strlen(string) + 1);
	unsigned char *r = result, *s = string;
	while ((*r = *s++)) {
	    if (*r >= 'a' && *r <= 'z') {
		*r += 13;
		if (*r > 'z') {
		    *r = 'a' + (*r - 'z') - 1;
		}
	    }
	    if (*r >= 'A' && *r <= 'Z') {
		*r += 13;
		if (*r > 'Z') {
		    *r = 'A' + (*r - 'Z') - 1;
		}
	    }
	    r++;
	}
	return result;
    }
}

// pm 2005-10-03
char * version ()
{
  char * sz_return = (char*) MALLOC (255);
  strcpy(sz_return,"adhoc 20080219");
  return sz_return;
}
                         string_functions.h                                                                                  0000744 0000000 0000764 00000007642 10756254562 013465  0                                                                                                    ustar   root                            adhoc                                                                                                                                                                                                                  /*****************************************************************************
 * FreeAdhocUDF - copyright (c) 2004 - 2008 adhoc dataservice GmbH
 * Christoph Theuring ct / Peter Mandrella pm / Georg Horn gh
 * <http://www.udf.adhoc-data.de> eMail <udf@adhoc-data.de>
 * based on FreeUDFLibC - copyright (c) 1999 Gregory Deatz
 * some code from Robert Loipfinger rl copyright (c) 2000 ADITO Software GmbH
 * some code from rFunc UDF library copyright (c) 1998-2003 Polaris Software
 *
 * File Name:	string_functions.h
 * Description: This header contains the prototype definitions
 *
 * This file is part of FreeAdhocUDF.
 * FreeAdhocUDF is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * FreeAdhocUDF is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with FreeAdhocUDF.  If not, see <http://www.gnu.org/licenses/>. 
*****************************************************************************/

char *character (int *);
char *crlf ();
char *lf ();
char *tab ();
char *nbsp ();
char *dqm ();
char *sqm ();
char *digits (char *);
char *encryptmd5 (char *);
char *left (char *, int *);
char *linewrap (char *, int *, int *);
char *ltrim (char *);
char *lrtrim (char *);
char *rtrim (char *);
char *mid (char *, int *, int *);
char *padleft (char *, char *, int *);
char *r_padleft (char *, int *, char *);
char *padright (char *, char *, int *);
char *r_padright (char *, int *, char *);
char *padcenter (char *, char *, int *);
char *propercase (char *);
char *replace (char *, char *, char *);
char *right (char *, int *);
char *soundex (char *);
char *gsoundex (char *);
int *stringlength (char *);
char *stripstring (char *, char *);
char *stripstringhold (char *, char *);
int *substr (char *, char *);
int *substrnull (char *, char *);
int *strsub (char *, char *);
int *strsubnull (char *, char *);
int *strpos (char *, char *);
char *lower (char *);
char *upper (char *);
char *rlower (char *);
char *rupper (char *);
char *rlatin (char *);
char *telefonnr (char *, int *);
char *aif (char *, char *, char *, char *, char *);
char *strcopy (char *, int *, int *);
char *strrm (char *, int *);
char *version ();
char *predecessor (char *, int *);
char *successor (char *, int *);
char *reverse (char *);
int *wordcount (char *);
short *ord(unsigned char *);
int *stringcount(char *, char *);
int *r_stringcount(char *, char *);
int *r_strcmp(char *, char *);
int *r_wordcount(char *, char *, int *);
char *wordnum(char *, int *, char *, int *);

// internal functions
int find_char (char, char *);

char *collatebr (char *);
int *equalstring (char *, char *);
char *findnthword (char *, int *);
char *findword (char *, int *);
int *findwordindex (char *, int *);
int *findwordindexnull (char *, int *);
char *mid1 (char *, int *, int *);
char *replacestring (char *, char *, char *, int *, int *);
char *intern_replacestring (char *, char *, char *, int *, int *, int);
char *space (int *);
char *strofchar (char *, int *);
char *dollarval (double *);
char *euroval (double *);
char *stringlistitem (char *, char *);
char *excelstring (char *);
char *intern_excelstring (char *, int);
char *keyup(char *, int *);
char *r_c(char *);
char *convertsymbols(char *, char *, char *);
char *repeattrim(char *, char *);
char *strrepeat(char *, int *);
char *strstuff(char *, int *, int *, char *);
char *floattostr(double *, char *);
char *inttostr(int *, char *);
char *domainfromemail (char *);
char *rot13(char *);

                                                                                              sysdep.c                                                                                            0000744 0000000 0000764 00000017063 10756255064 011365  0                                                                                                    ustar   root                            adhoc                                                                                                                                                                                                                  /*****************************************************************************
 * FreeAdhocUDF - copyright (c) 2004 - 2008 adhoc dataservice GmbH
 * Christoph Theuring ct / Peter Mandrella pm / Georg Horn gh
 * <http://www.udf.adhoc-data.de> eMail <udf@adhoc-data.de>
 * Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc.
 * Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. &
 * Digital Equipment Corporation, Maynard, Mass.
 * Copyright (c) 1998 Microsoft.
 * 
 * File Name:	sysdep.c
 * Description: this module contains system routines for the UUID functions
 * and was originally written by the Open Software Foundation, Inc.
 * adapted for FreeAdhoc UDF by Georg Horn 2006-10-20
 * for exported functions list see sysdep.h
 *
 * This file is part of FreeAdhocUDF.
 * FreeAdhocUDF is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * FreeAdhocUDF is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with FreeAdhocUDF.  If not, see <http://www.gnu.org/licenses/>. 
 *
 * Additional license for sysdep.c 
 * To anyone who acknowledges that this file is provided "AS IS"
 * without any express or implied warranty: permission to use, copy,
 * modify, and distribute this file for any purpose is hereby
 * granted without fee, provided that the above copyright notices and
 * this notice appears in all source code copies, and that none of
 * the names of Open Software Foundation, Inc., Hewlett-Packard
 * Company, or Digital Equipment Corporation be used in advertising
 * or publicity pertaining to distribution of the software without
 * specific, written prior permission.  Neither Open Software
 * Foundation, Inc., Hewlett-Packard Company, Microsoft, nor Digital
 * Eqiupment Corporation makes any representations about the suitability
 * of this software for any purpose.
*****************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "sysdep.h"

/* get a mac address if available */
#ifdef UUID_WINDOWS
typedef struct _ASTAT_ {
    ADAPTER_STATUS adapt;
    NAME_BUFFER NameBuff[30];

} ASTAT;

ASTAT Adapter;

int get_mac_address(uuid_node_t *node)
{
    NCB Ncb;
    LANA_ENUM lenum;

    memset(&Ncb, 0, sizeof(Ncb));
    Ncb.ncb_command = NCBENUM;
    Ncb.ncb_buffer = (UCHAR *) &lenum;
    Ncb.ncb_length = sizeof(lenum);
    Netbios(&Ncb);
    if ((Netbios(&Ncb) != 0) || (lenum.length < 1)) {
	return -1;
    }

    memset(&Ncb, 0, sizeof(Ncb));
    Ncb.ncb_command = NCBRESET;
    Ncb.ncb_lana_num = lenum.lana[0];
    if (Netbios(&Ncb) != 0) {
	return -1;
    }

    memset(&Ncb, 0, sizeof(Ncb));
    Ncb.ncb_command = NCBASTAT;
    Ncb.ncb_lana_num = lenum.lana[0];
    strcpy((char *) Ncb.ncb_callname, "*");
    Ncb.ncb_buffer = (PUCHAR) & Adapter;
    Ncb.ncb_length = sizeof(Adapter);
    if (Netbios(&Ncb) != 0) {
	return -1;
    }

    node->nodeID[0] = Adapter.adapt.adapter_address[0];
    node->nodeID[1] = Adapter.adapt.adapter_address[1];
    node->nodeID[2] = Adapter.adapt.adapter_address[2];
    node->nodeID[3] = Adapter.adapt.adapter_address[3];
    node->nodeID[4] = Adapter.adapt.adapter_address[4];
    node->nodeID[5] = Adapter.adapt.adapter_address[5];

    return 0;
}
#else  /* UUID_WINDOWS */
int get_mac_address(uuid_node_t *node)
{
    int sfd;
    struct ifreq ifr;
    unsigned char *u;

    if ((sfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
	return -1;
    }

    memset(&ifr, 0, sizeof ifr);
    strcpy(ifr.ifr_name, INTERFACE_NAME);
    if (ioctl(sfd, SIOCGIFHWADDR, &ifr) < 0) {
	return -1;
    }

    u = (unsigned char *) &ifr.ifr_addr.sa_data;
    node->nodeID[0] = u[0];
    node->nodeID[1] = u[1];
    node->nodeID[2] = u[2];
    node->nodeID[3] = u[3];
    node->nodeID[4] = u[4];
    node->nodeID[5] = u[5];

    close(sfd);
    return 0;
}
#endif  /* UUID_WINDOWS */

/* system dependent call to get IEEE node ID.
   This implementation generates a random node ID if rand_nodeid is 1
   or if no real nodeid can be detected. */
void get_ieee_node_identifier(uuid_node_t *node, int rand_nodeid)
{
    static int real_inited = 0;
    static int rand_inited = 0;
    static uuid_node_t real_node;
    static uuid_node_t rand_node;

    if (rand_nodeid) {
	if (!rand_inited) {
	    unsigned char seed[16];
	    get_random_info(seed);
	    seed[0] |= 0x80;
	    memcpy(&rand_node, seed, sizeof(uuid_node_t));
	    rand_inited = 1;
	}
	*node = rand_node;
    } else {
	if (!real_inited) {
	    if (get_mac_address(&real_node) < 0) {
		get_ieee_node_identifier(node, 1);
		memcpy(&real_node, &rand_node, sizeof(uuid_node_t));
	    }
	    real_inited = 1;
	}
	*node = real_node;
    }
}

/* system dependent call to get the current system time.
   returned as 100ns ticks since Oct 15, 1582, but resolution may be less
   than 100ns. */
#ifdef UUID_WINDOWS
void get_system_time(uuid_time_t * uuid_time)
{
    unsigned __int64 time;

    GetSystemTimeAsFileTime((FILETIME *) & time);

    /* NT keeps time in FILETIME format which is 100ns ticks since
       Jan 1, 1601.  UUIDs use time in 100ns ticks since Oct 15, 1582.
       The difference is 17 Days in Oct + 30 (Nov) + 31 (Dec)
       + 18 years and 5 leap days. */
    time += (unsigned __int64) (1000 * 1000 * 10)	// seconds
	* (unsigned __int64) (60 * 60 * 24)	// days
	* (unsigned __int64) (17 + 30 + 31 + 365 * 18 + 5);	// # of days

    *uuid_time = time;
}

void get_random_info(unsigned char seed[16])
{
    MD5_CTX c;
    typedef struct {
	MEMORYSTATUS m;
	SYSTEM_INFO s;
	FILETIME t;
	LARGE_INTEGER pc;
	DWORD tc;
	DWORD l;
	char hostname[MAX_COMPUTERNAME_LENGTH + 1];
    } randomness;
    randomness r;

    MD5Init(&c);
    /* memory usage stats */
    GlobalMemoryStatus(&r.m);
    /* random system stats */
    GetSystemInfo(&r.s);
    /* 100ns resolution (nominally) time of day */
    GetSystemTimeAsFileTime(&r.t);
    /* high resolution performance counter */
    QueryPerformanceCounter(&r.pc);
    /* milliseconds since last boot */
    r.tc = GetTickCount();
    r.l = MAX_COMPUTERNAME_LENGTH + 1;
    GetComputerName(r.hostname, &r.l);
    MD5Update(&c, (unsigned char *) &r, sizeof(randomness));
    MD5Final(seed, &c);
}
#else
/* ! UUID_WINDOWS */
void get_system_time(uuid_time_t * uuid_time)
{
    struct timeval tp;

    gettimeofday(&tp, (struct timezone *) 0);

    /* Offset between UUID formatted times and Unix formatted times.
       UUID UTC base time is October 15, 1582.
       Unix base time is January 1, 1970. */
    *uuid_time = ((uuid_time_t)tp.tv_sec * 10000000)
	+ ((uuid_time_t)tp.tv_usec * 10) + I64(0x01B21DD213814000);
}

void get_random_info(unsigned char seed[16])
{
    MD5_CTX c;
    typedef struct {
	struct sysinfo s;
	struct timeval t;
	char hostname[257];
    } randomness;
    randomness r;

    MD5Init(&c);
    sysinfo(&r.s);
    gettimeofday(&r.t, (struct timezone *) 0);
    gethostname(r.hostname, 256);
    MD5Update(&c, (unsigned char *)&r, sizeof(randomness));
    MD5Final(seed, &c);
}
#endif
/* UUID_WINDOWS */
                                                                                                                                                                                                                                                                                                                                                                                                                                                                             sysdep.h                                                                                            0000744 0000000 0000764 00000007474 10756254712 011376  0                                                                                                    ustar   root                            adhoc                                                                                                                                                                                                                  /*****************************************************************************
 * FreeAdhocUDF - copyright (c) 2004 - 2008 adhoc dataservice GmbH
 * Christoph Theuring / Peter Mandrella / Georg Horn
 * <http://www.udf.adhoc-data.de> eMail <udf@adhoc-data.de>
 * Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc.
 * Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. &
 * Digital Equipment Corporation, Maynard, Mass.
 * Copyright (c) 1998 Microsoft.
 * 
 * File Name:	sysdep.h
 * Description: This header contains the prototype definitions for sysdep.c
 * and was originally written by the Open Software Foundation, Inc.
 * adapted for FreeAdhoc UDF by Georg Horn 2006-10-20 
 * some changes made 2006 to integrate to the FreeAdhocUDF project 
 * 
 * This file is part of FreeAdhocUDF.
 * FreeAdhocUDF is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * FreeAdhocUDF is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with FreeAdhocUDF.  If not, see <http://www.gnu.org/licenses/>. 
 *
 * Additional license for sysdep.h 
 * To anyone who acknowledges that this file is provided "AS IS"
 * without any express or implied warranty: permission to use, copy,
 * modify, and distribute this file for any purpose is hereby
 * granted without fee, provided that the above copyright notices and
 * this notice appears in all source code copies, and that none of
 * the names of Open Software Foundation, Inc., Hewlett-Packard
 * Company, or Digital Equipment Corporation be used in advertising
 * or publicity pertaining to distribution of the software without
 * specific, written prior permission.  Neither Open Software
 * Foundation, Inc., Hewlett-Packard Company, Microsoft, nor Digital
 * Eqiupment Corporation makes any representations about the suitability
 * of this software for any purpose.
*****************************************************************************/

/* Borland definiert __BORLANDC__, fuer MS Visual C evtl. anpassen...
   _WINDOWS_ darf NICHT definiert sein, es wird in windows.h definiert.
   Defines für BC5 waren: _RTLDLL; */

#if defined(__BORLANDC__) || defined(__MSVC__)
#define UUID_WINDOWS
#include <windows.h>
#include <wincon.h>
#else
/* Set name of your ethernet-interface here: */
#define INTERFACE_NAME "eth0"
#include <unistd.h>
#include <sys/time.h>
#include <sys/sysinfo.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <net/if.h> 
#include <arpa/inet.h>
#endif

/* change to point to where MD5 .h's live */
/* get MD5 sample implementation from RFC 1321 */
#include "md5_global.h"
#include "md5.h"

/* set the following to the number of 100ns ticks of the actual
   resolution of your system's clock */
#define UUIDS_PER_TICK 1024

/* Set the following to a call to acquire a system wide global lock */
#define LOCK
#define UNLOCK

typedef unsigned long unsigned32;
typedef unsigned short unsigned16;
typedef unsigned char unsigned8;
typedef unsigned char byte;

/* Set this to what your compiler uses for 64 bit data type */
#ifdef UUID_WINDOWS
#define unsigned64_t unsigned __int64
#define I64(C) C
#else
#define unsigned64_t unsigned long long
#define I64(C) C##LL
#endif

typedef unsigned64_t uuid_time_t;

typedef struct {
    unsigned char nodeID[6];
} uuid_node_t;

void get_ieee_node_identifier(uuid_node_t *node, int do_rand);
void get_system_time(uuid_time_t *uuid_time);
void get_random_info(unsigned char seed[16]);
                                                                                                                                                                                                    uuid.c                                                                                              0000744 0000000 0000764 00000021131 10756254760 011015  0                                                                                                    ustar   root                            adhoc                                                                                                                                                                                                                  /*****************************************************************************
 * FreeAdhocUDF - copyright (c) 2004 - 2008 adhoc dataservice GmbH
 * Christoph Theuring ct / Peter Mandrella pm / Georg Horn gh
 * <http://www.udf.adhoc-data.de> eMail <udf@adhoc-data.de>
 * Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc.
 * Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. &
 * Digital Equipment Corporation, Maynard, Mass.
 * Copyright (c) 1998 Microsoft.
 * 
 * File Name:	uuid.c
 * Description: this module contains basic routines for the UUID functions
 * and was originally written by the Open Software Foundation, Inc.
 * adapted for FreeAdhoc UDF by Georg Horn 2006-10-20 
 * for exported functions list see uuid.h
 *
 * This file is part of FreeAdhocUDF.
 * FreeAdhocUDF is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * FreeAdhocUDF is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with FreeAdhocUDF.  If not, see <http://www.gnu.org/licenses/>. 
 *
 * Additional license for uuid.c 
 * To anyone who acknowledges that this file is provided "AS IS"
 * without any express or implied warranty: permission to use, copy,
 * modify, and distribute this file for any purpose is hereby
 * granted without fee, provided that the above copyright notices and
 * this notice appears in all source code copies, and that none of
 * the names of Open Software Foundation, Inc., Hewlett-Packard
 * Company, or Digital Equipment Corporation be used in advertising
 * or publicity pertaining to distribution of the software without
 * specific, written prior permission.  Neither Open Software
 * Foundation, Inc., Hewlett-Packard Company, Microsoft, nor Digital
 * Eqiupment Corporation makes any representations about the suitability
 * of this software for any purpose.
*****************************************************************************/

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "sysdep.h"
#include "uuid.h"

/* various forward declarations */
static int read_state(unsigned16 * clockseq, uuid_time_t * timestamp, uuid_node_t * node);
static void write_state(unsigned16 clockseq, uuid_time_t timestamp, uuid_node_t node);
static void get_current_time(uuid_time_t * timestamp);
static unsigned16 true_random(void);

/* generate a V1 UUID */
int uuid_create_v1(uuid_t *uuid, int rand_nodeid)
{
    uuid_time_t timestamp, last_time;
    unsigned16 clockseq;
    uuid_node_t node;
    uuid_node_t last_node;
    int f;

    /* acquire system wide lock so we're alone */
    LOCK;

    /* get current time */
    get_current_time(&timestamp);

    /* get node ID */
    get_ieee_node_identifier(&node, rand_nodeid);

    /* get saved state from NV storage */
    f = read_state(&clockseq, &last_time, &last_node);

    /* if no NV state, or if clock went backwards, or node ID changed (e.g.,
       net card swap) change clockseq */
    if (!f || memcmp(&node, &last_node, sizeof(uuid_node_t)))
	clockseq = true_random();
    else if (timestamp < last_time)
    	clockseq++;

    /* stuff fields into the UUID */
    uuid->time_low = (unsigned long) (timestamp & 0xFFFFFFFF);
    uuid->time_mid = (unsigned short) ((timestamp >> 32) & 0xFFFF);
    uuid->time_hi_and_version = (unsigned short) ((timestamp >> 48) & 0x0FFF);
    uuid->time_hi_and_version |= (1 << 12);
    uuid->clock_seq_low = clockseq & 0xFF;
    uuid->clock_seq_hi_and_reserved = (clockseq & 0x3F00) >> 8;
    uuid->clock_seq_hi_and_reserved |= 0x80;
    memcpy(&uuid->node, &node, sizeof uuid->node);

    /* save the state for next time */
    write_state(clockseq, timestamp, node);
    UNLOCK;
    return 1;
}

/* generate a V4 UUID */
int uuid_create_v4(uuid_t *uuid)
{
    int i;

    uuid->time_low = (true_random() << 16) | true_random();
    uuid->time_mid = true_random();
    uuid->time_hi_and_version = true_random();
    uuid->clock_seq_low = true_random();
    uuid->clock_seq_hi_and_reserved = true_random();
    for (i = 0; i < 6; i++) {
	uuid->node[i] = true_random();
    }
    uuid->time_hi_and_version &= 0x0fff;
    uuid->time_hi_and_version |= 0x4000;
    uuid->clock_seq_hi_and_reserved &= 0x3f;
    uuid->clock_seq_hi_and_reserved |= 0x80;
    return 1;
}

/* data type for UUID generator persistent state */
typedef struct {
    uuid_time_t ts;		/* saved timestamp */
    uuid_node_t node;		/* saved node ID */
    unsigned16 cs;		/* saved clock sequence */
} uuid_state;
static uuid_state st;

/* read UUID generator state from non-volatile store */
int read_state(unsigned16 * clockseq, uuid_time_t * timestamp,
    uuid_node_t * node)
{
    FILE *fd;
    static int inited = 0;

    /* only need to read state once per boot */
    if (!inited) {
	char *tmpStr;
	char *tmp = getenv("TMP");
	if (!tmp) {
	    tmp = getenv("TEMP");
	    if (!tmp) {
		tmp = "/tmp";
	    }
	}
	tmpStr = (char *) malloc(strlen(tmp) + 20);
	strcpy(tmpStr, tmp);
	strcat(tmpStr, "/uuid.state");
	fd = fopen(tmpStr, "rb");
	if (!fd)
	    return 0;
	fread(&st, sizeof(uuid_state), 1, fd);
	fclose(fd);
	free(tmpStr);
	inited = 1;
    }
    *clockseq = st.cs;
    *timestamp = st.ts;
    *node = st.node;
    return 1;
}

/* save UUID generator state back to non-volatile storage */
void write_state(unsigned16 clockseq, uuid_time_t timestamp, uuid_node_t node)
{
    FILE *fd;
    static int inited = 0;
    static uuid_time_t next_save;

    if (!inited) {
	next_save = timestamp;
	inited = 1;
    }

    /* always save state to volatile shared state */
    st.cs = clockseq;
    st.ts = timestamp;
    st.node = node;
    if (timestamp >= next_save) {
	char *tmpStr;
	char *tmp = getenv("TMP");
	if (!tmp) {
	    tmp = getenv("TEMP");
	    if (!tmp) {
		tmp = "/tmp";
	    }
	}
	tmpStr = (char *) malloc(strlen(tmp) + 20);
	strcpy(tmpStr, tmp);
	strcat(tmpStr, "/uuid.state");
	fd = fopen(tmpStr, "wb");
	if (fd) {
	    fwrite(&st, sizeof(uuid_state), 1, fd);
	    fclose(fd);
	}

	/* schedule next save for 10 seconds from now */
	free(tmpStr);
	next_save = timestamp + (10 * 10 * 1000 * 1000);
    }
}

/* get time as 60 bit 100ns ticks since whenever.
   Compensate for the fact that real clock resolution is less than 100ns. */
void get_current_time(uuid_time_t * timestamp)
{
    uuid_time_t time_now;
    static uuid_time_t time_last;
    static unsigned16 uuids_this_tick;
    static int inited = 0;

    if (!inited) {
	/* ivar: is this line not surplus? maybe it should call time_last as it
	   has not been set yet? */
	get_system_time(&time_now);
	uuids_this_tick = UUIDS_PER_TICK;
	inited = 1;
    }
    while (1) {
	get_system_time(&time_now);

	/* if clock reading changed since last UUID generated... */
	if (time_last != time_now) {
	    /* reset count of uuids gen'd with this clock reading */
	    uuids_this_tick = 0;
	    break;
	}
	if (uuids_this_tick < UUIDS_PER_TICK) {
	    uuids_this_tick++;
	    break;
	}

    /* going too fast for our clock; spin */
    }

    /* add the count of uuids to low order bits of the clock reading */
    *timestamp = time_now + uuids_this_tick;

    /* ########## Buggered up by ian and ivar. maybe, fudge. need to rem time
       last */
    time_last = time_now;
}

/* generate a crypto-quality random number. This sample doesn't do that. */
static unsigned16 true_random(void)
{
    static int inited = 0;
    uuid_time_t time_now;

    if (!inited) {
	get_system_time(&time_now);
	time_now = time_now / UUIDS_PER_TICK;
	srand((unsigned int) (((time_now >> 32) ^ time_now) & 0xffffffff));
	inited = 1;
    }
    return rand();
}

/* Compare two UUID's "lexically" and return
   -1   u1 is lexically before u2
    0   u1 is equal to u2
    1   u1 is lexically after u2
   Note: lexical ordering is not temporal ordering! */
// ct 2006-12-01 remove because no sence of this function
/*int uuid_compare(uuid_t * u1, uuid_t * u2)
{
    int i;
#define CHECK(f1, f2) if (f1 != f2) return f1 < f2 ? -1 : 1

    CHECK(u1->time_low, u2->time_low);
    CHECK(u1->time_mid, u2->time_mid);
    CHECK(u1->time_hi_and_version, u2->time_hi_and_version);
    CHECK(u1->clock_seq_hi_and_reserved, u2->clock_seq_hi_and_reserved);
    CHECK(u1->clock_seq_low, u2->clock_seq_low);
    for (i = 0; i < 6; i++) {
	if (u1->node[i] < u2->node[i])
	    return -1;
	if (u1->node[i] > u2->node[i])
	    return 1;
    }
    return 0;
} */
                                                                                                                                                                                                                                                                                                                                                                                                                                       uuid_functions.c                                                                                    0000744 0000000 0000764 00000041263 10756255106 013110  0                                                                                                    ustar   root                            adhoc                                                                                                                                                                                                                  /*****************************************************************************
 * FreeAdhocUDF - copyright (c) 2004 - 2008 adhoc dataservice GmbH
 * Christoph Theuring ct / Peter Mandrella pm / Georg Horn gh
 * <http://www.udf.adhoc-data.de> eMail <udf@adhoc-data.de>
 *
 * File Name:	uuid_functions.c
 * Description: this module contains UDFs to generate and manipulate uuids.
 * for exported functions list see uuid_functions.h
 *
 * This file is part of FreeAdhocUDF.
 * FreeAdhocUDF is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * FreeAdhocUDF is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with FreeAdhocUDF.  If not, see <http://www.gnu.org/licenses/>. 
*****************************************************************************/

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
#include <ctype.h>
#include "global.h"

#include "sysdep.h"
#include "uuid.h"
#include "date_functions.h"
#include "uuid_functions.h"

/*****************************************************************
 * Note.
 * Throughout this code the terms _uuid, uuid, and guid are:
 * _uuid - 128bit (16 byte) raw value (internal only)
 * guid - 36 characters (eg. e902893a-9d22-3c7e-a7b8-d6e313b71d9f)
 * uuid - interbase uuid is 19 char value (see fn_i_uuid_create)
 ****************************************************************/
/*****************************************************************
 * Note from adhoc dataservice:
 * in this code the terms UUID and GUID are not as descriped in the RFC4122
 * the term GUID in this code is called UUID in RFC4122
 * and the UUID in this code is not part of the RFC4122
 * it is made by the former programmers and is a decoded UUID for quicker reading
 * so it is better called a UUIDCOMPRESSED
 * We only changed the names of the exported functions for a better understanding
 *****************************************************************/
static char urlchars[64] =
    "!*0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

/* Check if a RFC uuid is valid */
int check_uuid(char *uuid)
{
    if (!uuid) {
	return 0;
    } else {
	int l = 0;
	char *c = uuid;

	while (*c) {
	    if (isxdigit(*c) || (*c == '-')) {
		l++;
		c++;
	    } else {
		break;
	    }
	}
	return (l == 36);
    }
}

/* Check if a compressed uuid is valid */
/* ct 2006-11-21 implementation of NULL for FB 2.0 */
int check_uuidcompr(char *uuidcompr)
{
    if (!uuidcompr) {
	return 0;
    } else {
	int l = 0;
	char *c = uuidcompr;

	while (*c) {
	    if (isalnum(*c) || (*c == '!') || (*c == '*')) {
		l++;
		c++;
	    } else {
		break;
	    }
	}
	return (l == 22);
    }
}

/* return the passed in _uuid as a 36 char guid */
char *_uuid_to_guid(uuid_t * _uuid, char *guid)
{
    int i, j;

    sprintf(guid, "%8.8lx-%4.4x-%4.4x-%2.2x%2.2x-", _uuid->time_low,
	    _uuid->time_mid, _uuid->time_hi_and_version,
	    _uuid->clock_seq_hi_and_reserved, _uuid->clock_seq_low);
    for (i = 0, j = 24; i < 6; i++, j += 2) {
	sprintf(guid + j, "%2.2x", _uuid->node[i]);
    }

    return guid;
}

/* returns the passed in guid as a _uuid */
uuid_t *guid_to__uuid(char *guid, uuid_t * _uuid)
{
    int i, j;

    char *time_low, *time_mid, *time_hi_and_version;
    char *clock_seq_hi_and_reserved, *clock_seq_low;
    char *node[6];
    char *eptr;			// dummy for strtol
#ifdef UUID_WINDOWS		/* Nasty hack to fix lack of strtoll() */
    char *hi_time_low, *lo_time_low;	/* see UUID_WINDOWS below. UGH */
#endif

    time_low = (char *) MALLOC(9);
    time_mid = (char *) MALLOC(5);
    time_hi_and_version = (char *) MALLOC(4);
    clock_seq_hi_and_reserved = (char *) MALLOC(3);
    clock_seq_low = (char *) MALLOC(3);
    memset(time_low, 0, 9);
    memset(time_mid, 0, 5);
    memset(time_hi_and_version, 0, 5);
    memset(clock_seq_hi_and_reserved, 0, 3);
    memset(clock_seq_low, 0, 3);
    for (i = 0; i < 6; i++) {
	node[i] = (char *) MALLOC(3);
	memset(node[i], 0, 3);
    }
    strncpy(time_low, guid, 8);
    strncpy(time_mid, guid + 9, 4);
    strncpy(time_hi_and_version, guid + 14, 4);
    strncpy(clock_seq_hi_and_reserved, guid + 19, 2);
    strncpy(clock_seq_low, guid + 21, 2);
    for (i = 0, j = 24; i < 6; i++, j += 2) {
	strncpy(node[i], guid + j, 2);
    }
#ifdef UUID_WINDOWS		/* Nasty hack to fix lack of strtoll() */
    hi_time_low = (char *) MALLOC(5);
    lo_time_low = (char *) MALLOC(5);
    memset(hi_time_low, 0, 5);
    memset(lo_time_low, 0, 5);
    strncpy(hi_time_low, guid, 4);
    strncpy(lo_time_low, guid + 4, 4);
    _uuid->time_low = strtol(hi_time_low, &eptr, 16);
    _uuid->time_low <<= 16;
    _uuid->time_low |= strtol(lo_time_low, &eptr, 16);
    free(hi_time_low);
    free(lo_time_low);
#else
    _uuid->time_low = strtoll(time_low, &eptr, 16);
#endif
    _uuid->time_mid = strtol(time_mid, &eptr, 16);
    _uuid->time_hi_and_version = strtol(time_hi_and_version, &eptr, 16);
    _uuid->clock_seq_hi_and_reserved =
	strtol(clock_seq_hi_and_reserved, &eptr, 16);
    _uuid->clock_seq_low = strtol(clock_seq_low, &eptr, 16);
    for (i = 0; i < 6; i++) {
	_uuid->node[i] = strtol(node[i], &eptr, 16);
    }

    free(time_low);
    free(time_mid);
    free(time_hi_and_version);
    free(clock_seq_hi_and_reserved);
    free(clock_seq_low);
    for (i = 0; i < 6; i++) {
	free(node[i]);
    }
    return _uuid;
}

#define MASK_1_2	0x03
#define MASK_1_4	0x0f
#define MASK_1_6	0x3f
#define MASK_3_6	0x3c
#define MASK_5_6	0x30
#define MASK_3_8	0xfc
#define MASK_5_8	0xf0
#define MASK_7_8	0xc0
#define MASK_5_10	0x03f0
#define MASK_7_12	0x0fc0
#define MASK_13_16	0xf000
#define MASK_11_16	0xfc00
#define MASK_13_18	0x0003f000
#define MASK_19_24	0x00fc0000
#define MASK_25_30	0x3f000000
#define MASK_31_32	0xc0000000

/* returns the 22char string from the passed in _uuid */
char *_uuid_to_uuid(uuid_t *_uuid, char *uuid)
{
    char sq_u[22];
    int i;

    sq_u[21] = _uuid->time_low & MASK_1_6;
    sq_u[20] = (_uuid->time_low & MASK_7_12) >> 6;
    sq_u[19] = (_uuid->time_low & MASK_13_18) >> 12;
    sq_u[18] = (_uuid->time_low & MASK_19_24) >> 18;
    sq_u[17] = (_uuid->time_low & MASK_25_30) >> 24;
    sq_u[16] = (_uuid->time_low & MASK_31_32) >> 30;

    sq_u[16] |= (_uuid->time_mid & MASK_1_4) << 2;
    sq_u[15] = (_uuid->time_mid & MASK_5_10) >> 4;
    sq_u[14] = (_uuid->time_mid & MASK_11_16) >> 10;

    sq_u[13] = _uuid->time_hi_and_version & MASK_1_6;
    sq_u[12] = (_uuid->time_hi_and_version & MASK_7_12) >> 6;
    sq_u[11] = (_uuid->time_hi_and_version & MASK_13_16) >> 12;

    sq_u[11] |= (_uuid->clock_seq_hi_and_reserved & MASK_1_2) << 4;
    sq_u[10] = (_uuid->clock_seq_hi_and_reserved & MASK_3_8) >> 2;

    sq_u[9] = (_uuid->clock_seq_low & MASK_1_6);
    sq_u[8] = (_uuid->clock_seq_low & MASK_7_8) >> 6;

    sq_u[8] |= (_uuid->node[5] & MASK_1_4) << 2;
    sq_u[7] = ((_uuid->node[5] & MASK_5_8) >> 4) | ((_uuid->node[4] & MASK_1_2) << 4);
    sq_u[6] = (_uuid->node[4] & MASK_3_8) >> 2;
    sq_u[5] = (_uuid->node[3] & MASK_1_6);
    sq_u[4] = ((_uuid->node[3] & MASK_7_8) >> 6) | ((_uuid->node[2] & MASK_1_4) << 2);
    sq_u[3] = ((_uuid->node[2] & MASK_5_8) >> 4) | ((_uuid->node[1] & MASK_1_2) << 4);
    sq_u[2] = ((_uuid->node[1] & MASK_3_8) >> 2);
    sq_u[1] = (_uuid->node[0] & MASK_1_6);
    sq_u[0] = (_uuid->node[0] & MASK_7_8) >> 6;	// +4 unused bits

    for (i = 0; i < 22; i++) {
	uuid[i] = urlchars[(int) sq_u[i]];
    }
    uuid[22] = '\0';
    return uuid;
}

int sq_to_int(char i)
{
    if (i == '!')
	return 0;
    if (i == '*')
	return 1;
    if (i >= '0' && i <= '9')
	return (int) i - 46;  // 0 is 2
    if (i >= 'A' && i <= 'Z')
	return (int) i - 53;  // A is 12
    if (i >= 'a' && i <= 'z')
	return (int) i - 59;  // a is 38
    return -1;
}

/* returns the _uuid from the passed in uuid */
uuid_t *uuid_to__uuid(char *uuid, uuid_t * _uuid)
{
    _uuid->time_low = sq_to_int(uuid[16]);
    _uuid->time_low <<= 6;
    _uuid->time_low |= sq_to_int(uuid[17]);
    _uuid->time_low <<= 6;
    _uuid->time_low |= sq_to_int(uuid[18]);
    _uuid->time_low <<= 6;
    _uuid->time_low |= sq_to_int(uuid[19]);
    _uuid->time_low <<= 6;
    _uuid->time_low |= sq_to_int(uuid[20]);
    _uuid->time_low <<= 6;
    _uuid->time_low |= sq_to_int(uuid[21]);

    _uuid->time_mid = sq_to_int(uuid[14]);
    _uuid->time_mid <<= 6;
    _uuid->time_mid |= sq_to_int(uuid[15]);
    _uuid->time_mid <<= 4;
    _uuid->time_mid |= ((sq_to_int(uuid[16]) & MASK_3_6) >> 2);

    _uuid->time_hi_and_version = sq_to_int(uuid[11]);
    _uuid->time_hi_and_version <<= 6;
    _uuid->time_hi_and_version |= sq_to_int(uuid[12]);
    _uuid->time_hi_and_version <<= 6;
    _uuid->time_hi_and_version |= sq_to_int(uuid[13]);

    _uuid->clock_seq_hi_and_reserved = sq_to_int(uuid[10]);
    _uuid->clock_seq_hi_and_reserved <<= 2;
    _uuid->clock_seq_hi_and_reserved |= ((sq_to_int(uuid[11]) & MASK_5_6) >> 4);

    _uuid->clock_seq_low = sq_to_int(uuid[8]);
    _uuid->clock_seq_low <<= 6;
    _uuid->clock_seq_low |= sq_to_int(uuid[9]);

    _uuid->node[0] = (sq_to_int(uuid[0]) << 6);
    _uuid->node[0] |= sq_to_int(uuid[1]);

    _uuid->node[1] = (sq_to_int(uuid[2]) << 2);
    _uuid->node[1] |= (sq_to_int(uuid[3]) >> 4);

    _uuid->node[2] = (sq_to_int(uuid[3]) << 4);
    _uuid->node[2] |= (sq_to_int(uuid[4]) >> 2);

    _uuid->node[3] = (sq_to_int(uuid[4]) << 6);
    _uuid->node[3] |= sq_to_int(uuid[5]);

    _uuid->node[4] = (sq_to_int(uuid[6]) << 2);
    _uuid->node[4] |= (sq_to_int(uuid[7]) >> 4);

    _uuid->node[5] = (sq_to_int(uuid[7]) << 4);
    _uuid->node[5] |= (sq_to_int(uuid[8]) >> 2);

    return _uuid;
}

/* return timestamp from a _uuid. returned pointer must bee free()d */
struct tm *get__uuid_timestamp(uuid_t *_uuid)
{
    uuid_time_t timestamp;
    time_t t;
#ifndef UUID_WINDOWS
    struct tm *tp = MALLOC(sizeof(struct tm));
#endif

    timestamp = ((uuid_time_t)(_uuid->time_hi_and_version ^ 0x1000) << 48)
	| ((uuid_time_t)_uuid->time_mid << 32) | (uuid_time_t)_uuid->time_low;

    timestamp -= I64(0x01B21DD213814000);
    t = timestamp / 10000000;
    if (t < 0) {
	t = 0;
#ifdef UUID_WINDOWS
	return gmtime(&t);
#else
	gmtime_r(&t, tp);
#endif
    } else {
#ifdef UUID_WINDOWS
	return localtime(&t);
#else
	localtime_r(&t, tp);
#endif
    }
#ifndef UUID_WINDOWS
    return tp;
#endif
}

/* Exported UDFs start here... */

/* return the created _uuid as a 36 char RFC uuid version 1a*/
char *uuid1mac()
{
    char *uuid = (char *) MALLOC (37);
    uuid_t _uuid;

    uuid_create_v1(&_uuid, 0);
    return _uuid_to_guid(&_uuid, uuid);
}

/* return the created _uuid as a 22 character, URL compatible,
   humanly readable string, with the entropy in the low order
   bits for interbase to efficiently hash it.
   Valid URL chars A-Z|a-z|0-9|"-"|"_"|"."|"!"|"~"|"*"|"'"|"("|")"
   and we use a subset of 63 of these, *A-Za-z0-9 */

char *uuid1maccompr()
{
    char *uuid = (char *) MALLOC (23);
    uuid_t _uuid;

    uuid_create_v1(&_uuid, 0);
    return _uuid_to_uuid(&_uuid, uuid);
}

/* return the created _uuid as a 36 char RFC uuid version 1b */
char *uuid1rand()
{
    char *uuid = (char *) MALLOC (37);
    uuid_t _uuid;

    uuid_create_v1(&_uuid, 1);
    return _uuid_to_guid(&_uuid, uuid);
}

/* return the created _uuid as a 22 character, URL compatible, humanly readable
   string. */
char *uuid1randcompr()
{
    char *uuid = (char *) MALLOC (23);
    uuid_t _uuid;

    uuid_create_v1(&_uuid, 1);
    return _uuid_to_uuid(&_uuid, uuid);
}

/* return the created _uuid as a 36 char RFC uuid version 4 */
char *uuid4()
{
    char *uuid = (char *) MALLOC (37);
    uuid_t _uuid;

    uuid_create_v4(&_uuid);
    return _uuid_to_guid(&_uuid, uuid);
}

/* return the created _uuid as a 22 character, URL compatible, humanly readable
   string. */
char *uuid4compr()
{
    char *uuidcompr = (char *) MALLOC (23);
    uuid_t _uuid;

    uuid_create_v4(&_uuid);
    return _uuid_to_uuid(&_uuid, uuidcompr);
}


/* returns the passed in RFC uuid to a compressed uuid */
char *compressuuid(char *uuid)
{
    if (!uuid) {
	return NULL;
    } else {
	char *uuidcompr = (char *) MALLOC(23);
	uuid_t _uuid;

	if (check_uuid(uuid)) {
	    guid_to__uuid(uuid, &_uuid);
	    uuidcompr = _uuid_to_uuid(&_uuid, uuidcompr);
	} else {
	    strcpy(uuidcompr, "Input no RFC4122 UUID");
	}
	return uuidcompr;
    }
}

/* return the passed in compressed uuid expanded to a RFC uuid */
char *expanduuidcompr(char *uuidcompr)
{
    if (!uuidcompr) {
	return NULL;
    } else {
	char *uuid = (char *) MALLOC(37);
	uuid_t _uuid;

	if (check_uuidcompr(uuidcompr)) {
	    uuid_to__uuid(uuidcompr, &_uuid);
	    uuid = _uuid_to_guid(&_uuid, uuid);
	} else {
	    strcpy(uuid, "Input no compressed UUID");
	}
	return uuid;
    }
}

/* return the timestamp from a compressed uuid */
ISC_QUAD *uuid1comprtimestamp(char *uuidcompr)
{
    if (!uuidcompr)
	return NULL;
    else {
	uuid_t _uuid;
	struct tm *tp;
#ifdef UUID_WINDOWS
#else
	ISC_QUAD *date;
#endif
	if (check_uuidcompr(uuidcompr)) {
	    uuid_to__uuid(uuidcompr, &_uuid);
	    if (_uuid.time_hi_and_version & 0x1000) {
		tp = get__uuid_timestamp(&_uuid);
#ifdef UUID_WINDOWS
		return (ISC_QUAD *) gen_ib_date(tp);
#else
		date = gen_ib_date(tp);
		free(tp);
		return date;
#endif
	    }
	}
        return NULL;
    }
}

/* return the timestamp from a RFC uuid */
// gh 2006-12-06 implementation of NULL for FB 2.0 and testing on version 1
ISC_QUAD *uuid1timestamp(char *uuid)
{
    if (!uuid)
	return NULL;
    else {
	uuid_t _uuid;
	struct tm *tp;
#ifndef UUID_WINDOWS
	ISC_QUAD *date;
#endif
	if (check_uuid(uuid) && (uuid[14] == '1')) {
	    guid_to__uuid(uuid, &_uuid);
	    if (_uuid.time_hi_and_version & 0x1000) {
		tp = get__uuid_timestamp(&_uuid);
#ifdef UUID_WINDOWS
		return (ISC_QUAD *) gen_ib_date(tp);
#else
		date = gen_ib_date(tp);
		free(tp);
		return date;
#endif
	    }
	}
	return NULL;
    }
}


/* return the nodeid from a compressed uuid */
/* ct 2006-11-21 implementation of NULL for FB 2.0 */
char *uuid1maccomprmac(char *uuidcompr)
{
    if (!uuidcompr) {
	return NULL;
    } else {
	if (check_uuidcompr(uuidcompr)) {
	    uuid_t _uuid;
	    uuid_to__uuid(uuidcompr, &_uuid);
	    if ((_uuid.time_hi_and_version & 0x1000) && !(_uuid.node[0] & 0x80)) {
		char *nodeid = (char *) MALLOC(19);
		sprintf(nodeid, "%02x:%02x:%02x:%02x:%02x:%02x", _uuid.node[0],
		    _uuid.node[1], _uuid.node[2], _uuid.node[3],
		    _uuid.node[4], _uuid.node[5]);
		return nodeid;
	    }
	}
	return NULL;
    }
}


/* return the nodeid from a RFC uuid */
/* ct 2006-11-21 implementation of NULL for FB 2.0 */
char *uuid1macmac(char *uuid)
{
    if (!uuid) {
	return NULL;
    } else {
	int v2;
	
	sscanf(&uuid[24], "%2x", &v2);
	if (check_uuid(uuid) && (uuid[14] == '1') && !(v2 & 0x80)) {
	    char *nodeid = (char *) MALLOC(18);
	    uuid_t _uuid;

	    guid_to__uuid(uuid, &_uuid);
	    sprintf(nodeid, "%02x:%02x:%02x:%02x:%02x:%02x", _uuid.node[0],
		    _uuid.node[1], _uuid.node[2], _uuid.node[3],
		    _uuid.node[4], _uuid.node[5]);
	    return nodeid;
	} else {
	    return NULL;
	}
    }
}

/* Return the variant and the version from a RFC uuid
* variants are:
*  0 NCS (reserved for backward compatibility)
* 10 The current variant, described used and produced on these pages.
* 110 Microsoft (reserved for backward compatibility)
* 111 reserved for further use
* versions are:
* 1  Time-based
*    a with real existing host identifier (IEEE 802 MAC-adress)
*    b with a random host identifier
* 2 DCE Security version (with POSIX UIDs)
* 3 Name-based (MD5 hash)
* 4 Random
* 5 Name-based (SHA-1 hash)
*
****************************************************************/
/* ct 2006-11-21 implementation of NULL for FB 2.0 */
char *uuidversion(char *uuid)
{
    if (!uuid) {
	return NULL;
    } else {
	char *version = (char *) MALLOC(254);
	int v1 = uuid[14];
	int v2;

	if (v1 == '1') {
	    sscanf(&uuid[24], "%2x", &v2);
	    if (v2 & 0x80)
		strcpy(version, "V1b");
	    else
		strcpy(version, "V1a");
	} else {
	    sprintf(version, "V%c", v1);
	}

	return version;
    }
}
                                                                                                                                                                                                                                                                                                                                             uuid_functions.h                                                                                    0000744 0000000 0000764 00000003071 10756255136 013113  0                                                                                                    ustar   root                            adhoc                                                                                                                                                                                                                  /*****************************************************************************
 * FreeAdhocUDF - copyright (c) 2004 - 2008 adhoc dataservice GmbH
 * Christoph Theuring / Peter Mandrella / Georg Horn
 * <http://www.udf.adhoc-data.de> eMail <udf@adhoc-data.de>
 *
 * File Name:	uuid_functions.h
 * Description: This header contains the prototype definitions
 *
 * This file is part of FreeAdhocUDF.
 * FreeAdhocUDF is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * FreeAdhocUDF is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with FreeAdhocUDF.  If not, see <http://www.gnu.org/licenses/>. 
*****************************************************************************/

int check_uuidcompr(char *uuidcompr);
int check_uuid(char *uuid);
char *uuid1mac();
char *uuid1maccompr();
char *uuid1rand();
char *uuid1randcompr();
char *uuid4compr();
char *uuid4();
char *compressuuid(char *uuid);
char *expanduuidcompr(char *uuidcompr);
ISC_QUAD *uuid1comprtimestamp(char *uuidcompr);
ISC_QUAD *uuid1timestamp(char *uuid);
char *uuid1maccomprmac(char *uuidcompr);
char *uuid1macmac(char *uuid);
char *uuidversion(char *uuid);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                       uuid.h                                                                                              0000744 0000000 0000764 00000005627 10756254674 011042  0                                                                                                    ustar   root                            adhoc                                                                                                                                                                                                                  /*****************************************************************************
 * FreeAdhocUDF - copyright (c) 2004 - 2008 adhoc dataservice GmbH
 * Christoph Theuring / Peter Mandrella / Georg Horn
 * <http://www.udf.adhoc-data.de> eMail <udf@adhoc-data.de>
 * Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc.
 * Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. &
 * Digital Equipment Corporation, Maynard, Mass.
 * Copyright (c) 1998 Microsoft.
 * 
 * File Name:	uuid.h
 * Description: This header contains the prototype definitions for uuid.c
 * and was originally written by the Open Software Foundation, Inc.
 * adapted for FreeAdhocUDF by Georg Horn 2006-10-20 
 * some changes made 2006 to integrate to the FreeAdhocUDF project 
 *
 * This file is part of FreeAdhocUDF.
 * FreeAdhocUDF is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * FreeAdhocUDF is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with FreeAdhocUDF.  If not, see <http://www.gnu.org/licenses/>. 
 *
 * Additional license for uuid.h 
 * To anyone who acknowledges that this file is provided "AS IS"
 * without any express or implied warranty: permission to use, copy,
 * modify, and distribute this file for any purpose is hereby
 * granted without fee, provided that the above copyright notices and
 * this notice appears in all source code copies, and that none of
 * the names of Open Software Foundation, Inc., Hewlett-Packard
 * Company, or Digital Equipment Corporation be used in advertising
 * or publicity pertaining to distribution of the software without
 * specific, written prior permission.  Neither Open Software
 * Foundation, Inc., Hewlett-Packard Company, Microsoft, nor Digital
 * Eqiupment Corporation makes any representations about the suitability
 * of this software for any purpose.
*****************************************************************************/

#undef uuid_t

typedef struct _uuid_t {
    unsigned32 time_low;
    unsigned16 time_mid;
    unsigned16 time_hi_and_version;
    unsigned8 clock_seq_hi_and_reserved;
    unsigned8 clock_seq_low;
    byte node[6];
} uuid_t;

/* generate a V1 UUID */
int uuid_create_v1(uuid_t *uuid, int rand_nodeid);

/* generate a V4 UUID */
int uuid_create_v4(uuid_t *uuid);

/* Compare two UUID's "lexically" and return
   -1   u1 is lexically before u2
    0   u1 is equal to u2
    1   u1 is lexically after u2
   Note:   lexical ordering is not temporal ordering!  */
//int uuid_compare(uuid_t * u1, uuid_t * u2);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         