/*
    dtaus.c - Belegloser Datenträgeraustausch mit einer Bank
    Copyright (c) 1996,8,2001-4,5,9  Martin Schulze <joey@infodrom.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.

    $Id$
 */

#include "dtaus.h"
#include "bigint.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <malloc.h>
#include "latex.h"

#define DEFAULT_EURO
#ifndef DEFAULT_EURO
int use_euro = 0;
#else
int use_euro = 1;
#endif

/*
 *  First: Some control structures
 */

typedef struct
{
  char *name;
  unsigned short int pos;
  unsigned short int len;
  int type;
} dtaus_record;

#define REC_A	1
#define REC_C	2
#define REC_E	3

#define REQ	1
#define OPT	2
#define IGN	3

dtaus_record recA[] = {
  {"Art", 5, 2, REQ},
  {"Name", 23, 27, REQ},
  {"Konto", 60, 10, REQ},
  {"BLZ", 7, 8, REQ},
  {"Referenz", 70, 10, OPT},
  {"Datum", 50, 6, IGN},
  {"Ausfuehrung", 95, 8, OPT},
  {"Currency", 127, 1, OPT},
  {"Euro", 127, 1, OPT},
  {"DM", 127, 1, OPT},
  {NULL, 0, 0, 0}
};

#define A_TRANS	0
#define A_NAME	1
#define A_KTO	2
#define A_BLZ	3
#define A_REF	4
#define A_DATE	5
#define A_TODO	6
#define A_CURR	7
#define A_EURO	8
#define A_DM	9
#define A_LEN	10
#define A_LOOP	7

dtaus_record recC[] = {
  {"Name", 93, 27, REQ},
  {"Konto", 21, 10, REQ},
  {"BLZ", 13, 8, REQ},
  {"Transaktion", 44, 5, REQ},
#ifndef DEFAULT_EURO
  {"Betrag", 50, 11, REQ},
#else
  {"Betrag", 79, 11, REQ},
#endif
  {"Zweck", 155, 27, REQ},
  {"myName", 128, 27, OPT},
  {"myKonto", 69, 10, OPT},
  {"myBLZ", 61, 8, OPT},
  {"Text", 187, 29, OPT},
  {"Extension", 216, 29, OPT},
  {"Currency", 182, 1, IGN},
#ifndef DEFAULT_EURO
  {"Betrag-Euro", 79, 11, IGN},
#else
  {"Betrag-DM", 50, 11, IGN},
#endif
  {NULL, 0, 0, 0}
};

#define C_NAME	0
#define C_KTO	1
#define C_BLZ	2
#define C_TRANS	3
#define C_VAL	4
#define C_ZWECK	5
#define C_MYNAM	6
#define C_MYKTO	7
#define C_MYBLZ	8
#define C_TEXT  9
#define C_EXT  10
#define C_EURO 11
#ifndef DEFAULT_EURO
#define C_EUR  12
#else
#define C_DM   12
#endif
#define C_LEN  13
#define C_LOOP 11

#define MAX_TEXT 14

dtaus_record recE[] = {
  {"Anzahl", 10, 7, IGN},
#ifndef DEFAULT_EURO
  {"Summe", 17, 13, IGN},
#else
  {"Summe", 64, 13, IGN},
#endif
  {"Kontos", 30, 17, IGN},
  {"BLZs", 47, 17, IGN},
#ifndef DEFAULT_EURO
  {"Summe-Euro", 64, 13, IGN},
#else
  {"Summe-DM", 17, 13, IGN},
#endif
  {NULL, 0, 0, 0}
};

#define E_COUNT	0
#define E_VAL	1
#define E_KTO	2
#define E_BLZ	3
#ifndef DEFAULT_EURO
#define E_EUR	4
#else
#define E_DM	4
#endif
#define E_LEN	5

/*
 *  Second: Some low level routines
 */

size_t dtaus_nextrec (void **buf, FILE *f)
{
  memset (buf, 0, 128);
  return fread(buf, 128, 1, f);
}

char *upcase(char *s)
{
  static char x[100];
  static char *xp;
  char *cp;

  for (cp=s,xp=x; *cp; cp++,xp++) {
    if (strchr(" 0123456789.,&-/+*$%ABCDEFGHIJKLMNOPQRSTUVWXYZ",*cp)) {
	*xp = *cp;
    } else if (strchr("abcdefghijklmnopqrstuvwxyz",*cp)) {
      *xp = toupper(*cp);
    } else if (strchr ("üÜäÄöÖß", *cp)) {
      switch (*cp) {
      case 'ü': *(xp++) = 'U'; *xp='E'; break;
      case 'Ü': *(xp++) = 'U'; *xp='E'; break;
      case 'ä': *(xp++) = 'A'; *xp='E'; break;
      case 'Ä': *(xp++) = 'A'; *xp='E'; break;
      case 'ö': *(xp++) = 'O'; *xp='E'; break;
      case 'Ö': *(xp++) = 'O'; *xp='E'; break;
      case 'ß': *(xp++) = 'S'; *xp='S'; break;
      }
    } else
      /*
       * Filter out all other characters since credit institutes won't
       * accept the file otherwise.
       */
      *xp = ' ';
  }
  *xp = '\0';

  return x;
}

char *downcase(char *s)
{
  static char x[100];
  char *cp;

  memset (x, 0, sizeof (x));
  strncpy (x, s, 99);
  
  for (cp=x;*cp;cp++)
    if (isupper(*cp))
      *cp = tolower(*cp);
  return x;
}

char *strip_spaces (char *s)
{
  int i;
  char *p;

  for (i=strlen(s);(s[i-1] == ' '||s[i-1] == '\t')&&i>0; i--)
    s[i-1] = '\0';
  for (p=s; *p==' '; p++);
  return p;
}

char *strip_zeros (char *s)
{
  char *p;

  for (p=s; *p=='0'; p++);
  return p;
}

char *strip_nondigits (char *s)
{
  char *p;
  char *x;

  for (x=s,p=s;*x;x++)
    if (isdigit (*x))
      *(p++) = *x;
  *(p++) = '\0';

  return s;
}

