/* write.c -- routines to copy a group or elt to another file */
#include "he.h"

int HEwrite(cmd)
    HE_CMD *cmd;
{
    register int i;
    char *file;
    uint16 ref = 0;
    uint16 tag = 0;

    if (cmd->argc < 2 ||
	(cmd->argv[1][0] == '-' && findOpt(cmd->argv[1]+1) == HE_HELP))
    {
	puts("write <file> [-attachto <atag> <aref>]");
	puts("\tWrite an element or group into another HDF file");
	puts("\t-attchto\tONLY for writing annontations");
	puts("\t\t\tWhat element to attach annotation to");
	return HE_OK;
    }

    file = cmd->argv[1];
    for (i = 2; i < cmd->argc; i++)
	if (cmd->argv[i][0] != '-')
	    file = cmd->argv[i];
	else
	    switch (findOpt(cmd->argv[i] + 1))
	    {
	    case HE_ATTACHTO:
		tag = (uint16) atoi(cmd->argv[++i]);
		ref = (uint16) atoi(cmd->argv[++i]);
		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 writ(file, tag, ref);
}

int writ(file, tag, ref)
    char *file;
    uint16 tag;
    uint16 ref;
{
    int ret;
    uint16 ref1;

    if (!fileOpen())
    {
	noFile();
	return HE_FAIL;
    }
    if (!strcmp(file, he_file))
    {
	fprintf(stderr,"Cannot write to self.\n");
	return HE_FAIL;
    }

    /* handle special cases */
    if (isAnnot(currTag()))
	return writeAnnot(file, tag, ref);
    if (isGrp(currTag()))
	return writeGrp(file);

    if (getNewRef(file, &ref1) < 0)
	return HE_FAIL;

    ret = writeElt(file, ref1, he_currDesc);
    return ret;
}

/* end of write.c */
