/*===========================================================================
  Copyright (C) 1989-2009 European Southern Observatory (ESO)
 
  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., 675 Massachusetss Ave, Cambridge, 
  MA 02139, USA.
 
  Corresponding concerning ESO-MIDAS should be addressed as follows:
	Internet e-mail: midas@eso.org
	Postal address: European Southern Observatory
			Data Management Division 
			Karl-Schwarzschild-Strasse 2
			D 85748 Garching bei Muenchen 
			GERMANY
===========================================================================*/

/*++++++++++++++
.NAME		tfile.c
.TYPE           Module
.LANGUAGE       C
.KEYWORDS	Forms
.ENVIRONMENT    TermWindows
.AUTHOR		Alan Richmond, Francois Ochsenbein 
.COMMENTS
	This module contains the basic File operations for Forms:
	(copy to Output)
.VERSION 1.0 	07-Jun-1989: Extracted from Proteus.

 090902         last modif
------------------*/

#define	PM_LEVEL	LEVEL_TF

#define  PASCAL_DEF	0	/* Don't include Pascalisation 	*/

#include <midas_def.h>	/* Standard definitions	*/

#include <stesodef.h>	/* Standard definitions	*/
#include <tform.h>	/* for form values	*/
#include <str.h>	/* String utilities	*/


extern int pm_enter(), pm_iexit(), pm_tr2(), pm_ed_i();

extern int fi_open(), fi_close(), fi_put(), fi_write();

extern int mm_free();

extern int tf_fclose();



#define FINISH	goto FIN

static	char	*sep = "|";		/* Column Separator	*/

/*=====================================================================*/
char *tf_fsep(text)
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
.PURPOSE Choose the column separator text
.RETURNS Old separator
.REMARKS The | is used by default.
------------------------------------------------------------------------*/
	char	*text;	/* IN: The separator text */
{
	char	*old_sep;

  old_sep = sep;
  sep = text;
  
  return(old_sep);
}

/*=====================================================================*/
int tf_fopen (form, filename)
/*++++++++
.PURPOSE Open an Ascii File for Output
.RETURNS OK / NOK
.REMARKS No preparation of the First Record.
----------*/
	TFORM	*form;		/* IN: The form concerned	*/
	char	*filename;	/* IN: Name of File to open	*/
{
	int	fn;	/* File Number */
	
  ENTER("tf_open");

	/* Check first if a file exists; close the current file if necessary */

  if (form->afileno >= 0)	tf_fclose(form);
  fn = OPEN_OUT(filename);
  if (fn > 0)
  {
	form->acount = 0;	/* Initialize the number of Records */
	form->afileno = fn;	/* File Number	*/
	form->options |= _FORM_TOFILE;
	fn = OK;
  }
  else	fn = NOK;
  
  EXIT(fn);
}

/*=====================================================================*/
int tf_fclose (form)
/*++++++++
.PURPOSE Close the File associated to the Form
.RETURNS OK / NOK
.REMARKS 
----------*/
	TFORM	*form;		/* IN: The form concerned	*/
{
	
  ENTER("tf_fclose");
  
  if (form->afileno >= 0)
  {
	fi_close(form->afileno);
	form->afileno = -1;
	form->options &= ~_FORM_TOFILE;
  }

  EXIT(OK);
}

/*=====================================================================*/
int tf_fput (form)
/*++++++++
.PURPOSE Write out one Record (contents of the Form)
.RETURNS Number of Fields Written.
.REMARKS Fields are filled with blanks
----------*/
	TFORM	*form;		/* IN: The form concerned	*/
{
        int     i, len, sepno;
	TFIELD	*field;
	char	*p;

  ENTER("+tf_fput");

  sepno = 0;
  
  if_not(form->options & _FORM_TOFILE)	FINISH;
  
  for (field = form->fields, i = form->nfields; --i>=0; field++)
  {
  	if_not(field->options & _FIELD_TOFILE)	continue;

	if (sepno)	fi_put(form->afileno, sep);
	
	len = strlen(field->string);
	p   = field->string + len;
	len = field->string_size - 1 - len;	/* Blanks to add */

	strfill(p, len, ' ');

	fi_put(form->afileno, field->string);
	sepno++;
  }
  form->acount += 1;
  fi_put(form->afileno, "\n");
	
  FIN:
  EXIT ( sepno );
}

/*=====================================================================*/
int tf_ftitle (form)
/*++++++++
.PURPOSE Write out the Title 
.RETURNS OK / NOK
.REMARKS 
----------*/
	TFORM	*form;		/* IN: The form concerned	*/
{
	int  	i, j, reclen, fwidth, lsep;
	char	*p, *q, *t, *titles;
	TFIELD	*field;
  
  ENTER("tf_ftitle");

	/* Compute first the Record Length. Note that action fields
	   can't be output...	*/
  
  lsep = strlen(sep);
  
  for (reclen = 0, field = form->fields, i = form->nfields; --i>=0; field++)
  {
	if_not (field->string_size)	field->options &= ~_FIELD_TOFILE;
	if (isactionField(field))	field->options &= ~_FIELD_TOFILE;
	if_not (field->options & _FIELD_TOFILE)	continue;
	if (reclen)	reclen += lsep;
	reclen += (field->string_size - 1);
  }
  reclen += 1;			/* Record length, including \n */
  
  titles = MEM_GET(char, 8*reclen);
  
  	/* Fill the title with blanks and sep's: first a complete line,
  	   recopy 6 times (to make 7 lines),
  	   and adds a last line with dashes
  	 */

  for (p = titles, field = form->fields, i = form->nfields; --i>=0; field++)
  {
	if_not (field->options & _FIELD_TOFILE)	continue;
	if (p != titles)	p += oscopy(p, sep, lsep);
	p += oscfill(p, (field->string_size - 1), ' ');
  }
  *(p++) = '\n';		/* End of record	*/
  
  for (j=6; --j>=0; )	p += oscopy(p, titles, reclen);

  oscopy(p, titles, reclen);	/* The 8th line replaces blanks with - */
  for (j=reclen; --j>=0; p++)	if (*p == ' ')	*p = '-';
  *p = EOS;
	

	/* Write titles of Fields. Titles are written on up to 7 lines,
	 * and are bottom-adjusted	*/
  
  for (p = titles, field = form->fields, i = form->nfields; --i>=0; field++)
  {
	if_not (field->options & _FIELD_TOFILE)	continue;
	if(p != titles)	p += lsep;
	fwidth = field->string_size - 1;
	j = (strlen(field->name) + fwidth-1)/fwidth;
	if (j > 7)	j = 7;
	q = p + (7-j)*reclen;		/* Starting point for title	*/
	p += fwidth;
	
	for (j=0, t = field->name; *t; j++)
	{
		if (j == fwidth)	/* Continue below	*/
			j = 0, q += (reclen - fwidth);
		if (*q != ' ')	break;
		*(q++) = *(t++);
	}
  }

	/* Output the Titles in one single output	*/
  
  fi_write(form->afileno, titles, reclen*8);

  MEM_FREE(titles);
	
  EXIT(OK);
}