char dtaus_char (void *buf, unsigned int pos)
{
  static char res;
  char *bufp = (char *)buf;

  bufp+=pos;
  memcpy(&res, bufp, 1);
  return res;
}

char *string2real(char *s)
{
  static char res[20];
  char *cp = s;

  cp+=strlen(s)-2;
  strncpy(res, s, strlen(s)-2);
  res[strlen(s)-2] = '.';
  res[strlen(s)-1] = s[strlen(s)-2];
  res[strlen(s)] = s[strlen(s)-1];
  return res;
}

char *real2string(char *s)
{
  static char res[20];
  char *cp;
  char *xp;	/* only to avoid a GCC warning */

  strncpy(res, s, sizeof(res)-1);
  res[sizeof(res)-1] = 0;
  for (cp=res; *cp&&!(*cp == ',')&&!(*cp == '.');cp++);

  if ((cp-res) >= (sizeof(res)-3)) { 
    /* Bail out, since the number is too large, shouldn't be possible though. */
    fprintf (stderr, "Value %s too large.\n", res);
    exit (1);
  }

  if (*cp == '.' || *cp == ',') {
    if (*(cp+1)) {
      /* 1st decimal place */
      xp = cp+1;
      if (*xp && isdigit(*xp))
	*(cp++) = *xp;
      else
	*(cp++) = '0';
      /* 2nd decimal place */
      xp = cp+1;
      if (*xp && isdigit(*xp))
	*(cp++) = *xp;
      else
	*(cp++) = '0';
    } else {
      *(cp++) = '0';
      *(cp++) = '0';
    }
  } else {
    *(cp++) = '0';
    *(cp++) = '0';
  }
  *cp = '\0';
  return res;
}

/*
 * Return the last digit of the year as character
 */
char get_date_lastdigit()
{
  time_t timer;
  struct tm *loctime;

  timer = time ( NULL );
  loctime = localtime(&timer);
  return loctime->tm_year % 10 + '0';
}

char *string2trans (char *s)
{
  static char res[30];

  res[0] = '\0';
  if (!strcmp(s, "04000"))
    sprintf (res, "Abbuchung");
  else if (!strcmp(s, "05000"))
    sprintf (res, "Einzug");
  else if (!strcmp(s, "05005"))
    sprintf (res, "E-Cash");
  else if (!strcmp(s, "05006"))
    sprintf (res, "E-Cash-A");
  else if (!strcmp(s, "51000"))
    sprintf (res, "Gutschrift");
  else if (!strcmp(s, "53000"))
    sprintf (res, "Lohn");
  else if (!strncmp(s, "5400", 4))
    sprintf (res, "Vermögen %c",s[4]);
  /*  else if (!strcmp(s, "56000"))
    sprintf (res, ""); / * Überweisung öffentlicher Kassen */
  return res;
}

char *trans2string (char *s)
{
  static char res[30];
  char *cp;

  res[0] = '\0';
  if (!strcmp(s, "Abbuchung"))
    sprintf (res, "04000");
  else if (!strcmp(s, "Einzug"))
    sprintf (res, "05000");
  else if (!strcmp(s, "E-Cash"))
    sprintf (res, "05005");
  else if (!strcmp(s, "E-Cash-A"))
    sprintf (res, "05006");
  else if (!strcmp(s, "Gutschrift"))
    sprintf (res, "51000");
  else if (!strcmp(s, "Lohn"))
    sprintf (res, "53000");
  else {
    cp = NULL;
    if (!strncmp(s, "Vermögen", 8))
      cp = s+8;
    if (!strncmp(s, "Vermoegen", 9))
      cp = s+9;

    if (!cp) {
      fprintf (stderr, "Unbekannte Transaktion `%s'\n", res);
      exit (1);
    }

    /*
      Vermögen --> 5400<heutiges Jahr>
      Vermögen 8 -> 5400<8>
      Vermögen 2003 -> 5400<3>
     */

    if (*cp) while (!isspace(*cp)) cp++;
    while (isspace(*cp)) cp++;

    if (!*cp || !isdigit(*cp))
      sprintf (res, "5400%c",get_date_lastdigit());
    else {
      while (isdigit(*cp)) cp++;
      sprintf (res, "5400%c",*(cp-1));
    }
  }
  /*  else if (!strcmp(s, ""))
    sprintf (res, "56000"); / * Überweisung öffentlicher Kassen */
  return res;
}

char *string2ext (char *s)
{
  static char res[30];

  res[0] = '\0';
  if (!strcmp(s, "01"))
    sprintf (res, "Kunde");
  else if (!strcmp(s, "02"))
    sprintf (res, "Text");
  else if (!strcmp(s, "03"))
    sprintf (res, "Auftraggeber");
  return res;
}

char *ext2string (char *s)
{
  static char res[3];

  res[0] = '\0';
  if (!strcmp(s, "Kunde"))
    sprintf (res, "01");
  else if (!strcmp(s, "Text"))
    sprintf (res, "02");
  else if (!strcmp(s, "Auftraggeber"))
    sprintf (res, "03");
  return res;
}
    
unsigned long int dtaus_int(void *buf, unsigned int pos, unsigned int len)
{
  char tmp[30];
  char *bufp = (char *)buf;
  static unsigned long int res;

  bufp+=pos;
  memcpy(tmp, bufp, len);
  tmp[len] = '\0';
  sscanf(tmp, "%lu", &res);
  return res;
}

/*
 * returns the first word in this line, returns it and shortens the
 * line.
 */
char *extract_ident (char *line)
{
  char *c, *x, *y;
  static char word[30];

  if (strlen(line) > 0) {
    x = strchr (line, ' ');
    y = strchr (line, '\t');

    if (!x && !y) {
        strncpy(word, downcase(line), 29);
        line[0] = '\0';
        return word;
    }

    /* Check which index returns the lower value, and check if the
       value is non-NULL */
    if ((c = (x && x<y)?x:(y?y:x))) { 
      strncpy(word, line, c - line);
      word[c-line] = '\0';
      for (;*c == '\t' || *c == ' '; c++);
      for (x=line; *c; c++,x++)
	*x = *c;
      *x = '\0';
      strcpy(word, downcase(word));
      return word;
    }
    return NULL;
  }
  return line;
}

