/* open.c -- contains open and close HDF file routines */
#include "he.h"

extern int he_backup;

int HEopen(cmd)
    HE_CMD *cmd;
{
    int backup = YES;
    register int i;
    char *file = NULL;

    for (i = 1; i < cmd->argc; i++)
	if (cmd->argv[i][0] != '-')
	{
	    if (!file)
		file = cmd->argv[i];
	    else
	    {
		fprintf(stderr, "Only one file allowed.\n");
		return HE_FAIL;
	    }
	}
	else
	    switch (findOpt(cmd->argv[i] + 1))
	    {
	    case HE_HELP:
		puts("open <file> [-nobackup]");
		puts("\t-nobackup\tDon't make a backup for this file.");
		return HE_OK;
	    case HE_NOBACKUP:
		backup = 0;
		break;
	    case HE_NOTFOUND:
		unkOpt(cmd->argv[i]);
		return HE_FAIL;
	    case HE_AMBIG:
		ambigOpt(cmd->argv[i]);
		return HE_FAIL;
	    default:
		irrOpt(cmd->argv[i]);
		return HE_FAIL;
	    }

    if (!file)
    {
	fprintf(stderr, "No file name.\n");
	return HE_FAIL;
    }

    return openFile(file, backup);
}


/* openFile -- Internal open file routine. */
/* Called by:	HEopen, main */
/* Returns:	HE_OK and HE_FAIL */
int openFile(file, backup)
    char *file;
    int backup;
{
    ASSERT(file);

    /* only allow one file at a time */
    if (fileOpen())
    {
	fprintf(stderr,"File: %s is still open. Close before reopening.\n",
		he_file);
	return HE_FAIL;
    }

    /* Make backup first if necessary */
    if (backup)
    {
	if (backupFile(file) < 0)
	    return HE_FAIL;
	he_backup = 1;
    }
    else
	he_backup = 0;

    if (initFile(file) < 0)
	return HE_FAIL;

    return HE_OK;
}


/* HEclose -- close current file*/
/* Called by HEdoCmd */
int HEclose(cmd)
    HE_CMD *cmd;
{
    register int i;
    int keep = NO;

    for (i = 1; i < cmd->argc; i++)
	if (cmd->argv[i][0] != '-')
	{
	    unkArg(cmd->argv[i]);
	    return HE_FAIL;
	}
	else
	    switch (findOpt(cmd->argv[i] + 1))
	    {
	    case HE_HELP:
		puts("close [-keep]");
		puts("\t-keep\t\tDon't delete the backup file.");
		return HE_OK;
	    case HE_KEEP:
		keep = YES;
		break;
	    case HE_NOTFOUND:
		unkOpt(cmd->argv[i]);
		return HE_FAIL;
	    case HE_AMBIG:
		ambigOpt(cmd->argv[i]);
		return HE_FAIL;
	    default:
		irrOpt(cmd->argv[i]);
		return HE_FAIL;
	    }

    return closeFile(keep);
}

int HErevert(cmd)
    HE_CMD *cmd;
{
    if (cmd->argc < 2)
	return revert();

    if (cmd->argv[1][0] != '-' || findOpt(cmd->argv[1]+1) == HE_HELP)
    {
	puts("revert");
	puts("\tDiscard all changes.");
	return HE_OK;
    }
}

/* end of open.c */
