#include "streaksremove.h"
#include "libgen.h"
#include "unistd.h"

static nebServer *ourNebServer = NULL;

streakFiles *openFiles(pmConfig *config, bool remove)
{
    bool status;
    streakFiles *sf = psAlloc(sizeof(streakFiles));
    memset(sf, 0, sizeof(*sf));

    sf->config = config;

    // error checking is done by sFileOpen. If a file can't be opened we just exit
    ippStage stage = psMetadataLookupS32(&status, config->arguments, "STAGE");

    sf->stage = stage;
    sf->extnum = 0;

    sf->class_id = psMetadataLookupStr(&status, config->arguments, "CLASS_ID");

    sf->inImage = sFileOpen(config, stage, "INPUT", NULL, true);
    sf->nHDU = sf->inImage->nHDU;

    // don't need to free inputBasename see basename(3)
    // The names of the temporary and recovery files are taken from the input
    char *inputBasename = basename(sf->inImage->name);
    sf->outImage = sFileOpen(config, stage, "OUTPUT", inputBasename, true);

    if (remove) {
        sf->recImage = sFileOpen(config, stage, "RECOVERY", inputBasename, false);
    } else {
        sf->recImage = sFileOpen(config, stage, "RECOVERY.IMAGE", NULL, true);
    }

    sf->inMask = sFileOpen(config, stage, "INPUT.MASK", NULL, false);
    if (sf->inMask) {
        inputBasename = basename(sf->inMask->name);
        sf->outMask = sFileOpen(config, stage, "OUTPUT", inputBasename, true);
        if (remove) {
            sf->recMask = sFileOpen(config, stage, "RECOVERY", inputBasename, false);
        } else {
            sf->recMask = sFileOpen(config, stage, "RECOVERY.MASK", NULL, true);
        }
    }
    sf->inWeight = sFileOpen(config, stage, "INPUT.WEIGHT", NULL, false);
    if (sf->inWeight) {
        inputBasename = basename(sf->inWeight->name);
        sf->outWeight = sFileOpen(config, stage, "OUTPUT", inputBasename, true);
        if (remove) {
            sf->recWeight = sFileOpen(config, stage, "RECOVERY", inputBasename, false);
        } else {
            sf->recWeight = sFileOpen(config, stage, "RECOVERY.WEIGHT", NULL, true);
        }
    }
     
    psElemType tileType;                // Type corresponding to "long"
    if (sizeof(long) == sizeof(psS64)) {
        tileType = PS_TYPE_S64;
    } else if (sizeof(long) == sizeof(psS32)) {
        tileType = PS_TYPE_S32;
    } else {
        psAbort("can't map (long) type to a psLib type");
    }

    sf->tiles = psVectorAlloc(3, tileType); // Tile sizes
    if (tileType == PS_TYPE_S64) {
        sf->tiles->data.S64[0] = 0;
        sf->tiles->data.S64[1] = 1;
        sf->tiles->data.S64[2] = 1;
    } else {
        sf->tiles->data.S32[0] = 0;
        sf->tiles->data.S32[1] = 1;
        sf->tiles->data.S32[2] = 1;
    }

    sf->transparentStreaks = psMetadataLookupF64(&status, config->arguments, "TRANSPARENT_STREAKS");

    return sf;
}

void sFileFree(sFile *sfile)
{
    psFree(sfile->resolved_name);
    psFree(sfile->name);
    psFree(sfile);
}