/*
 * Pads a string with zero's on the left side.
 */
char *padzeroclip (char *s, int len)
{
  char *p, *q;

  if (strlen(s) == len) return s;
  if (strlen(s) > len) {
      q=s+len;
      *(q--) = '\0';
      return s;
  }

  q=s+len;
  *(q--) = '\0';
  for (p=s+strlen(s)-1;p>=s;p--)
    *(q--)=*p;
  for (;q>=s;) *(q--)='0';
  return s;
}

int rec_index(char *ident, int type)
{
  int i;
  dtaus_record *rec = NULL;

  switch (type) {
  case REC_A:	rec = recA; break;
  case REC_C:	rec = recC; break;
  case REC_E:	rec = recE; break;
  }

  for (i=0; (rec[i].name); i++) {
    if (!strcmp(ident, downcase(rec[i].name)))
      return i;
  }

  return -1;
}

size_t control_nextline (void **buf, int len, FILE *f)
{
  char line[100];
  char tmp[100];
  char *cp;
  int i;

  memset (line, 0, sizeof(line));
  memset (buf, 0, len);
  cp = line;

  while (!strlen(line) && (cp = fgets(line, 100, f))) {
    if (strlen(line)) {
      if (line[0] != '#') {
	if (line[strlen(line)-1] != '\n') { 
	  strcpy(tmp, line);
	  while (tmp[strlen(tmp)-1] != '\n' && (cp = fgets(tmp, 100, f)));
	} else
	  line[strlen(line)-1] = '\0';
	if (line[strlen(line)-1] == '\r')
	  line[strlen(line)-1] = '\0';
	for (i=strlen(line);(line[i-1] == ' '||line[i-1] == '\t')&&i>0; i--)
	  line[i-1] = '\0';
      } else
	line[0] = '\0';
    }
  }
  for (cp=line; *cp==' '; cp++);

  if (strlen(cp)) {
    memcpy(buf, cp, strlen(cp));
    return 1;
  } else
    return 0;
}

/*
 * Return the current date nicely formatted
 */
char *get_date()
{
  static char res[10];
  time_t timer;
  struct tm *loctime;

  timer = time ( NULL );
  loctime = localtime(&timer);
  sprintf(res, "%02d.%02d.%02d", loctime->tm_mday, loctime->tm_mon+1, loctime->tm_year % 100);
  return res;
}

/*
 *  Prepare a record A according to the specs.
 *  See dtaus.txt for explanation
 */
void dtaus_prepareA (char *buf)
{
  int i;
  time_t timer;
  struct tm *loctime;
  char tmp[10];

  memset (buf, 0, 129);
  timer = time ( NULL );
  loctime = localtime(&timer);

  buf[0] = '0';
  buf[1] = '1';
  buf[2] = '2';
  buf[3] = '8';
  buf[4] = 'A';
  for (i=15;i<15+8; i++) buf[i] = '0';		/* A5 */
  sprintf(tmp, "%02d%02d%02d", loctime->tm_mday, loctime->tm_mon+1, loctime->tm_year % 100);
  for (i=0; i<6; i++) buf[50+i] = tmp[i];	/* A7 (Date) */
  for (i=56;i<56+4; i++) buf[i] = ' ';		/* A8 */
  for (i=70;i<70+10; i++) buf[i] = '0';		/* A10 */
  for (i=80;i<80+48; i++) buf[i] = ' ';		/* A11 */
  if (use_euro)
    buf[recA[A_CURR].pos] = '1';				/* A12 (Currency) */
  else
    buf[recA[A_CURR].pos] = ' ';				/* A12 (Currency) */
}

/*
 *  Prepare a record C according to the specs.
 *  See dtaus.txt for explanation
 */
void dtaus_prepareC (char *buf, int normaltext, int maxtext)
{
  int i;
  int appendix = 0;

  memset (buf, 0, 257);

  if (normaltext)
    appendix = 1;
  appendix += maxtext;
  i = 187 + (appendix * 29);

  /* Bail out if the number is too large, shouldn't be possible though */
  if (i >= 1000)
    exit (1);

  buf[0] = (i/1000)+48;i-=(i/1000)*100;
  buf[1] = (i/100)+48;i-=(i/100)*100;
  buf[2] = (i/10)+48;i-=(i/10)*10;
  buf[3] = i+48;
  buf[4] = 'C';

  for (i=31;i<31+13; i++) buf[i] = '0';		/* C6 */
  buf[49] = ' ';				/* C8 */
  for (i=50;i<50+11; i++) buf[i] = '0';		/* C9 (Betrag) */
  for (i=79;i<79+11; i++) buf[i] = '0';		/* C12 (Betrag Euro) */
  for (i=90;i<90+3; i++) buf[i] = ' ';		/* C13 */
  for (i=93;i<90+27; i++) buf[i] = ' ';		/* C14a (Kunde) */
  for (i=120;i<120+8; i++) buf[i] = ' ';	/* C14b */
  if (use_euro)
    buf[recC[C_EURO].pos] = '1';				/* C17a (Currency) */
  else
    buf[recC[C_EURO].pos] = ' ';				/* C17a (Currency) */
  for (i=183;i<183+2; i++) buf[i] = ' ';	/* C17b */
  for (i=187;i<187+(29*2); i++) buf[i] = ' ';	/* C19-C22 (misc text) */
  for (i=245;i<245+11; i++) buf[i] = ' ';	/* C23 */

  buf[185+0] = (appendix/10)+48;appendix-=(appendix/10)*10;
  buf[185+1] = appendix+48;
}

/*
 *  Prepare a record E according to the specs.
 *  See dtaus.txt for explanation
 */
