/* putr8.c -- routines to put an r8 into raw files */
#include "he.h"

int HEputR8(cmd)
    HE_CMD *cmd;
{
    register int i;
    int verbose = NO;
    char *image = "img#.@.%";
    char * pal = "pal#";

    for (i = 1; i < cmd->argc; i++)
	if (cmd->argv[i][0] == '-')
	    switch (findOpt(cmd->argv[i] + 1))
	    {
	    case HE_HELP:
		puts("putr8 [-image <img>] [-palette <pal>] [-verbose]");
		puts("\tPut an r8 group into raw image and palette files");
		puts("\t-image\t\tImage file name template (default \"img#.@.%\")");
		puts("\t-palette\tPalette file name template (default \"pal#\")");
		puts("\t-verbose\tTo give output of steps taken");
		return HE_OK;
	    case HE_IMAGE:
		image = cmd->argv[++i];
		break;
	    case HE_PALETTE:
		pal = cmd->argv[++i];
		break;
	    case HE_VERBOSE:
		verbose = 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;
	    }
	else
	{
	    unkArg(cmd->argv[i]);
	    return HE_FAIL;
	}
    return putR8(image, pal, verbose);
}

int putR8(image, pal, verbose)
    char *image;
    char *pal;
    int verbose;
{
    int ret;
    int xdim, ydim;
    char *palette;
    char *raster;

    if (!fileOpen())
    {
	noFile();
	return HE_FAIL;
    }
    if (!isRig(currTag()))
    {
	fprintf(stderr,"Current element not an image group.");
	return HE_FAIL;
    }
    getCurrRig(&xdim, &ydim, &palette, &raster);
    if (raster == NULL)
    {
	fprintf(stderr,"Cannot find raster.\n");
	return HE_FAIL;
    }
    ret = putWithTempl(image, he_currDesc, xdim, ydim, raster, xdim*ydim,
		       verbose);
    free(raster);
    if (ret < 0) return HE_FAIL;
    if (palette != NULL)
    {
	register int i;
	char p[HE_PALETTE_SZ];

	for (i = 0; i < HE_COLOR_SZ; i++)
	{
	    p[i] = *palette++;
	    p[HE_COLOR_SZ + i] = *palette++;
	    p[2 * HE_COLOR_SZ + i] = *palette++;
	}
	ret = putWithTempl(pal, he_currDesc, xdim, ydim, p,
			   HE_PALETTE_SZ, verbose);
	free(palette);
	if (ret < 0) return HE_FAIL;
    }

    return HE_OK;
}

/* end of putr8.c */