// getNebServer()
//
// it gets created the first time a nebulous file is accessed.
// if config is passed in we are to create it and exit if not able.
// if config is null we return NULL indicating that there are no nebulous files in use
// The purpose of this is to avoid passing extra arguments between all of the functions.
// but it is probably a bad idea.
//
static nebServer *getNebServer(pmConfig *config)
{
    if (ourNebServer) {
        return ourNebServer;
    }

    if (!config) {
        return NULL;
    }

    psString serverURI = getenv("NEB_SERVER");

    // XXX: Note: all of the flags to psError should be true, but I don't think nebclient
    // uses psError
    if (!serverURI) {
        bool status;
        serverURI = psMetadataLookupStr(&status, config->site, "NEB_SERVER");
        if (!status) {
            psError(PM_ERR_CONFIG, true, "failed to lookup config value for NEB_SERVER.");
            streaksExit("", PS_EXIT_CONFIG_ERROR);
        }
    }

    if (!serverURI) {
        psError(PM_ERR_CONFIG, true, "Could not determine nebulous server URI.");

        streaksExit("", PS_EXIT_CONFIG_ERROR);
    }

    ourNebServer = nebServerAlloc(serverURI);
    if (!ourNebServer) {
        psError(PM_ERR_SYS, true, "failed to create a nebServer object from %s.", serverURI);
        streaksExit("", PS_EXIT_CONFIG_ERROR);
    }

    return ourNebServer;
}

static psString
resolveFilename(pmConfig *config, sFile *sfile, bool create)
{
    sfile->inNebulous = IN_NEBULOUS(sfile->name);

    if (sfile->inNebulous) {
        // make sure we have our neb server connection
        nebServer *server = getNebServer(config);
        if (create) {
            // delete the existing file, since there may be more than one
            // instance. It will get created below in pmConfigConvertFilename
            if (nebFind(server, sfile->name)) {
                nebDelete(server, sfile->name);
            }
        }
    }

    return pmConfigConvertFilename(sfile->name, config, create, create);
}

sFile *sFileOpen(pmConfig *config, ippStage stage, psString fileSelect,
    psString outputFilename, bool required)
{
    bool status;
    sFile *sfile = psAlloc(sizeof(sFile));
    memset(sfile, 0, sizeof(sFile));

    // We use psFits directly to read the image unless the stage is warp
    // or diff. In those cases we use the pmFPAfile functions to read the image file
    // to make managing the astrometry easy.
    // The reason we don't use pmFPAfile in all cases is that I was having trouble getting
    // all of the keywords in the raw image files written to the output destreaked files

    if (!CHIP_LEVEL_INPUT(stage) && !strcmp(fileSelect, "INPUT")) {
        // stage is warp or diff AND fileSelect eq "INPUT"
        // get data from pmFPAfile.

        // we need to know what the nebulous and real filenames are so we steal
        // some code from pmFPAfileDefineFromArgs
        // XXX: create a pmFPAfile function that does this and use it there
        psArray *infiles = psMetadataLookupPtr(&status, config->arguments, "INPUT");
        if (!status) {
            psError(PS_ERR_PROGRAMMING, false, "INPUT not found in config->arguments");
            streaksExit("", PS_EXIT_PROG_ERROR);
        }
        if (infiles->n != 1) {
            psError(PS_ERR_IO, false, "Found n == %ld files in %s in arguments expencted 1\n",
                infiles->n, "INPUT");
            streaksExit("", PS_EXIT_DATA_ERROR);
        }
        // end of file name lookup code adapted from pmFPAfileDefineFromArgs
        //
        sfile->name = psStringCopy(infiles->data[0]);
        sfile->inNebulous = IN_NEBULOUS(sfile->name);

        // XXX: I should probably be using a different file rule for diffs, but I don't
        // have an input rule that takes a diff image. 
        // Since they're skycells, this should be compatible
        sfile->pmfile = pmFPAfileDefineFromArgs(&status, config, "PPSUB.INPUT", "INPUT");
        if (!sfile->pmfile) {
            psError(PS_ERR_IO, false, "Failed to define file for %s", fileSelect);
            streaksExit("", PS_EXIT_DATA_ERROR);
        }

        pmFPAview *view = pmFPAviewAlloc(0);
        if (!pmFPAfileIOChecks(config, view, PM_FPA_BEFORE)) {
            psError(PS_ERR_UNKNOWN, false, "Failed to load input.");
            streaksExit("", PS_EXIT_DATA_ERROR);
        }
        psFree(view);
        sfile->resolved_name = psStringCopy(sfile->pmfile->filename);
        
        // copy header from fpu
        sfile->header = (psMetadata*) psMemIncrRefCounter(sfile->pmfile->fpa->hdu->header);

        return sfile;
    }

    // For all other files we use using psFits for i/o

    psString name = psMetadataLookupStr(&status, config->arguments, fileSelect);
    if (!status || !name) {
        if (required) {
            psError(PS_ERR_IO, false, "Failed to lookup name for %s", fileSelect);
            sFileFree(sfile);
            streaksExit("", 1);
        }
        return NULL;
    }

    // if outputFilename is not null name it contains the "directory" 
    // and outputFilename is the basename name of the file (or nebulous key)
    // and the file is to be opened for writing
    if (outputFilename) {
        psStringAppend(&sfile->name, "%s%s", name, outputFilename);
        sfile->resolved_name = resolveFilename(config, sfile, true);
        if (!sfile->resolved_name) {
            psError(PS_ERR_IO, false, "Failed to resolve filename for %s", sfile->name);
            sFileFree(sfile);
            streaksExit("", 1);
        }
        sfile->fits = psFitsOpen(sfile->resolved_name, "w");
        if (sfile->fits) {
            sfile->fits->options = psFitsOptionsAlloc();
        }
    } else {
        sfile->name = psStringCopy(name);
        sfile->resolved_name = resolveFilename(config, sfile, false);
        if (!sfile->resolved_name) {
            psError(PS_ERR_IO, false, "Failed to resolve name for %s", sfile->name);
            sFileFree(sfile);
            streaksExit("", 1);
        }
        sfile->fits = psFitsOpen(sfile->resolved_name, "r");
        if (sfile->fits) {
            sfile->nHDU = psFitsGetSize(sfile->fits);
        }
    }

    if (!sfile->fits) {
        psError(PS_ERR_IO, false, "failed to open fits file %s for %s",
                    sfile->resolved_name, outputFilename ? "writing" : "reading");
        sFileFree(sfile);
        streaksExit("", 1);
    }

    return sfile;
}