void dtaus_prepareE (char *buf)
{
  int i;

  memset (buf, 0, 129);
  buf[0] = '0';
  buf[1] = '1';
  buf[2] = '2';
  buf[3] = '8';
  buf[4] = 'E';
  for (i=5;i<5+5; i++) buf[i] = ' ';	/* E3 */
  for (i=17;i<17+13; i++) buf[i] = '0';	/* E8 (Check Betrag) */
  for (i=64;i<64+13; i++) buf[i] = '0';	/* E8 (Check Euro) */
  for (i=77;i<77+51; i++) buf[i] = ' ';	/* E9 */
}

int dtaus_writeA(FILE *f, char **values)
{
  char buf[129];
  char tmp[30];
  int i;
  
  for (i=0; (recA[i].name); i++)
    if ((recA[i].type == REQ) && !values[i]) {
      fprintf (stderr, "Anfangsdatensatz ist nicht vollständig, kein %s.\n", recA[i].name);
      return 0;
    }
  if (!(((values[A_TRANS][0] == 'L')||(values[A_TRANS][0] == 'G'))
	&&((values[A_TRANS][1] == 'B')||(values[A_TRANS][1] == 'K')))) {
    fprintf (stderr, "Ungültiger Typ, nur LK, GK, LB oder GB erlaubt.\n");
    return 0;
  }

  i=A_NAME;if (values[i] && strlen(values[i]) > recA[i].len)
    values[i][recA[i].len] = '\0';

  dtaus_prepareA(buf);
  buf[5] = values[A_TRANS][0];
  buf[6] = values[A_TRANS][1];
  sprintf (tmp, "%s", padzeroclip (strip_nondigits (values[A_BLZ]),recA[A_BLZ].len));
  for (i=0; i<recA[A_BLZ].len; i++) buf[recA[A_BLZ].pos+i] = tmp[i];
  sprintf (tmp, "%-27.27s", upcase(values[A_NAME]));
  for (i=0; i<27; i++) buf[recA[A_NAME].pos+i] = tmp[i];
  if (values[A_TODO]) {
    sprintf (tmp, "%s", padzeroclip (strip_nondigits (values[A_TODO]),recA[A_TODO].len));
    for (i=0; i<recA[A_TODO].len; i++) buf[recA[A_TODO].pos+i] = tmp[i];
  }
  sprintf (tmp, "%s", padzeroclip (strip_nondigits (values[A_KTO]),recA[A_KTO].len));
  for (i=0; i<recA[A_KTO].len; i++) buf[recA[A_KTO].pos+i] = tmp[i];

  if (values[A_REF]) {
    sprintf (tmp, "%s", padzeroclip(strip_nondigits (values[A_REF]), recA[A_REF].len));
    for (i=0; i < recA[A_REF].len; i++) buf[recA[A_REF].pos+i] = tmp[i];
  }

  fputs(buf, f);
  return 1;
}

int dtaus_writeC(FILE *f, char **valuesA, char **values, char **text)
{
  char buf[257];
  char appendix[129];
  char tmp[30];
  int i, k;
  int maxtext = 0;
  int fieldnr;

  /* Just count */
  if (text) for (maxtext=0;text[maxtext];maxtext++);

#if DEBUG
  for (i=0; (recC[i].name); i++)
    if (values[i])
      printf ("%s: %s\n", recC[i].name, values[i]);
#endif

  for (i=0; (recC[i].name); i++)
    if ((recC[i].type == REQ) && !values[i]) {
      fprintf (stderr, "Datensatz ist nicht vollständig, kein %s.\n", recC[i].name);
      return 0;
    }
  sprintf (tmp, "%s", trans2string(values[C_TRANS]));
  if (!strlen(tmp)) {
    fprintf (stderr, "Ungültige Transaktion, nur Abbuchung, Einzug, E-Cash, E-Cash-A, Gutschrift und Lohn erlaubt.\n");
    return 0;
  }

  i=C_TEXT;if (values[i] && strlen(values[i]) > recC[i].len)
    values[i][recC[i].len-2] = '\0';
  i=C_ZWECK;if (values[i] && strlen(values[i]) > recC[i].len)
    values[i][recC[i].len] = '\0';
  i=C_MYNAM;if (values[i] && strlen(values[i]) > recC[i].len)
    values[i][recC[i].len] = '\0';
  i=C_TEXT;if (values[i] && strlen(values[i]) > recC[i].len)
    values[i][recC[i].len] = '\0';

  dtaus_prepareC (buf, values[C_TEXT] != NULL, maxtext);
  for (i=0; i<5; i++) buf[recC[C_TRANS].pos+i] = tmp[i];
  if (values[C_MYBLZ])
    sprintf (tmp, "%s", padzeroclip (strip_nondigits (values[C_MYBLZ]),8));
  else
    sprintf (tmp, "%s", padzeroclip (strip_nondigits (valuesA[A_BLZ]),8));
  for (i=0; i<recC[C_MYBLZ].len; i++) buf[5+i] = tmp[i];
  for (i=0; i<recC[C_MYBLZ].len; i++) buf[recC[C_MYBLZ].pos+i] = tmp[i];
  sprintf (tmp, "%s", padzeroclip (strip_nondigits (values[C_BLZ]),8));
  for (i=0; i<recC[C_BLZ].len; i++) buf[recC[C_BLZ].pos+i] = tmp[i];
  sprintf (tmp, "%s", padzeroclip (strip_nondigits (values[C_KTO]),10));
  for (i=0; i<recC[C_KTO].len; i++) buf[recC[C_KTO].pos+i] = tmp[i];
  sprintf (tmp, "%s", padzeroclip (real2string(values[C_VAL]),11));
#ifndef DEFAULT_EURO
  if (!use_euro)
    for (i=0; i<recC[C_VAL].len; i++) buf[recC[C_VAL].pos+i] = tmp[i];
  else
    for (i=0; i<recC[C_EUR].len; i++) buf[recC[C_EUR].pos+i] = tmp[i];
#else
  if (use_euro)
    for (i=0; i<recC[C_VAL].len; i++) buf[recC[C_VAL].pos+i] = tmp[i];
  else
    for (i=0; i<recC[C_DM].len; i++) buf[recC[C_DM].pos+i] = tmp[i];
#endif
  if (values[C_MYKTO])
    sprintf (tmp, "%s", padzeroclip (strip_nondigits (values[C_MYKTO]),10));
  else
    sprintf (tmp, "%s", padzeroclip (strip_nondigits (valuesA[A_KTO]),10));
  for (i=0; i<recC[C_MYKTO].len; i++) buf[recC[C_MYKTO].pos+i] = tmp[i];
  sprintf (tmp, "%-27.27s", upcase(values[C_NAME]));
  for (i=0; i<recC[C_NAME].len; i++) buf[recC[C_NAME].pos+i] = tmp[i];
  if (values[C_MYNAM])
    sprintf (tmp, "%-27.27s", upcase(values[C_MYNAM]));
  else
    sprintf (tmp, "%-27.27s", upcase(valuesA[A_NAME]));
  for (i=0; i<recC[C_MYNAM].len; i++) buf[recC[C_MYNAM].pos+i] = tmp[i];
  sprintf (tmp, "%-27.27s", upcase(values[C_ZWECK]));
  for (i=0; i<recC[C_ZWECK].len; i++) buf[recC[C_ZWECK].pos+i] = tmp[i];

  if (values[C_TEXT]) {
    buf[recC[C_TEXT].pos+0] = '0';
    buf[recC[C_TEXT].pos+1] = '2';
    sprintf (tmp, "%-27.27s", upcase(values[C_TEXT]));
    for (i=0; i<recC[C_TEXT].len-2; i++) buf[recC[C_TEXT].pos+2+i] = tmp[i];
  }

  if (text) {
    buf[recC[C_EXT].pos+0] = '0';
    buf[recC[C_EXT].pos+1] = '2';
    sprintf (tmp, "%-27.27s", upcase(text[0]));
    for (i=0; i<recC[C_EXT].len-2; i++) buf[recC[C_EXT].pos+2+i] = tmp[i];
  }

  fputs(buf, f);

  if (text && maxtext > 1) {
    fieldnr=1;
    while (fieldnr<maxtext) {
      memset (appendix, ' ', 128);
      appendix[128] = '\0';
      for (k=0; k<4 && (fieldnr+k)<maxtext; k++) {
	sprintf (tmp, "%-27.27s", upcase(text[fieldnr+k]));
	appendix[k*29] = '0';
	appendix[(k*29)+1] = '2';
	for (i=0; i<recC[C_TEXT].len-2; i++) appendix[(k*29)+2+i] = tmp[i];
      }
      fputs(appendix, f);
      fieldnr += k;
    }
  }

  return 1;
}

