/*===========================================================================
  Copyright (C) 1988-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 Massachusetts Ave, Cambridge, 
  MA 02139, USA.
 
  Correspondence 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
===========================================================================*/

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
.TYPE        Module
.NAME        tedittbl.c
.LANGUAGE    C
.AUTHOR      J.D.Ponz  IPG-ESO Garching
.CATEGORY    table aplication (Design 2.0)
.COMMENTS    This module contains the code executed with the command
             EDIT/TABLE.
    
             - The table to be edited has been copied (in a previous
             task) to a temporary file. This temporary file is then
             opened and edited. If the user wants to keep the edited
             file, then it is renamed to the name specified as the
             file to be edited; otherwise, the temporary file is deleted.

             - The editor works in two flavours: VAX EDT like using the
             keypad functions, and 'vi' like if
             the terminal does not have keypad.

             - A buffering mechanism allows the recovering of interrumpted
             editing session.

.PURPOSE     Execute the command
             edit/table  tablename [option  | ncol nrow]
\begin{TeX}
\begin{verbatim}

WRITE/KEY HISTORY "'MID$CMND(1:4)'/'MID$CMND(11:14)' 'P1' 'P2' 'P3'"
WRITE/KEY INPUTI/I/1/2  0,0	! Values of columns + rows
IF PCOUNT .GE. 2 THEN
  IF M$TSTNO(P2) .EQ. 0 THEN
    WRITE/KEY INPUTI/I/1/1 -1
  ELSE
    WRITE/KEY INPUTI/I/1/1 'P2'
    WRITE/KEY INPUTI/I/2/1 'P3'
  ENDIF 
ENDIF
IF INPUTI(1) .EQ. 0  THEN 	! Copy to a temporary table
  IF M$INDEX(P1,".tbl") .EQ. 0  THEN
    -COPY 'P1(1:>)'.tbl MIDASEDT{mid$sess(11:12)}.tbl
   ELSE
    -COPY 'P1(1:>)' MIDASEDT{mid$sess(11:12)}.tbl
  ENDIF
ELSE
ENDIF
RUN MID_EXE:tedittbl           
\end{verbatim}
\end{TeX}

.VERSION     1.0 25-Mar-1988   Implementation     JDP
.VERSION     1.1 12-Feb-1990   Mod. to use alloc. cols as table limit JDP
.VERSION     1.2 28-Oct-1990   Allow the option 
			r (read-only) 
			i (immediate update)
			which are stored in INPUTI
.VERSION     1.3 08-Apr-1991  make it working when table doesn't exist MP

 090710		last modif
------------------------------------------------------------*/


#include <midas_def.h>
#include <atype.h>		/* character classes */
#include <tbldef.h>
#include <tfmdef.h>
#include <tfmini.h>
#include <tbledt.h>
#include <tblmac.h>

#include <str.h>

#include <stdio.h>
#include <stdlib.h>

#define NAMLEN 80  /* length of file names */

extern int tbl_argc(), tbl_getarg(), tbl_edit();
extern int edt_init(), edt_keys(), edt_format(), edt_page(), edt_close();


int main()