static bool
moveExt(sFile *sfile, int extnum)
{
    bool status = psFitsMoveExtNum(sfile->fits, extnum, false);
    if (!status) {
        psError(PS_ERR_IO, false, 
            "failed to move to extension %d for %s", extnum, sfile->resolved_name);
        streaksExit("", PS_EXIT_DATA_ERROR);
    }
    return true;
}

bool
streakFilesNextExtension(streakFiles *sf)
{
    // unless stage is raw or chip when we get here we're done
    if (sf->stage != IPP_STAGE_RAW) {
        if (sf->view) {
            sf->view->readout = -1;
            pmFPAfileIOChecks(sf->config, sf->view, PM_FPA_AFTER);
            sf->view->cell = -1;
            pmFPAfileIOChecks(sf->config, sf->view, PM_FPA_AFTER);
            sf->view->chip = -1;
            pmFPAfileIOChecks(sf->config, sf->view, PM_FPA_AFTER);
        }
        return false;
    }

    ++sf->extnum;
    if (sf->nHDU == 1) {
        // return true the first time through
        return (sf->extnum == 1);
    }
    if (sf->extnum < sf->nHDU) {
        moveExt(sf->inImage, sf->extnum);
        if (sf->inMask) {
            moveExt(sf->inMask, sf->extnum);
        }
        if (sf->inWeight) {
            moveExt(sf->inWeight, sf->extnum);
        }
        return true;
    } else {
        return false;
    }
}

