/*
 * eb_convert.c
 *
 * This file is part of the Easy Database. It contains some routines
 * to convert a single string into fields and vice-versa
 *
 * Written by Mark Overmars
 *
 * Version 0.9
 * Last Changed: Sep  7, 1992
 */

#include "eb_main.h"

/*********
 *  int string_to_fields(char str[], char fields[][MAXFIELDLENGHT])
 *	Convert a string into a set of fields. Fields should be
 *	separated by FIELDSEP which can be escaped by placing an
 *	ESCAPE in front of it. Twice ESCAPE means the escape itself.
 *	The routine returns the number of fields.
 *		str		= the string to convert
 *		fields		= the fields in which to put the result
 *********/

int string_to_fields(char str[], char fields[][MAXFIELDLENGHT])
{
  int pos = 0, fnumb = 0;	/* current filed number and position */
  int strpos = 0;		/* position in str */
  
  /* Clear the fields */
  for (fnumb = 0; fnumb < MAXFIELDNUMB; fnumb++)
    fields[fnumb][0] = '\0';

  if (str == NULL) return 0;

  /* Convert the string */
  fnumb = 0;
  while (str[strpos] != '\0')
  {
    if (str[strpos] == FIELDSEP)
    {
      fields[fnumb][pos] = '\0';
      fnumb++; pos = 0;
      if (fnumb == MAXFIELDNUMB) return fnumb;
    }
    else if (str[strpos] == ESCAPE)
    {
      strpos++;
      fields[fnumb][pos++] = str[strpos];
    }
    else
      fields[fnumb][pos++] = str[strpos];
    if (pos == MAXFIELDLENGHT) pos--;
    strpos++;
  }
  fields[fnumb][pos] = '\0';
  return fnumb+1;
}

/*********
 *  void string_to_field(char str[], char field[], int fnumb)
 *	Gets field fnumb out of the string str.
 *		str		= the string to convert
 *		field		= the field in which to put the result
 *		fnumb		= the number of field required
 *********/

void string_to_field(char str[], char field[], int fnumb)
{
  /* POOR IMPLEMENTATION */
  int i;
  char ff[MAXFIELDNUMB][MAXFIELDLENGHT];	/* Temporary fields */
  string_to_fields(str,ff);
  i = 0;
  do field[i] = ff[fnumb][i]; while (field[i++] != '\0');
}

/*********
 *  void fields_to_string(char fields[][], char str[], int fnumb)
 *	Convert a set of fields int a string.
 *		fields		= the fields to convert
 *		str		= the string to put the result in
 *		fnumb		= number of fields
 *********/

int fields_to_string(char fields[][MAXFIELDLENGHT], char str[], int fnumb)
{
  int i;		/* Current field. */
  int pos;		/* Position in the field */
  int strpos = 0;	/* Position in the resutl string */
  
  for (i=0; i<fnumb; i++)
  {
     for (pos = 0; fields[i][pos] != '\0'; pos ++)
     {
       if (fields[i][pos] == FIELDSEP)
       {
         str[strpos++] = ESCAPE;
         str[strpos++] = FIELDSEP;
       }
       else if (fields[i][pos] == ESCAPE)
       {
         str[strpos++] = ESCAPE;
         str[strpos++] = ESCAPE;
       }
       else
         str[strpos++] = fields[i][pos];
     }
     if (i != fnumb-1) str[strpos++] = FIELDSEP;
  }
  str[strpos++] = '\0';
}
