/* he.c -- main and dispatcher for HDFedit */
#include "he.h"

/* the return status of last command executed */
int he_status = HE_OK;

/* is this on the console or remote terminals?
   this should eventually be detected automatically */
int he_remote = YES;

/* is this batch mode or interactive? */
extern int he_batch;

main(argc, argv)
    int argc;
    char *argv[];
{
    int backup = YES;		/* Backup files when opening? */
    register int i;
    char *fileName = NULL;

    for (i = 1; i < argc; i++)
    {
	if (argv[i][0] == '-')
	{
	    switch (findOpt(argv[i] + 1))
	    {
	    case HE_HELP:
		puts("he [<file>] [-nobackup] [-batch]");
		help();
		quit(0);
	    case HE_BATCH:
		he_batch = YES;
		break;
	    case HE_REMOTE:
		he_remote = YES;
		break;
	    case HE_NOBACKUP:
		backup = NO;
		break;
	    case HE_BACKUP:
		backup = YES;
		break;
	    case HE_NOTFOUND:
		unkOpt(argv[i]);
		quit(1);	/* does not return */
		break;
	    case HE_AMBIG:
		ambigOpt(argv[i]);
		quit(1);
		break;
	    default:
		irrOpt(argv[i]);
		quit(1);	/* does not return */
		break;
	    }
	}
	else
	{
	    /* Must be a filename */
	    if (!fileName)
		fileName = argv[i];
	    else
		fprintf(stderr, "Single file only. %s not open.\n", argv[i]);
	}
    }

    /* if there is a file name given in the command line, open it */
    if (fileName) he_status = openFile(fileName, backup);

    /* read, execute loop */
    cmdLoop();

    if (fileOpen()) close(YES);	/* close with keep */
    quit(0);
}

/* cmdLoop -- read commands and execute them */
void cmdLoop()
{
    HE_CMD *cmd;

    for (cmd = getCmd(); cmd; cmd = getCmd())
    {
	if (cmd->func)
	    he_status = (*cmd->func) (cmd);
	else
	{
	    fprintf(stderr, "Unknown command: %s.\n", cmd->argv[0]);
	    he_status = HE_FAIL;
	}
	deleteCmd(cmd);
    }
}