void
copyPHU(streakFiles *sfiles, bool remove)
{
    psAssert(sfiles->stage == IPP_STAGE_RAW, "copyPHU should only be used for raw stage");

    psMetadata *imageHeader = psFitsReadHeader(NULL, sfiles->inImage->fits);
    if (!imageHeader) {
        psError(PS_ERR_IO, false, "failed to read primary header from %s\n",
            sfiles->inImage->resolved_name);
        streaksExit("", PS_EXIT_DATA_ERROR);
    }

    // TODO: add keyword indicating that streaks have been removed
    if (!psFitsWriteBlank(sfiles->outImage->fits, imageHeader, NULL)) {
        psError(PS_ERR_IO, false, "failed to write primary header to %s",
            sfiles->outImage->resolved_name);
        streaksExit("", PS_EXIT_DATA_ERROR);
    }
    // TODO: add keyword indicating that this is the recovery image
    if (remove && sfiles->recImage && !psFitsWriteBlank(sfiles->recImage->fits, imageHeader, NULL)) {
        psError(PS_ERR_IO, false, "failed to write primary header to %s",
            sfiles->recImage->resolved_name);
        streaksExit("", PS_EXIT_DATA_ERROR);
    }
    psFree(imageHeader);

    sFile *inMask = sfiles->inMask;
    if (inMask) {
        psMetadata *maskHeader = psFitsReadHeader(NULL, inMask->fits);
        if (!maskHeader) {
            psError(PS_ERR_IO, false, "failed to read primary header from %s\n",
                sfiles->inMask->resolved_name);
            streaksExit("", 1);
        }
        // TODO: add keyword indicating that streaks have been removed
        if (!psFitsWriteBlank(sfiles->outMask->fits, maskHeader, NULL)) {
            psError(PS_ERR_IO, false, "failed to write primary header to %s",
                sfiles->outMask->resolved_name);
            streaksExit("", PS_EXIT_DATA_ERROR);
        }
        // TODO: add keyword indicating that this is the recovery image
        if (remove && sfiles->recMask && !psFitsWriteBlank(sfiles->recMask->fits, maskHeader, NULL)) {
            psError(PS_ERR_IO, false, "failed to write primary header to %s",
                sfiles->recMask->resolved_name);
            streaksExit("", PS_EXIT_DATA_ERROR);
        }
        psFree(maskHeader);
    }
    sFile *inWeight = sfiles->inWeight;
    if (inWeight) {
        psMetadata *weightHeader = psFitsReadHeader(NULL, inWeight->fits);
        if (!weightHeader) {
            psError(PS_ERR_IO, false, "failed to read primary header from %s\n",
                sfiles->inWeight->resolved_name);
            streaksExit("", 1);
        }
        // TODO: add keyword indicating that streaks have been removed
        if (!psFitsWriteBlank(sfiles->outWeight->fits, weightHeader, NULL)) {
            psError(PS_ERR_IO, false, "failed to write primary header to %s",
                sfiles->outWeight->resolved_name);
            streaksExit("", PS_EXIT_DATA_ERROR);
        }
        // TODO: add keyword indicating that this is a recovery image
        if (remove && sfiles->recWeight && !psFitsWriteBlank(sfiles->recWeight->fits, weightHeader, NULL)) {
            psError(PS_ERR_IO, false, "failed to write primary header to %s",
                sfiles->recWeight->resolved_name);
            streaksExit("", PS_EXIT_DATA_ERROR);
        }
        psFree(weightHeader);
    }
}

// Determine whether the current header for this file is an image or not
// Find a cleaner way to do this
static bool
isImage(sFile *in)
{
    bool status;
    psString exttype = psMetadataLookupStr(&status, in->header, "EXTTYPE");
    if (exttype && !strcmp(exttype, "IMAGE")) {
        return true;
    }
    // examine current header and determine if it is an image
    psString xtension = psMetadataLookupStr(&status, in->header, "XTENSION");
    if (xtension) {
        if (!strcmp(xtension, "IMAGE")) {
            return true;
        } else if (!strcmp(xtension, "BINTABLE")) {
            psString ztension = psMetadataLookupStr(&status, in->header, "ZTENSION");
            if (ztension && !strcmp(ztension, "IMAGE")) {
                return true;
            }
        }
    } else if (psMetadataLookupBool(&status, in->header, "ZIMAGE")) {
        return true;
    } else if (in->nHDU == 1) {
        // no extensions in the file, can just return true? For now require 
        // at least one dimension
        int naxis =  psMetadataLookupS32(&status, in->header, "NAXIS");
        return naxis > 0;
    }
    return false;
}