int dtaus_writeE(FILE *f, int count, bigint sum, bigint blz, bigint kto)
{
  char buf[129];
  char tmp[30];
  int i;
  
  dtaus_prepareE(buf);

  sprintf (tmp, "%07d", count);
  for (i=0; i<recE[E_COUNT].len; i++) buf[recE[E_COUNT].pos+i] = tmp[i];
  bigint_sprintf (tmp, "%s", sum);
  padzeroclip (tmp,13);
#ifndef DEFAULT_EURO
  if (!use_euro)
    for (i=0; i<recE[E_VAL].len; i++) buf[recE[E_VAL].pos+i] = tmp[i];
  else
    for (i=0; i<recE[E_EUR].len; i++) buf[recE[E_EUR].pos+i] = tmp[i];
#else
  if (use_euro)
    for (i=0; i<recE[E_VAL].len; i++) buf[recE[E_VAL].pos+i] = tmp[i];
  else
    for (i=0; i<recE[E_DM].len; i++) buf[recE[E_DM].pos+i] = tmp[i];
#endif
  bigint_sprintf (tmp, "%s", kto);
  padzeroclip (tmp,17);
  for (i=0; i<recE[E_KTO].len; i++) buf[recE[E_KTO].pos+i] = tmp[i];
  bigint_sprintf (tmp, "%s", blz);
  padzeroclip (tmp,17);
  for (i=0; i<recE[E_BLZ].len; i++) buf[recE[E_BLZ].pos+i] = tmp[i];

  fputs(buf, f);
  return 1;
}

void printctln(FILE *f, char *field, char *value)
{
  if (strlen(field) && strlen(value))
    fprintf(f, "  %s\t%s\n", field, value);
}

/*
 * one date line, format it properly
 */
void printctlndate(FILE *f, char *field, char *value)
{
  char mydate[11];
  int i;

  if (!strlen(field) || !strlen(value))
    return;

  for (i=0;isspace (value[i]) && i<= strlen (value); i++);
  if (i == strlen (value))
    return;

  memset (mydate, 0, sizeof (mydate));
  if (strlen (value) == 6) {
    mydate[0] = value[0];
    mydate[1] = value[1];
    mydate[2] = '.';
    mydate[3] = value[2];
    mydate[4] = value[3];
    mydate[5] = '.';
    mydate[6] = value[4];
    mydate[7] = value[5];
    fprintf(f, "  %s\t%s\n", field, mydate);
  } else if (strlen (value) == 8) {
    mydate[0] = value[0];
    mydate[1] = value[1];
    mydate[2] = '.';
    mydate[3] = value[2];
    mydate[4] = value[3];
    mydate[5] = '.';
    mydate[6] = value[4];
    mydate[7] = value[5];
    mydate[8] = value[6];
    mydate[9] = value[7];
    fprintf(f, "  %s\t%s\n", field, mydate);
  } else {
    fprintf (stderr, "Broken date field: %s\n", value);
    fprintf(f, "  %s\t%s\n", field, value);
  }
}


/*
 *  Third: Some high level routines
 */

