/* Copyright (C) 2000-2002 Damir Zucic */

/*=============================================================================

				execute_script.c

Purpose:
	Read and execute the specified script file.

Input:
	(1) Pointer to MolComplexS structure, with macromol. complexes.
	(2) Pointer to the number of macromolecular complexes.
	(3) Pointer to the next macromolecular complex identifier.
	(4) Pointer to RuntimeS structure, with some runtime data.
	(5) Pointer to ConfigS structure, with configuration data.
	(6) Pointer to GUIS structure, with GUI data.
	(7) Pointer to pointer to NearestAtomS structure.
	(8) Pointer to the number of pixels in the main win. free area.
	(9) Pointer to refreshI.

Output:
	(1) Some files may be loaded, data changed etc.
	(2) Return value.

Return value:
	(1) If the attempt to open script file fails,  the return value
	    will be ERROR_OPEN_FAILURE.
	(2) If script is available,  the return value  will be equal to
	    the return code of the last  executed command.  On success,
	    the return will be  (in most cases)  positive.  On failure,
	    the return value will be (in most cases) negative.

Notes:
	(1) This function is called by  ExecuteCommand1_  but  it calls
	    ExecuteCommand2_,  which is not capable to execute scripts.
	    This helps to avoid infinite loops.

========includes:============================================================*/

#include <stdio.h>

#include <string.h>

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#include <X11/Xatom.h>

#include "defines.h"
#include "commands.h"
#include "typedefs.h"

/*======function prototypes:=================================================*/

char		*ExtractToken_ (char *, int, char *, char *);
FILE		*OpenFileForReading_ (char *);
int		ExecuteCommand2_ (MolComplexS *, int *, int *,
				  RuntimeS *, ConfigS *, GUIS *,
				  NearestAtomS **, size_t *, unsigned int *);
int		TruncateCommand_ (RuntimeS *);
int		InputRefresh_ (GUIS *, RuntimeS *);

/*======execute script:======================================================*/

int ExecuteScript_ (MolComplexS *mol_complexSP, int *mol_complexesNP,
		    int *next_mol_complexIDP,
		    RuntimeS *runtimeSP,
		    ConfigS *configSP, GUIS *guiSP,
		    NearestAtomS **nearest_atomSPP, size_t *pixelsNP,
		    unsigned int *refreshIP)
{
int		command_code = 2;
int		line_length;
char		*remainderP;
char		tokenA[STRINGSIZE];
static FILE	*fileP;
char		commandA[COMMSTRINGSIZE];
char		*currP;

/* If file is not opened yet: */
if (fileP == NULL)
	{
	/* Skip the first token: */
	remainderP = ExtractToken_ (tokenA, STRINGSIZE,
				    runtimeSP->curr_commandA, " \t\n");
	if (!remainderP) return ERROR_EXECUTE;

	/* The second token should contain the file name: */
	remainderP = ExtractToken_ (tokenA, STRINGSIZE, remainderP, " \t\n");
	if (!remainderP)
		{
		strcpy (runtimeSP->messageA, "Script file not specified!");
		runtimeSP->message_length = strlen (runtimeSP->messageA);
		return ERROR_NO_FILE_NAME;
		}

	/* Open the script file: */
	if ((fileP = OpenFileForReading_ (tokenA)) == NULL)
		{
		sprintf (runtimeSP->messageA,
			"Unable to open script %s!", tokenA);
		runtimeSP->message_length = strlen (runtimeSP->messageA);
		return ERROR_OPEN_FAILURE;
		}

	/* On success, set the scriptF: */
	runtimeSP->scriptF = 1;
	}

/* Read the next (or the very first) line: */
while (fgets (commandA, COMMSTRINGSIZE, fileP))
	{
	/* If the previous command was pause command, reset the pauseF: */
	if (runtimeSP->pauseF) runtimeSP->pauseF = 0;

	/* The length of the command line: */
	line_length = strlen (commandA);

	/* Skip empty lines and lines shorter than two characters: */
	if (line_length < 3) continue;

	/* Skip comments: */
	if (commandA[0] == '#') continue;

	/* Remove the terminal newline: */
	if (commandA[line_length - 1] == '\n')
		{
		commandA[line_length - 1] = '\0';
		line_length--;
		}

	/* Copy the command to RuntimeS structure: */
	strncpy (runtimeSP->curr_commandA, commandA, line_length);
	runtimeSP->curr_commandA[line_length] = '\0';

	/* Prepare other parameters associated with the current command: */
	runtimeSP->command_length = line_length;
	runtimeSP->carriage_position = runtimeSP->command_length;

	/* Prepare the width (in pixels) of the command string: */
	runtimeSP->left_part_widthA[line_length] =
				XTextWidth (guiSP->main_winS.fontSP,
					    runtimeSP->curr_commandA,
					    runtimeSP->carriage_position);

	/* Refresh the input window, so that user knows what is going on: */
	InputRefresh_ (guiSP, runtimeSP);

	/* Print command to log file, if requested: */
	if (configSP->log_fileF)
		{
		fprintf (configSP->log_fileP, "%s\n",
			 runtimeSP->curr_commandA);
		fflush (configSP->log_fileP);
		}

	/* Copy the command string to the history buffer: */
	currP = runtimeSP->commandsP +
		runtimeSP->next_commandI * COMMSTRINGSIZE;
	strcpy (currP, runtimeSP->curr_commandA);

	/* Execute the command: */
	command_code = ExecuteCommand2_ (mol_complexSP, mol_complexesNP,
					 next_mol_complexIDP,
					 runtimeSP, configSP, guiSP,
					 nearest_atomSPP, pixelsNP, refreshIP);

	/* Print the latest message to log file (if log file is used): */
	if ((command_code < 0) && (configSP->log_fileF))
		{
		fprintf (configSP->log_fileP, "#%s\n", runtimeSP->messageA);
		fflush (configSP->log_fileP);
		}

	/* Truncate the command string: */
	TruncateCommand_ (runtimeSP);

	/* Refresh (redraw) the input window: */
	InputRefresh_ (guiSP, runtimeSP);

	/* Update and check the command index */
	/* and the  total number of commands: */
	runtimeSP->next_commandI++;
	if (runtimeSP->next_commandI >= MAXCOMMSTRINGS - 1)
		{
		runtimeSP->next_commandI = 0;
		}
	if (runtimeSP->highest_commandI < MAXCOMMSTRINGS - 1)
		{
		runtimeSP->highest_commandI++;
		}

	/* Update the old_commandI: */
	runtimeSP->old_commandI = runtimeSP->next_commandI;

	/* If PAUSE command was issued, return to the caller: */
	if (command_code == COMMAND_PAUSE) return COMMAND_PAUSE;

	/* If QUIT command was issued, break from the loop: */
	if (command_code == COMMAND_QUIT) break;
	}

/* Close the script file, reset the file pointer and reset the script flag: */
fclose (fileP);
fileP = NULL;
runtimeSP->scriptF = 0;

/* If this point is reached, return the last command code: */
return command_code;
}

/*===========================================================================*/