void
readImageFrom_pmFile(streakFiles *sf)
{
    // XXX: This function assumes that it is only used for a single
    // chip single cell FPA (i.e. a skycell)
    pmFPAview *view = sf->view;
    assert(view->chip == 0);
    view->cell = 0;
    sf->cell =  pmFPAviewThisCell(view, sf->inImage->pmfile->fpa);

    if (!sf->cell) {
        streaksExit("no cells found in chip", PS_EXIT_PROG_ERROR);
    }
    if (sf->cell->readouts->n != 1) {
        psError(PS_ERR_PROGRAMMING, true, "unexpected number of readouts found: %ld", sf->cell->readouts->n);
        streaksExit("", PS_EXIT_PROG_ERROR);
    }
    view->readout = 0;
    pmReadout *readout = pmFPAviewThisReadout(view, sf->inImage->pmfile->fpa);
    if (!readout) {
        streaksExit("readout 0 not found", PS_EXIT_PROG_ERROR);
    }

    sf->inImage->image = (psImage*) psMemIncrRefCounter(readout->image);
    sf->inImage->numCols = readout->image->numCols;
    sf->inImage->numRows = readout->image->numRows;
}

void
setDataExtent(ippStage stage, sFile *in)
{
    if (stage == IPP_STAGE_RAW) {
        psString datasec = psMetadataLookupStr(NULL, in->header, "DATASEC");
        if (!datasec) {
            psError(PS_ERR_IO, false, "failed to find DATASEC in header");
            streaksExit("", PS_EXIT_DATA_ERROR);
        }
        int xmin, xmax, ymin, ymax;
        sscanf(datasec, "[%d:%d,%d:%d]", &xmin, &xmax, &ymin, &ymax);
        in->numCols = xmax - xmin + 1;
        in->numRows = ymax - ymin + 1;
    } else {
        in->numCols = in->image->numCols;
        in->numRows = in->image->numRows;
    }
}

void
readImage(sFile *in, int extnum, ippStage stage)
{
    psRegion region = {0, 0, 0, 0};

    if (in->header) psFree(in->header);
    if (in->image) {
        psFree(in->image);
        in->image = NULL;
    }
    if (in->imagecube) {
        psFree(in->imagecube);
        in->imagecube = NULL;
    }

    in->header = psFitsReadHeader(NULL, in->fits);
    if (!in->header) {
        psError(PS_ERR_IO, false, "failed to read header from %s extnum: %d", 
            in->resolved_name, extnum);
        streaksExit("", PS_EXIT_DATA_ERROR);
    }

    bool status;
    in->extname = psMetadataLookupStr(&status, in->header, "EXTNAME");

    if (!isImage(in)) {
        return;
    }

    in->numZPlanes = psMetadataLookupS32(NULL, in->header, "NAXIS3");

    if (in->numZPlanes == 0) {
        in->image = psFitsReadImage(in->fits, region, 0);
        if (!in->image) {
            psError(PS_ERR_IO, false, "failed to read image from %s extnum: %d", 
                in->resolved_name, extnum);
            streaksExit("", PS_EXIT_DATA_ERROR);
        }
    }  else {
        if (stage != IPP_STAGE_RAW) {
            psError(PS_ERR_PROGRAMMING, true, "unexpected image cube found in non-raw image");
            streaksExit("", PS_EXIT_PROG_ERROR);
        }
        in->imagecube = psFitsReadImageCube(in->fits, region);
        if (!in->imagecube) {
            psError(PS_ERR_IO, false, "failed to read image cube from %s extnum: %d", 
                in->resolved_name, extnum);
            streaksExit("", PS_EXIT_DATA_ERROR);
        }
        psImage *image = (psImage *) (in->imagecube->data[0]);
    }
    setDataExtent(stage, in);
}

static void
setFitsOptions(sFile *sfile, int bitpix, float bscale, float bzero)
{
    if (!sfile) {
        return;
    }
    if (sfile->fits->options) {
        psFree(sfile->fits->options);
    }
    sfile->fits->options = psFitsOptionsAlloc();
    sfile->fits->options->scaling = PS_FITS_SCALE_MANUAL;
    sfile->fits->options->bitpix = bitpix;
    sfile->fits->options->bscale = bscale;
    sfile->fits->options->bzero = bzero;
}