void dtaus2control (char *cdtaus, char *ccontrol)
{
  FILE *fdtaus, *fcontrol;
  char *buf;
  char *bufp;
  char tmp[30];
  char x[30];
  int index;
  int extC;
  div_t res;

  if (!cdtaus) {
    if (!(fdtaus = fopen("DTAUS0.TXT", "r")))
      if (!(fdtaus = fopen("dtaus0.txt", "r")))
	return;
  } else {
    if (!strcmp (cdtaus, "-"))
      fdtaus = stdin;
    else
      if (!(fdtaus = fopen(cdtaus, "r")))
	return;
  }
  if (!ccontrol) 
    fcontrol = stdout;
  else
    if (!strcmp (ccontrol, "-"))
      fcontrol = stdout;
    else
      if (!(fcontrol = fopen(ccontrol, "w")))
	return;
  if ((buf = (char *)malloc (512)) == NULL)
    return;

  /* 
   * Record A lesen
   */
  if (dtaus_nextrec((void *)buf, fdtaus) == 1) {
    if (dtaus_char(buf,4) == 'A') {
      fprintf(fcontrol, "BEGIN {\n");
      bufp = buf;

      for (index=A_TRANS; index < A_LOOP; index++) {
	bufp = buf + recA[index].pos;
	memcpy(tmp, bufp, recA[index].len); tmp[recA[index].len] = '\0';
	if (index == A_DATE || index == A_TODO)
	  printctlndate(fcontrol, recA[index].name, tmp);
	else
	  printctln(fcontrol, recA[index].name, strip_zeros(strip_spaces(tmp)));
      }

      bufp = buf + recA[A_CURR].pos;
      if (*bufp == '1') {
	use_euro = 1;
	fprintf(fcontrol, "  Euro\n");
      } else {
	use_euro = 0;
	fprintf(fcontrol, "  DM\n");
      }

      fprintf(fcontrol, "}\n\n");
    } else {
      fprintf (stderr, "Datei fängt nicht mit dem Anfangsdatensatz an.\n");
      return;
    }
  } else {
    fprintf (stderr, "Der Anfangsdatensatz ist kaputt.\n");
    return;
  }

  /*
   * Record C lesen
   */
  if (dtaus_nextrec((void *)buf, fdtaus) == 1) {
    while (dtaus_char(buf,4) == 'C') {
      bufp = buf + 128;
      if (dtaus_nextrec((void *)bufp, fdtaus) != 1) {
	fprintf (stderr, "Der zweite Teil der Transaktion ist kaputt.\n");
	return;
      } else {
	fprintf(fcontrol, "{\n");

	for (index=C_NAME; index < C_LOOP; index++) {
	  if (index == C_TEXT || index == C_EXT)
	    continue;
#ifndef DEFAULT_EURO
	  if (use_euro && index == C_VAL)
	    index = C_EUR;
#else
	  if (!use_euro && index == C_VAL)
	    index = C_DM;
#endif
	  bufp = buf + recC[index].pos;
	  memcpy(tmp, bufp, recC[index].len); tmp[recC[index].len] = '\0';

	  /*
	   * C_EUR and C_DM are outside of the loop, can only be
	   * selected for the non-default currency, but the value
	   * should be stored in the normal record field.
	   */
#ifndef DEFAULT_EURO
	  if (index == C_EUR)
#else
	  if (index == C_DM)
#endif
	    printctln(fcontrol, recC[C_VAL].name, strip_zeros(string2real(tmp)));
	  else if (index == C_VAL)
	    printctln(fcontrol, recC[index].name, strip_zeros(string2real(tmp)));
	  else if (index == C_TRANS)
	    printctln(fcontrol, recC[index].name, strip_zeros(string2trans(tmp)));
	  else
	    printctln(fcontrol, recC[index].name, strip_zeros(strip_spaces(tmp)));
#ifndef DEFAULT_EURO
	  if (use_euro && index == C_EUR)
	    index = C_VAL;
#else
	  if (!use_euro && index == C_DM)
	    index = C_VAL;
#endif
	}

	for (index=C_TEXT; index <= C_EXT; index++) {
	  if (!(dtaus_char(buf,recC[index].pos) == ' ')) {
	    bufp = buf + recC[index].pos;
	    memcpy(x, bufp, 2); tmp[2] = '\0'; bufp+=2;
	    memcpy(tmp, bufp, recC[index].len-2); tmp[recC[index].len-2] = '\0';
	    printctln(fcontrol, string2ext(x), strip_spaces(tmp));
	  }
	}

	/* Number of extension records for this C record */
	extC = dtaus_int(buf, 185, 2);
	extC -= 2;
	if (extC > 0) {
	  res = div (extC, 4);
	  extC = res.quot;
	  if (res.rem) extC++;
	}
      }
      if (dtaus_nextrec((void *)buf, fdtaus) != 1)
	memset (buf, 0, sizeof(buf));

      /*
       * Are there extension records that we have to check?
       *
       * 2nd half of the AND is wrong, but since dtaus < 0.5 wrote 01
       *     instead of 00 we should let it in so it can read its own
       *     old files...  *sigh*
       */
      while (extC > 0 && dtaus_char(buf,4) != 'C' && dtaus_char(buf,4) != 'E') {
	for (index=0; index < 4; index++) {
	  if ((dtaus_char(buf,index*29) != ' ')) {
	    bufp = buf + index*29;
	    memcpy(x, bufp, 2); tmp[2] = '\0'; bufp+=2;
	    memcpy(tmp, bufp, recC[C_TEXT].len-2); tmp[recC[C_TEXT].len-2] = '\0';
	    printctln(fcontrol, string2ext(x), strip_spaces(tmp));
	  }
	}
	if (dtaus_nextrec((void *)buf, fdtaus) != 1)
	  memset (buf, 0, sizeof(buf));
	extC--;
      }
      fprintf(fcontrol, "}\n");
    }
  }

  /*
   * Record E lesen
   *   (gelesen ist er eigentlich schon...)
   */
  if (dtaus_char(buf,4) == 'E') {
    if (dtaus_char(buf,4) == 'E') {
      fprintf(fcontrol, "\nEND {\n");

      for (index=E_COUNT; index <= E_BLZ; index++) {
#ifndef DEFAULT_EURO
	if (use_euro && index == E_VAL)
	  index = E_EUR;
#else
	if (!use_euro && index == E_VAL)
	  index = E_DM;
#endif

	bufp = buf + recE[index].pos;
	memcpy(tmp, bufp, recE[index].len); tmp[recE[index].len] = '\0';

#ifndef DEFAULT_EURO
	if (index == E_VAL || index == E_EUR)
#else
	if (index == E_VAL || index == E_DM)
#endif
	  printctln(fcontrol, recE[E_VAL].name, strip_zeros(string2real(tmp)));
	else
	  printctln(fcontrol, recE[index].name, strip_zeros(tmp));
#ifndef DEFAULT_EURO
	  if (use_euro && index == E_EUR)
	    index = E_VAL;
#else
	  if (!use_euro && index == E_DM)
	    index = E_VAL;
#endif
      }

      fprintf(fcontrol, "}\n");
    } else {
      fprintf (stderr, "Das ist kein Abschlußdatensatz.\n");
      return;
    }
  } else {
    fprintf (stderr, "Der Abschlußdatensatz ist leer oder kaputt.\n");
    return;
  }
  fclose(fcontrol);
  fclose(fdtaus);
}