{
  int   status, iav, npar, knull, ncol, tid, narow, nacol, stor;
  int   nrow, i, nsc, ipar[6],inrow, j, dummy;
  int   mode, iout[2],ibuf,zero,one,flags[3];
  int   actvals;
  int   noelem, inull;
  int   kunit, dunit;

  char	 *osfsupply(), *which_table;
  char   *history,*osmmget();
  char   name[NAMLEN+1], colname[17], type;
  char   namef[NAMLEN+1], tablef[NAMLEN+1], option[6];
  char   tmptable[16];
  static char   unit[17]      = "           ";
  static char   form[10]      = "E14.5";
  static char   msg[150];

/*  static char   tmptable[NAMLEN+1] = "MIDASEDT"; do not hardcode the name */

                                          /* start MIDAS session */

  status = SCSPRO("TEDITTBL");
  iout[0] = 1;
  mode = inrow = 0;
  zero = 0;
  one  = 1;
                                          /* get input parameters */

  npar = tbl_argc();
  tbl_getarg(1, NAMLEN, name);
  tbl_getarg(2, sizeof(option)-1, option);
  
  /*get name of temporary table which includes session number*/
  SCKGETC("TMPTABL",1,15,&actvals,tmptable);
                                        
                                          /* setup names */
  strcpy (tablef, tmptable);
  strcpy (namef , osfsupply(name ,".tbl"));

		/* Check the INPUTI keyword, which tells if it's a
		   new table (>0), or a direct update (<0)
		*/
		
  SCKRDI("INPUTI", 1, 2, &iav, ipar, &kunit, &knull);
  if (ipar[0] > 0) {					/* Create Table */
	ncol = nacol = ipar[0]; 
	inrow = nrow = narow = ipar[1];
	stor   = 0;
	which_table = name;
        status = SCFINF(namef,99,&ibuf);
        if (status == ERR_NORMAL){
               SCTPUT("Error: Table already exists");
               goto error;
               }
	status = TCTINI(which_table, F_TRANS, F_O_MODE, nacol, narow, &tid);
	for (i = 0; i < ncol; i++) {	/* Create Columns */
		sprintf(colname,"LAB%03d",i+1);
		status  = TCCINI(tid, D_R4_FORMAT,1, form, unit, colname, &j);
	}
  }
  else {				/* Table exists	*/
	if (ipar[0] == 0)
		which_table = tmptable, mode = F_U_MODE;
  	else	which_table = name,
		mode = (toupper(*option) == 'R' ? F_I_MODE : F_U_MODE);
	if ((status = TCTOPN(which_table, mode, &tid))) {
        	SCTPUT(" Table not found");
		goto error;
        }
  }

					/* set up columns to be edited */
  TCIGET(tid, &ncol, &nrow, &nsc, &nacol, &narow);

  if (nrow == 0) {
   if (inrow !=0) {
        nrow = inrow;
        TCIPUT(tid,ncol,inrow);
        }
  else {
        SCDFND(tid,"HISTORY",&type,&noelem,&dummy);
        if (type != ' ') {
           history = osmmget(noelem);
           SCDRDC(tid,"HISTORY",1,11,80,&dummy,history,&dunit,&inull);
            history += strskip(history,' ');
            history += strloc(history,' '); history++;
            history += strloc(history,' '); history++;
            nrow = atoi(history);
           TCIPUT(tid,ncol,inrow);
           }
        } 
  }
  TCSINI(tid);

                                          /* initialize windows */
  status = edt_init(name);
  edt_keys();
  thecol = 0;
  edt_nacol = nacol;
  edt_narow = nrow;
  edt_nrow  = nrow;
  edt_ncol  = ncol;  
  /* edt_nr    = MIN(nrow, data_lines); modified to allow for alloc cols */
  edt_nr    = MIN(nrow,data_lines);
  edt_tid   = tid;
  edt_advance = TRUE;
                                          /* setup window information */
  for (i=0; i<edt_nr; i++) edt_row[i] = i+1; 
  status = edt_format(FIRSTPAGE);  
  status = edt_page(tid);                                       

  status = SCECNT("GET",flags,flags+1,flags+2);
  status = SCECNT("PUT",&one,&zero,&zero);
  tbl_edit( );
  status = SCECNT("PUT",flags,flags+1,flags+2);

  status = edt_close();

  if ((edt_status == EXIT) && (mode == F_I_MODE))
  	SCTPUT("++++ All modifications ignored (read-only table)");
  status = TCTCLO(tid);

  if (which_table == tmptable) {	/* Only if a temporaty table used */
  	if (edt_status == EXIT) {	/* EXIT means Rename Tmp to Old	  */
  		sprintf(msg, "Rename %s to %s ",tablef,namef);
		SCTPUT (msg);
		status  = SCFRNM(tablef, namef);
		iout[0] = 0;
	} 
  	else  {	
  		status  = SCFDEL(tablef);
		iout[0] = 1;
	}
  }
                                          /* close windows */

error:
  status = SCKWRI("OUTPUTI", iout, 1, 1, &kunit);
  
  SCSEPI();    
  ospexit(0);

return 0;
}