void
copyFitsOptions(sFile *out, sFile *rec, sFile *in)
{
    // Get current BITPIX, BSCALE, BZERO, EXTNAME
    // Probably not necessary to look the numerical values up in this
    // way, but guards against changes to psLib and cfitsio FITS
    // handling.
    psMetadataItem *bitpixItem = psMetadataLookup(in->header, "BITPIX");
    psAssert(bitpixItem, "Every FITS image should have BITPIX");
    int bitpix = psMetadataItemParseS32(bitpixItem);
    psMetadataItem *bscaleItem = psMetadataLookup(in->header, "BSCALE");

    float bscale;
    if (!bscaleItem) {
        psWarning("BSCALE isn't set; defaulting to unity");
        bscale = 1.0;
    } else {
        bscale = psMetadataItemParseF32(bscaleItem);
    }
    psMetadataItem *bzeroItem = psMetadataLookup(in->header, "BZERO");
    float bzero;
    if (!bzeroItem) {
        psWarning("BZERO isn't set; defaulting to zero");
        bzero = 0.0;
    } else {
        bzero = psMetadataItemParseF32(bzeroItem);
    }

#ifdef STREAKS_COMPRESS_OUTPUT
    setFitsOptions(out, bitpix, bscale, bzero);
    setFitsOptions(rec, bitpix, bscale, bzero);
#endif
}


void
copyTable(sFile *out, sFile *in, int extnum)
{
    bool mdok;
    psString xtension = psMetadataLookupStr(&mdok, in->header, "XTENSION");
    psString extname = psMetadataLookupStr(&mdok, in->header, "EXTNAME");

    if (!xtension) {
        psWarning("extnum %d has no image and xtension is not defined in %s",
            extnum, in->resolved_name);
        // XXX abort?
        return;
    } 
    if (!extname) {
        psWarning("extnum %d has no image and extname not defined in %s",
            extnum, in->resolved_name);
        // XXX abort?
        return;
    }
    psArray *table = psFitsReadTable(in->fits);
    if (!table) {
        psError(PS_ERR_UNKNOWN, false, "failed to read table in extension %d from in->resolved name", extnum);
        streaksExit("", PS_EXIT_DATA_ERROR);
    }

    if (!psFitsWriteTable(out->fits, out->header, table, extname)) {
        psError(PS_ERR_UNKNOWN, false, "failed to copy table in extension %d", extnum);
        streaksExit("", PS_EXIT_DATA_ERROR);
    }
}

static void
createNewImage(sFile *out, sFile *in, int extnum, double initValue)
{
    out->image = psImageRecycle(out->image, in->image->numCols, in->image->numRows, in->image->type.type);
    if (!out->image) {
        psError(PS_ERR_UNKNOWN, false, "failed to allocate image for extnsion %d", extnum);
        streaksExit("", PS_EXIT_UNKNOWN_ERROR);
    }
    psImageInit(out->image, initValue);
}

void
setupImageRefs(sFile *out, sFile *recoveryOut, sFile *in, int extnum, bool exciseAll)
{
    if (!exciseAll) {
        // set output image to be the input image
        out->image = (psImage*) psMemIncrRefCounter(in->image);
        if (recoveryOut) {
            // create a recovery image initialized to NAN
            createNewImage(recoveryOut , in, extnum, NAN);
        }
    } else {
        // Excising all pixels in the input
        // set the output to an image all NANs
        createNewImage(out, in, extnum, NAN);
        if (recoveryOut) {
            // save the whole input as the recovery image
            recoveryOut->image = (psImage*) psMemIncrRefCounter(in->image);
        }
    }
}

void
writeImage(sFile *sfile, psString extname, int extnum)
{
    if (!sfile || !sfile->image) {
        return;
    }
    if (!psFitsWriteImage(sfile->fits, sfile->header, sfile->image, 0, extname)) {
        psError(PS_ERR_IO, false, "failed to write image to %s extnum: %d", 
            sfile->resolved_name, extnum);
        streaksExit("", PS_EXIT_DATA_ERROR);
    }
    psFree(sfile->image);
    sfile->image = NULL;
    psFree(sfile->header);
    sfile->header = NULL;
}

