/*****************************************************************************
FILE: espa_util.c

PURPOSE: Contains utility functions

*****************************************************************************/
#include <stdio.h>
#include <unistd.h>
#include "espa_metadata.h"

/******************************************************************************
MODULE:  delete_raw_binary

PURPOSE: Deletes ESPA raw binary image files

RETURNS: SUCCESS/ERROR
******************************************************************************/
int delete_raw_binary
(
    const Espa_internal_meta_t *xml_metadata, /* I:XML metadata */
    const char *source_dir,                   /* I:directory where files exist*/
    const char *espa_xml_file                 /* I:XML filename */
)
{
    char FUNC_NAME[] = "delete_raw_binary";
    char errmsg[STR_SIZE];      /* error message */
    char espa_band[PATH_MAX];   /* name of the raw binary for the band */
    char *cptr;
    int i;
    int count;

    for (i = 0; i < xml_metadata->nbands; i++)
    {
        /* .img file */
        count = snprintf (espa_band, sizeof(espa_band), "%s/%s",
            source_dir, xml_metadata->band[i].file_name);
        if (count < 0 || count >= sizeof (espa_band))
        {
            snprintf (errmsg, sizeof(errmsg), "Overflow of espa_band string");
            error_handler (true, FUNC_NAME, errmsg);
            return ERROR;
        }
        printf ("  Removing %s\n", espa_band);
        if ((access (espa_band, F_OK) == 0)
            && (unlink (espa_band) != 0))
        {
            snprintf (errmsg, sizeof(errmsg), 
                "Deleting source file: %s", espa_band);
            error_handler (true, FUNC_NAME, errmsg);
            return ERROR;
        }

        /* .hdr file */
        cptr = strrchr (espa_band, '.');
        if (cptr != NULL)
        {
            strcpy (cptr, ".hdr");
            printf ("  Removing %s\n", espa_band);
            if ((access (espa_band, F_OK) == 0)
                && (unlink (espa_band) != 0))
            {
                snprintf (errmsg, sizeof(errmsg), 
                    "Deleting source file: %s", espa_band);
                error_handler (true, FUNC_NAME, errmsg);
                return ERROR;
            }
        }
    }

    /* Remove the source XML if specified */
    if (espa_xml_file != NULL)
    {
        printf ("  Removing %s\n", espa_xml_file);
        if (unlink (espa_xml_file) != 0)
        {
            snprintf (errmsg, sizeof(errmsg), 
                "Deleting source file: %s", espa_xml_file);
            error_handler (true, FUNC_NAME, errmsg);
            return ERROR;
        }
    }

    return SUCCESS;
}
