/*
 * eb_file.c
 *
 * This file is part of the Easy Database. It contains the routines
 * that deal with loading, saving and printing the database or selections.
 *
 * Written by Mark Overmars
 *
 * Version 1.0
 * Last Changed: Sep 25, 1992
 */

#include <stdlib.h>
#include <stdio.h>
#include "forms.h"
#include "eb_main.h"

/***************************** INTERNAL ROUTINES ************************/

/*********
 *  void clear_database()
 *	Clears the database.
 *********/

static void clear_database()
{
  recordnumb = 0;
  selectlevel = 0;
  currentrecord = 0;
  deletioncount = -1;
  fieldnumb = 0;
}

/*********
 *  void new_database()
 *	Lets the user define the fields in a new, empty database.
 *********/

static void new_database()
{
  clear_database();
  while (fieldnumb == 0)
  {
    change_database_layout();
    if (fieldnumb == 0) 
	fl_show_message("Cannot handle databases without fields!", "", "");
  }
}

/***************************** EXTERNAL ROUTINES ************************/

/*********
 *  void init_database()
 *	Initializes the database. Should be called before anything else.
 *********/

void init_database()
{
  int i;
  clear_database();
  for (i=0; i<MAXRECORD; i++) database[i].dsize = 0;
}

/*********
 *  int load_database(char fname[])
 *	Loads a database file into the database. Returns whether successful.
 *		fname		= name of the file
 *********/

int load_database(char fname[])
{
  char str[MAXSTRINGLENGHT];
  char ff[MAXFIELDNUMB][MAXFIELDLENGHT];
  FILE *fl;

  fl = fopen(fname,"r");
  if (fl == NULL)
  {
    if (fl_show_question("File does not exist.",
				"Should I create a new database?",""))
      new_database();
    else
      return FALSE;
  }
  else
  {
    if (fgets(str,MAXSTRINGLENGHT,fl) == NULL)
    {
      fclose(fl);
      if (fl_show_question("File is empty.",
				"Should I create a new database?",""))
        new_database();
      else
        return FALSE;
    }
    else
    {
      clear_database();
      str[strlen(str)-1] = '\0';
      change_record(0,str);
      fieldnumb = string_to_fields(str,ff);
      
      while (fgets(str,MAXSTRINGLENGHT,fl) != NULL)
      {
        str[strlen(str)-1] = '\0';
        change_record(++recordnumb,str);
	database[recordnumb].level = selectlevel;
      }
      fclose(fl);
    }
  }

  /* Take care of at least one record */
  changed = 0;
  if (recordnumb == 0)
  {
    change_record(++recordnumb,"\0");
    database[recordnumb].level = selectlevel;
    changed = 1;
  }
  currentrecord = 1;
  return TRUE;
}

/*********
 *  int merge_database(char fname[])
 *	Merges a database file with the database. Returns whether successful.
 *		fname		= name of the file
 *********/

int merge_database(char fname[])
{
  char str[MAXSTRINGLENGHT];
  char ff[MAXFIELDNUMB][MAXFIELDLENGHT];
  FILE *fl;

  fl = fopen(fname,"r");
  if (fl == NULL)
  {
    fl_show_message("File does not exist.", "No records merged.","");
    return FALSE;
  }
  if (fgets(str,MAXSTRINGLENGHT,fl) == NULL)
  {
    fclose(fl);
    fl_show_message("File is empty.", "No records merged.","");
    return FALSE;
  }
  
  while (fgets(str,MAXSTRINGLENGHT,fl) != NULL)
  {
    str[strlen(str)-1] = '\0';
    change_record(++recordnumb,str);
    database[recordnumb].level = selectlevel;
  }
  fclose(fl);
  changed = 1;
  return TRUE;
}


/*********
 *  int save_database(char fname[])
 *	Saves the whole database in a file. Returns whether successful.
 *		fname		= name of the file
 *********/

int save_database(char fname[])
{
  level_zero();
  if (save_selection(fname)) changed = 0;
}

/*********
 *  int save_selection(char fname[])
 *	Saves the current selection in the database to a file. Returns
 *	whether successful.
 *		fname		= name of the file
 *********/

int save_selection(char fname[])
/* Saves the current selection. */
{
  int i;
  FILE *fl;
  char backupstr[1024];
  if ((fl = fopen(fname,"r")) != NULL)
  {
    fclose(fl);
    sprintf(backupstr, "cp %s %s.bak", fname, fname);
    system(backupstr);
  }
  fl = fopen(fname,"w");
  if (fl == NULL) return FALSE;
  for (i=0; i<=recordnumb; i++)
    if (i == 0 || database[i].level == selectlevel)
      fprintf(fl,"%s\n",database[i].data);
  fclose(fl);
  return TRUE;
}


/*********
 *  void print_selection(char fname[], int format)
 *	Prints the current selection according to format into a file. The
 *	following formats are supported: 1 = LaTeX, 2 = a list, 3 = records.
 *		fname		= file to write output to
 *		format		= printing format
 *********/

void print_selection(char fname[],int format)
{
  char ff[MAXFIELDNUMB][MAXFIELDLENGHT];
  char ff2[MAXFIELDNUMB][MAXFIELDLENGHT];
  int i,field,len = 0;

  FILE *fl;
  fl = fopen(fname,"w");
  if (fl == NULL) return;

  /* find longest field name */
  string_to_fields(database[0].data,ff);
  for (field = 0; field < fieldnumb; field++)
    if (strlen(ff[field]) > len) len = strlen(ff[field]);

  for (i=1; i<=recordnumb; i++)
    if (database[i].level == selectlevel)
    {
      string_to_fields(database[i].data,ff2);
      switch (format) {
	case 1: /* LaTeX */
	  fprintf(fl,"\\record\n");
      	  for (field = 0; field < fieldnumb; field++)
	    fprintf(fl,"{%s}\n", ff2[field]);
	  break;
	case 2: /* List */
      	  for (field = 0; field < fieldnumb; field++)
	  {
	    fprintf(fl,"%s", ff2[field]);
	    if (field < fieldnumb-1) fprintf(fl,"|");
	  }
	  fprintf(fl,"\n");
	  break;
	case 3: /* Record */
      	  for (field = 0; field < fieldnumb; field++)
	    fprintf(fl,"%*s: %s\n", len,ff[field],ff2[field]);
	  fprintf(fl,"\n");
	  break;
      }
    }
  fclose(fl);
}