void
writeImageCube(sFile *sfile, psArray *imagecube, psString extname, int extnum)
{
    if (!imagecube) {
        return;
    }
    if (!psFitsWriteImageCube(sfile->fits, sfile->header, imagecube, extname)) {
        psError(PS_ERR_IO, false, "failed to write image to %s extnum: %d", 
            sfile->resolved_name, extnum);
        streaksExit("", PS_EXIT_DATA_ERROR);
    }
    psFree(sfile->header);
    sfile->header = NULL;
}

#ifdef notdef
void
writeImages(streakFiles *sf, bool exciseImageCube)
{
    psString extname = NULL;
    if (sf->nHDU > 1) {
        bool mdok;
        extname = psMetadataLookupStr(&mdok, sf->inImage->header, "EXTNAME");
    }
    if (sf->inImage->numZPlanes == 0)  {
        // note exciseing complete images is handled in readAndCopyToOutput
        writeImage(sf->outImage, extname, sf->extnum);
        writeImage(sf->recImage, extname, sf->extnum);
    } else {
        // we have an image cube
        double initValue;
        if (exciseImageCube) {
            // copy the entire input image to the recovery image
            writeImageCube(sf->recImage, sf->inImage->imagecube, extname, sf->extnum);
            initValue = NAN;
        } else {
            // otherwise write it to the output 
            writeImageCube(sf->outImage, sf->inImage->imagecube, extname, sf->extnum);
            initValue = 0;
        }

        // borrow one of the images from the imagecube and set it to init value
        psImage *image = psArrayGet (sf->inImage->imagecube, 0);
        psMemIncrRefCounter(image);
        psImageInit(image, initValue);
        if (exciseImageCube) {
            sf->outImage->image = image;
            writeImage(sf->outImage, extname, sf->extnum);
        } else {
            // write zero valued image to reccovery
            if (sf->recImage) {
                sf->recImage->image = image;
                writeImage(sf->recImage, extname, sf->extnum);
            }
        }
        // Assumption: there are no mask and weight images for video cells
        return;
    }
    if (sf->outMask) {
        writeImage(sf->outMask, extname, sf->extnum);
        writeImage(sf->recMask, extname, sf->extnum);
    }
    if (sf->outWeight) {
        writeImage(sf->outWeight, extname, sf->extnum);
        writeImage(sf->recWeight, extname, sf->extnum);
    }
}
#endif

void
closeImage(sFile *sfile)
{
    if (!sfile) {
        return;
    }
    if (sfile->fits && !psFitsClose(sfile->fits)) {
        psError(PS_ERR_IO, false, "failed to close image to %s", 
            sfile->resolved_name);
        streaksExit("", PS_EXIT_DATA_ERROR);
    }
    psFree(sfile->header);
    psFree(sfile->image);
    psFree(sfile->imagecube);
    psFree(sfile->name);
    psFree(sfile->resolved_name);
    psFree(sfile);
}

void
closeImages(streakFiles *sf)
{
    closeImage(sf->inImage);
    closeImage(sf->outImage);
    closeImage(sf->recImage);
    if (sf->inMask) {
        closeImage(sf->inMask);
        closeImage(sf->outMask);
        closeImage(sf->recMask);
    }
    if (sf->inWeight) {
        closeImage(sf->inWeight);
        closeImage(sf->outWeight);
        closeImage(sf->recWeight);
    }
}

bool
replicate(sFile *sfile, void *xattr)
{
    if (!sfile->inNebulous) {
        return true;
    }
    nebServer *server = getNebServer(NULL);

    // for now just set "user.copies" to 2
    if (!nebSetXattr(server, sfile->name, "user.copies", "2",  NEB_REPLACE)) {
        psError(PM_ERR_UNKNOWN, true, "nebSetXattr failed for %s\n%s", sfile->name, nebErr(server));
        return false;
    }
    if (!nebReplicate(server, sfile->name, NULL, NULL)) {
        psError(PM_ERR_UNKNOWN, true, "nebSetXattr failed for %s\n%s", sfile->name, nebErr(server));
        return false;
    }
    return true;
}

// for any of the outputs that are stored in Nebulous set their extended attributes
// and replicate the files

