/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include <MvFortran.h>
#include <signal.h>

MvFortran::MvFortran(const char* name) :
    Name(name),
    Temp(marstmp())
{
    char buf[1024];

    sprintf(buf, "MNAME=%s", (const char*)Name);
    putenv(strcache(buf));

    sprintf(buf, "MREQUEST=%s", (const char*)Temp);
    putenv(strcache(buf));
}

MvFortran::~MvFortran()
{
    unlink(Temp);
}


void MvFortran::addParameter(double x)
{
    MvRequest r("NUMBER");
    r("VALUE") = x;
    Param = Param + r;
    Param.save(Temp);
}

void MvFortran::addParameter(const char* x)
{
    MvRequest r("STRING");
    r("VALUE") = x;
    Param = Param + r;
    Param.save(Temp);
}

void MvFortran::addParameter(MvFieldSet& fs)
{
    Param = Param + fs.getRequest();
    Param.save(Temp);
}

int MvFortran::external(const char* cmd)
{
    char buf[1024];
    sprintf(buf, "env PATH=$PATH:$METVIEW_BIN %s 2>&1", cmd);

    int n = -1;

    signal(SIGCHLD, SIG_DFL);

    FILE* f = popen(buf, "r");

    if (f) {
        while (fgets(buf, sizeof(buf), f))
            marslog(LOG_INFO, "%s", buf);
        n = pclose(f);
    }

    return n;
}


MvRequest MvFortran::getResult()
{
    Result.read(Temp);
    return Result;
}
