/*===========================================================================
  Copyright (C) 1995-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

.VERSION
 090904		last modif

===========================================================================*/
#include <math.h>
#include <midas_def.h>
#include <tbldef.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <proto_xech.h>
#include <Xm/List.h>
#include <Xm/Text.h>
#include <UxLib.h>

#define NFILEMAX 500
#define LFILEMAX 50

extern int AppendDialogText();



int dbx=0;
Widget Wdir, Wcard, Wldir, Wlist;
char   WFList[NFILEMAX][LFILEMAX];
int    WFnl, WFSelect[NFILEMAX], WFns;
char   WFDir[200];

char   command[500];
char   fcomm[500];
char   name[500];

/* Initialisation of widgets ID's and present directory*/
void  WInit_widgets(wdir, wcard, wldir, wlist)
Widget wdir, wcard, wldir, wlist;
{
	Wdir  = wdir;
	Wcard = wcard;
	Wldir = wldir;
	Wlist = wlist;
	strcpy(WFDir,".");
}


/* Change Midas directory to the present directory */
void WChange_Midas_dir()
{
	sprintf(command,"CHANGE/DIRECTORY %s",WFDir);
	AppendDialogText(command);
}

/* Determines the new directory using a relative path,
   updates the Directory: widget, 
   determine and updates the list of directories */
void WGet_all_dirs(node)

char *node;
{
	FILE *fpin;
	int    n=0;
        int    ispos=1;

	/* Get current directory name and display in tf_session1 */

	sprintf(command, "cd %s ; cd %s ; pwd",WFDir,node);
	if (dbx == 1) printf("GAD/Executing command: %s\n",command);
	if ((fpin = (FILE*) popen(command,"r")) == NULL)
		printf("Could not execute command: %s\n",command);
	fgets(name,79,fpin);
	name[strlen(name)-1] = '\0';
	if (pclose(fpin) == -1)
		printf("Could not close stream for command: %s\n",command);
	strcpy(WFDir, name);
	XmTextSetString(Wdir, name);

	/* Determines list of sub-directories */

	sprintf(command,"cd %s ;  ls -F | grep / | sort ",
	    WFDir);
	if (dbx == 1) printf("GAD/Executing command: %s\n",command);
	if ((fpin = (FILE*) popen(command,"r")) == NULL)
		printf("Could not execute command: %s\n",command);

	XmTextSetString(Wldir, "");
        XmTextInsert(Wldir, (XmTextPosition) ispos, "../\n");
	while (fgets(name,79,fpin) != NULL) {
		if (dbx == 1) printf("GAD/File: %s\n",name);
                ispos = strlen(XmTextGetString(Wldir));
		XmTextInsert(Wldir, (XmTextPosition) ispos, name);
		n++;
	}

	if (pclose(fpin) == -1)
		printf("Could not close stream for command: %s\n",command);
}

int WGet_all_files()
{
	FILE *fpin;
	int    n=0, len;
	char   ident[74], full_name[300];
	int    null, unit, actvals, imno;
	int    pc, pl, pd, npc=1, npl=0, npd=0, ibuf[5];
	XmString Item;

	/* Reads current directory */
	strcpy(WFDir, (char *)XmTextGetString(Wdir));
	XmListDeleteAllItems(Wlist);

	sprintf(fcomm,"cd %s ; ls %s",WFDir,XmTextGetString(Wcard));

	strcpy(command,fcomm);
	strcat(command," | grep -v middumm | sort");
	if (dbx == 1) printf("GAF/Executing command: %s\n",command);

	if ((fpin = (FILE*) popen(command,"r")) == NULL)
		printf("Could not execute command: %s\n",command);

	n=0;
	while (fgets(name,79,fpin) != NULL) {

		len = strlen(name);
		name[--len] = '\0';

		strcpy(full_name,WFDir);
		strcat(full_name,"/");
		strcat(full_name,name);

		strcpy(ident,"");
		SCECNT("GET", &pc, &pl, &pd);
		SCECNT("PUT", &npc, &npl, &npd);

		if (dbx == 1)
			printf("GAF/Opening File: %s. \n",full_name);

		if (SCFINF(full_name, 4, ibuf) == ERR_NORMAL) {
			SCFOPN(full_name, D_R4_FORMAT, 1, F_IMA_TYPE, &imno);
			if (ibuf[2] == 0) {
				len = SCDRDC(imno, "IDENT", 1, 1, 72, &actvals, ident, &unit, &null);
				if (dbx == 1) printf("Len = %d\n",len);
			}
			SCFCLO(imno);
		}
		SCECNT("PUT", &pc, &pl, &pd);
		if (dbx == 1) printf("GAF/Opened File: %s\n",full_name);
		strcpy(&WFList[n][0], name);

		if (len < 15)
		{
			while (len++ < 17) strcat(name," ");
		}
		else
		{
			strcat(name,"  ");
		}

		strcat(name, ident);
		Item = XmStringCreateSimple(name);
		XmListAddItem(Wlist, Item, 0);
		n++;
	}

	if (pclose(fpin) == -1)
		printf("Could not close stream for command: %s\n",command);

	WFnl = n;
	return(WFnl);
}


int WGet_selection()

{
	int *p, pcount, i;

	XmListGetSelectedPos(Wlist,&p, &pcount);

	if (pcount <= 0) {
		printf("No item selected in the list.\n");
		WFns = 0;
		return(0);
	}

	for (i=0; i<pcount; i++) {
		printf("Selected item nb %d. Value %s\n",p[i], &WFList[(p[i]-1)][0]);
		WFSelect[i] =  p[i]-1;
	}
	WFns = pcount;

	free(p);
	return(pcount);
}


void WProcess_table(ptable)

char* ptable;

{
	char       table[TEXT_LEN], outfile[TEXT_LEN], out[TEXT_LEN], outnb[TEXT_LEN];

	int  icol, ocol, row;
	int  tid, nbout;

	strcpy(out,(char *)XmTextGetString(UxGetWidget(UxFindSwidget("tf_wrang1"))));
	strcpy(outnb,(char *)XmTextGetString(UxGetWidget(UxFindSwidget("tf_wrang2"))));

	sscanf(outnb,"%d",&nbout);
	strcpy(table, WFDir);
	strcat(table, "/");
	strcat(table,ptable);

	TCTINI (table, F_TRANS, F_IO_MODE, 3, WFns, &tid);
	TCCINI (tid, D_C_FORMAT, 60, "A20",  "  ", "INPUT",    &icol);
	TCCINI (tid, D_C_FORMAT, 60, "A20",  "  ", "OUTPUT",   &ocol);

	for (row=1; row<=WFns; row++) {
		TCEWRC(tid, row, icol, &WFList[WFSelect[row-1]][0]);
		sprintf(outfile,"%s%d.bdf", out, (nbout+row-1));
		TCEWRC(tid, row, ocol, outfile);
	}

	TCTCLO(tid);

}

char* WGet_First()

{
	return(&WFList[WFSelect[0]][0]);
}