static bool
replicateOutputs(streakFiles *sfiles)
{
    bool status = false;

    // XXX: TODO: need a nebGetXatrr function, but there isn't one
    // another option would be to take the number of copies to be
    // created as an option. That way the system could decide
    // whether to replicate anything other than raw Image files
    void *xattr = NULL;

    if (!replicate(sfiles->outImage, xattr)) {
        psError(PM_ERR_SYS, false, "failed to replicate outImage.");
        return false;
    }

#ifdef notyet
    // XXX: don't replicate mask and weight images until we can look up
    // the input's xattr. There may be a perl program that can getXattr
    if (sfiles->outMask) {
        // get xattr from input to see if we need to replicate
        if (!replicate(sfiles->outMask, xattr)) {
            psError(PM_ERR_SYS, false, "failed to replicate outImage.");
            return false;
        }
    }
    if (sfiles->outWeight) {
        // get xattr from input to see if we need to replicate
        if (!replicate(sfiles->outWeight, xattr)) {
            psError(PM_ERR_SYS, false, "failed to replicate outImage.");
            return false;
        }
    }
#endif

//      replicate the recovery images (if in nebulous)
//      perhaps whether we do that or not should be configurable.
//      Sounds like we need a recipe

    return true;
}

static bool
swapOutputToInput(sFile *in, sFile *out)
{

    if (in->inNebulous) {
        nebServer *server = getNebServer(NULL);

        if (!nebSwap(server, in->name, out->name)) {
            psError(PM_ERR_SYS, true, "failed to swap files for: %s.",
                in->name, nebErr(server));
            return false;
        }
    } else {
        psString command = NULL;

        // regular files. use mv creating a backup
        // NOTE: -b is a gnu option and may not always be available
        psStringAppend(&command, "mv -b --suffix=.bak %s %s", out->resolved_name, in->resolved_name);
        int status = system(command);
        if (status != 0) {
            psError(PM_ERR_SYS, true, "%s failed with status %d.",
                command, status);
            psFree(command);
            return false;
        }
        psFree(command);
        // XXX: shouldn't I be doing mv in->resolved_name.bak out->resolved_name
        // to complete the swap if !remove?
    }

    return true;
}
static bool
swapOutputsToInputs(streakFiles *sfiles)
{
    if (sfiles->inMask) {
        if (!swapOutputToInput(sfiles->inMask, sfiles->outMask)) {
            psError(PM_ERR_SYS, false, "failed to swap instances for Mask.");
            return false;
        }
    }

    if (sfiles->inWeight) {
        if (!swapOutputToInput(sfiles->inWeight, sfiles->outWeight)) {
            psError(PM_ERR_SYS, false, "failed to swap instances for Weight.");
            return false;
        }
    }

    if (!swapOutputToInput(sfiles->inImage, sfiles->outImage)) {
        psError(PM_ERR_SYS, false, "failed to swap instances for Image.");
        return false;
    }

    return true;
}

static bool
deleteFile(sFile *sfile)
{

    if (sfile->inNebulous) {
        nebServer *server = getNebServer(NULL);
        if (!nebDelete(server, sfile->name)) {
            psError(PM_ERR_SYS, false, "failed to delete %s\n%s.", sfile->name,
                nebErr(server));
            return false;
        }
    } else {
        if (unlink(sfile->resolved_name)) {
            psError(PM_ERR_SYS, false, "failed to delete %s\n%s.", sfile->resolved_name,
                strerror(errno));
            return false;
        }
    }
    return true;
}

static bool
deleteTemps(streakFiles *sfiles)
{
    if (sfiles->outMask) {
        if (!deleteFile(sfiles->outMask)) {
            psError(PM_ERR_SYS, false, "failed to delete Mask.");
            return false;
        }
    }

    if (sfiles->outWeight) {
        if (!deleteFile(sfiles->outWeight)) {
            psError(PM_ERR_SYS, false, "failed to delete Weight.");
            return false;
        }
    }

    if (!deleteFile(sfiles->outImage)) {
        psError(PM_ERR_SYS, false, "failed to delete Image.");
        return false;
    }

    return true;
}