int control2dtaus (char *ccontrol, char *cdtaus, char *cbeleg, char *ccheck, char *latex)
{
  FILE *fdtaus, *fcontrol, *fbeleg, *fcheck;
  void *buf;
  char *ident;
  int  recindex;
  char line[100];
  char *valA[A_LEN], *valC[C_LEN];
  int count;
  bigint sum_val, sum_blz, sum_kto, bi;
  char **text = NULL;
  char *cp;
  int textindex = 0;
  int len, i;
  char *type = NULL;
  char *currency = NULL;
  char date_todo[11];
  char ssum_val[30], ssum_kto[30], ssum_blz[30];

  if (!cdtaus) {
    if (!(fdtaus = fopen("dtaus0.txt", "w")))
      return 0;
  } else {
    if (!strcmp (cdtaus, "-"))
      fdtaus = stdout;
    else
      if (!(fdtaus = fopen(cdtaus, "w")))
	return 0;
  }
  if (!ccontrol) {
    if (!(fcontrol = fopen("dtaus0.ctl", "r")))
      if (!(fcontrol = fopen("DTAUS0.CTL", "r")))
	return 0;
  } else {
    if (!strcmp (ccontrol, "-"))
      fcontrol = stdin;
    else
      if (!(fcontrol = fopen(ccontrol, "r")))
	return 0;
  }
  if (!cbeleg) {
    if (!(fbeleg = fopen("dtaus0.doc", "w")))
      return 0;
  } else {
    if (!(fbeleg = fopen(cbeleg, "w")))
      return 0;
  }
  if (!ccheck)
    fcheck = stdout;
  else
    if (!(fcheck = fopen(ccheck, "w")))
      return 0;


  if ((buf = (char *)malloc (512)) == NULL)
    return 0;

  /* 
   * Record A lesen
   */
  memset (valA, 0, sizeof(valA));
  control_nextline ((void *)line, 100, fcontrol);
  ident = extract_ident(line);
  if (!strcmp(ident, "begin") && (line[0] == '{')) {
    control_nextline ((void *)line, 100, fcontrol);
    while (strlen(line) && line[0] != '}') {
      ident = extract_ident(line);
      if ((recindex = rec_index(ident, REC_A)) != -1)
	{
	if (recA[recindex].type != IGN)
	  if ((valA[recindex] = (char *)malloc (strlen(line)+1)) != NULL)
	    strcpy(valA[recindex], line);
	} else {
	  if (! strcasecmp (ident, "euro"))
	    use_euro = 1;
	  if (! strcasecmp (ident, "dm"))
	    use_euro = 0;
	}
      control_nextline ((void *)line, 100, fcontrol);
    }
    if (((recindex = rec_index("art", REC_A)) != -1) && valA[recindex] && strlen(valA[recindex])) {
      if (valA[recindex][0] == 'L')
	type = strdup ("Sammeleinziehungsauftrag");
      else if (valA[recindex][0] == 'G')
	type = strdup ("Sammelueberweisungsauftrag");
      else
	type = strdup ("Sammelauftrag");

      if (use_euro)
	currency = strdup ("Euro");
      else
	currency = strdup ("DM");

      if (valA[A_TODO])
	sprintf (date_todo, valA[A_TODO]);
      else
	memset (date_todo, 0, sizeof (date_todo));

      fprintf(fbeleg, "\n\n");
      fprintf(fbeleg, "\n    Begleitzettel\n\n");
      fprintf(fbeleg, "\n    Belegloser Datentraegeraustausch\n\n");
      fprintf(fbeleg, "\n    %s\n\n", type);
      fprintf(fbeleg, "\n    VOL ........................:\n");
      fprintf(fbeleg, "\n    Erstellungsdatum ...........: %s\n", get_date());
      if (strlen(date_todo)) {
	fprintf(fbeleg, "\n    Ausfuehrungsdatum ..........: %s\n", date_todo);
      }
      fprintf(fbeleg, "\n    Waehrung ...................: %s\n", currency);
    }
    if (!dtaus_writeA(fdtaus, valA)) {
      fprintf (stderr, "Konnte den Anfangsdatensatz nicht schreiben.\n");
      return 0;
    }

    fprintf (fcheck, "\n\n\n");
    if (valA[recindex][0] == 'L')
      fprintf (fcheck, "    Sammeleinziehungsauftrag\n\n");
    else if (valA[recindex][0] == 'G')
      fprintf (fcheck, "    Sammelueberweisungsauftrag\n\n");
    else
      fprintf (fcheck, "    Sammelauftrag\n\n");
    fprintf (fcheck, "    Erstellungsdatum : %s\n\n", get_date());
    if (use_euro)
      fprintf (fcheck, "    Waehrung         : Euro\n\n\n");
    else
      fprintf (fcheck, "    Waehrung         : DM\n\n\n");
    fprintf (fcheck, "     %-10s  %-8s  %-30s   %12s\n", "Kontonr.", "BLZ", "Name", "Betrag");
    fprintf (fcheck, "    --------------------------------------------------------------------\n");
  } else {
    fprintf (stderr, "Datei fängt nicht mit dem Anfangsdatensatz (BEGIN) an.\n");
    return 0;
  }

  /* 
   * Record C lesen
   */
  count = 0;
  sum_val = bigint_int(0);
  sum_blz = bigint_int(0);
  sum_kto = bigint_int(0);
  memset (valC, 0, sizeof(valC));
  control_nextline ((void *)line, 100, fcontrol);
  if (line[0] == '{') {
    while (strlen(line) && line[0] == '{') {
      control_nextline ((void *)line, 100, fcontrol);
      if (text) {
	for (textindex=0; textindex < MAX_TEXT && text[textindex]; textindex++)
	  free (text[textindex]);
	free (text);
	text = NULL;
      }
      while (strlen(line) && line[0] != '}') {
	ident = extract_ident(line);
	if ((recindex = rec_index(ident, REC_C)) != -1)
	  if (recC[recindex].type != IGN) {
	    /*
	     * Special exception to support multiple Text fields
	     */
	    if (recindex == C_TEXT && valC[recindex]) {
	      if (!text) {
		if ((text = (char **)malloc ((MAX_TEXT+1) * sizeof (char *))) == NULL)
		  return 0;
		else {
		  textindex = 0;
		  memset (text, 0, (MAX_TEXT+1) * sizeof (char *));
		}
	      }
	      if (textindex < MAX_TEXT) {
		if ((cp = (char *)malloc (strlen (line) + 1)) == NULL)
		  return 0;
		strcpy (cp, line);
		cp[strlen (line)] = '\0';
		text[textindex++] = cp;
	      }
	    } else {
	      len = strlen(line);
	      if (recindex == C_VAL) {
		/* Convert commas to dots for later processing */
		for (i=0; line[i]; i++) if (line[i] == ',') line[i] = '.';

		if ((cp = strchr (line, '.')) == NULL) {
		  if (strlen(line) > 9) {
		    fprintf (stderr, "Betrag %s zu gross (max. 9 Stellen)\n", line);
		    return 0;
		  }
		  if ((valC[recindex] = (char *)malloc (strlen(line)+4)) == NULL)
		    return 0;
		  sprintf (valC[recindex], "%s.00", line);
		} else if ( ((len = cp - line + 3)) < strlen (line)) {
		  if (cp - line > 9) {
                    fprintf (stderr, "Betrag %s zu gross (max. 9.2 Stellen)\n", line);
                    return 0;
		  }
		  if ((valC[recindex] = (char *)malloc (len+1)) == NULL)
                    return 0;
                  strncpy (valC[recindex], line, len);
		  valC[recindex][len] = '\0';
		} else {
		  if (cp - line > 9) {
                    fprintf (stderr, "Betrag %s zu gross (max. 9.2 Stellen)\n", line);
                    return 0;
		  }
                  if ((valC[recindex] = (char *)malloc (strlen(line)+1)) == NULL)
                    return 0;
		  strcpy(valC[recindex], line);
		}
	      } else {
		if ((valC[recindex] = (char *)malloc (strlen(line)+1)) == NULL)
		  return 0;
		strcpy(valC[recindex], line);
	      }
	    }
	  }
	control_nextline ((void *)line, 100, fcontrol);
      }
      if (!dtaus_writeC(fdtaus, valA, valC, text)) {
	fprintf (stderr, "Konnte den regulären Datensatz nicht schreiben.\n");
	return 0;
      }
      count++;
      bi = bigint_string(real2string(valC[C_VAL])); sum_val = bigint_add(sum_val, bi);
      bi = bigint_string(valC[C_BLZ]); sum_blz = bigint_add(sum_blz, bi);
      bi = bigint_string(valC[C_KTO]); sum_kto = bigint_add(sum_kto, bi);

      fprintf (fcheck, "     %10s  %8s  %-30s   %12s\n", valC[C_KTO], valC[C_BLZ], valC[C_NAME], valC[C_VAL]);
      for (recindex=0; recindex<C_LEN; recindex++)
	if (valC[recindex])
	  free(valC[recindex]);
      memset (valC, 0, sizeof(valC));
      control_nextline ((void *)line, 100, fcontrol);
    }
  } else {
    fprintf (stderr, "Kein regulärer Datensatz?\n");
    return 0;
  }

  /* 
   * Record E lesen
   */
  dtaus_writeE(fdtaus, count, sum_val, sum_blz, sum_kto);
  fprintf (fcheck, "    --------------------------------------------------------------------\n");
  fprintf (fbeleg, "\n    Anzahl .....................: %d\n", count);
  bigint_sprintf (ssum_val, "%s", sum_val);
  recindex=strlen(ssum_val);
  ssum_val[recindex+1] = '\0';
  ssum_val[recindex] = ssum_val[recindex-1];
  ssum_val[recindex-1] = ssum_val[recindex-2];
  ssum_val[recindex-2] = '.';
  fprintf (fcheck, "     %-52s %14s\n", "Summe", ssum_val);
  fprintf (fbeleg, "\n    Summe ......................: %s\n", ssum_val);
  bigint_sprintf (ssum_kto, "%s", sum_kto);
  fprintf (fbeleg, "\n    Kontrollsumme Kontonummern .: %s\n", ssum_kto);
  bigint_sprintf (ssum_blz, "%s", sum_blz);
  fprintf (fbeleg, "\n    Kontrollsumme Bankleitzahlen: %s\n", ssum_blz);
  fprintf (fbeleg, "\n    Unsere Kontonummer .........: %s\n", valA[A_KTO]);
  fprintf (fbeleg, "\n    Unsere Bankleitzahl ........: %s\n", valA[A_BLZ]);
  fprintf (fbeleg, "\n\n\n\n\n    __________________________________________________\n");
  fprintf (fbeleg, "    Ort, Datum                     Unterschrift\n");

  if (latex)
    generate_latex_receipt (latex, type, get_date(), date_todo,
			    currency, count,
			    ssum_val, ssum_kto, ssum_blz,
			    valA[A_KTO], valA[A_BLZ]);

  for (recindex=0; recindex<A_LEN; recindex++)
    if (valA[recindex])
      free(valA[recindex]);
  fclose(fdtaus);
  fclose(fcontrol);
  fclose(fbeleg);
  if (ccheck)
    fclose(fcheck);
  return count;
}
