#include "InitBatch.h"

/**
  Destructor
  */
static void destroy(InitBatch* this) {

    // call superclass destructor
    this->base.destroy(&this->base);
    free (this);
}

/**
  Does the work.
  */
static int run(InitBatch* this) {

    if (this->base.exitCode != PS_EXIT_SUCCESS) return this->base.exitCode;

    if (!ippToPspsConfig_populateFromFile(this->base.config, this->base.fitsOut)) 
        this->base.exitCode = PS_EXIT_CONFIG_ERROR;
    else this->base.exitCode = PS_EXIT_SUCCESS;

    return this->base.exitCode;
}

/**
  Print-out this class. Calls base-calls print method first.
  */
static void print(InitBatch* this) {

    this->base.print(&this->base);
}

/**
  Reads command-line arguments.  Calls base-calls print method first.
  */
static bool parseArguments(InitBatch* this, int argc, char **argv) {

    this->base.parseArguments(&this->base, argc, argv);

    if (
            !this->base.gotFitsOutPath() ||
            !this->base.gotConfig() ) {

        printf("\n* ERROR with supplied arguments:");
        this->print(this);
        this->base.exitCode = PS_EXIT_CONFIG_ERROR;
        return false;
    }


    return true;
}

/**
  Constructor
  */
InitBatch* new_InitBatch(int *argc, char **argv) {

    InitBatch *this = (InitBatch*)calloc(1, sizeof(InitBatch));

    // call base-class constructor
    if (!new_Batch(&this->base)) {

        psError(PS_ERR_IO, false, "Unable to create Batch base-class object");
        return this;
    }

    this->print = print;
    this->destroy = destroy;
    this->base.run = run;

    if (!parseArguments(this, *argc, argv)) { return this; }

    strcat(this->base.configsDir, "/init");
    sprintf(this->base.fitsOutFile, "00000000.FITS");

    this->base.init(&this->base);

    return this;
}

/**
  Main
  */
int main(int argc, char **argv) {

    psTimerStart("initbatch");

    ippToPsps_VersionPrint();

    int exitCode;

    InitBatch* initBatch = new_InitBatch(&argc, argv);
    initBatch->base.run(initBatch);
    exitCode = initBatch->base.exitCode;

    initBatch->destroy(initBatch);

    double secs = psTimerMark("initbatch");

    psLogMsg("initbatch", 3, "initbatch completed %ssuccessfully, with exit code %d, in %.1f %s\n",
            (exitCode == PS_EXIT_SUCCESS) ? "" : "un",
            exitCode,
            (secs<60.0) ? secs : (secs/60.0),
            (secs<60.0) ? "sec(s)" : "min(s)");

    // tidy up
    psTimerStop();
    psLibFinalize();

    return exitCode;
}


