/***************************** 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 <ctype.h>
#include <script.h>

void Compute::rename(math* m, char* name, const char* sub)
{
    if (m) {
        if (m->name && (m->arity <= 0) && (name == m->name)) {
            strfree(name);
            m->name = strcache(sub);
        }
        rename(m->left, name, sub);
        rename(m->right, name, sub);
    }
}

// Import all the relevent names

void Compute::import(FILE* f, math* m, request* r)
{
    static int n = 0;
    if (m) {
        import(f, m->left, r);
        import(f, m->right, r);

        if (m->name && m->arity <= 0)
            if (!is_number(m->name) && (m->name[0] != '.')) {
                char buf[1024];
                const char* p = buf;

                sprintf(buf, "%s", m->name);

                // Get rid of quotes
                if (*buf == '"' || *buf == '\'') {
                    p = buf + 1;
                    buf[strlen(buf) - 1] = 0;
                }

                p = makepath(mdirname(Name()), p);

                fprintf(f, "x%d = metview(\"%s\")\n", n, p);

                // Add a dummy subrequest, so pool_link_objects
                // do its work
                request* u = empty_request("DUMMY");
                /* sprintf(buf,".x%d",n); */
                set_value(u, "_NAME", "%s", p);
                sprintf(buf, "PARAMETER_%d", n);
                set_subrequest(r, buf, u);
                free_all_requests(u);

                //

                char* s = strcache(m->name);
                sprintf(buf, ".x%d", n);
                rename(Math, s, buf);
                strfree(s);
                n++;
            }
    }
}

void Compute::write(FILE* f, math* m)
{
    if (m) {
        if (m->name)
            if (m->arity <= 0) {
                if (is_number(m->name))
                    fprintf(f, "%s", m->name);
                else
                    fprintf(f, "%s", m->name + 1);

                if (m->arity < 0) {
                    fprintf(f, "[");
                    write(f, m->left);
                    fprintf(f, "]");
                }
            }
            else {
                fprintf(f, "(");
                if (isalpha(m->name[0])) {
                    fprintf(f, "%s(", m->name);
                    write(f, m->left);
                    fprintf(f, ")");
                }
                else {
                    write(f, m->left);
                    fprintf(f, " %s ", m->name);
                    write(f, m->right);
                }
                fprintf(f, ")");
            }
        else {
            write(f, m->left);
            if (m->right)
                fprintf(f, ",");
            write(f, m->right);
        }
    }
}

// Free form formula

Compute::Compute(const char* name, request* r, Compiler* compiler) :
    Script(name, compiler)
{
    const char* form = get_value(r, "FORMULA", 0);
    char* file = marstmp();
    FILE* f = fopen(file, "w");
    if (!f)
        marslog(LOG_EROR | LOG_PERR, "Cannot open %s", file);
    else {
        if ((Math = compmath(form)) == nullptr)
            fprintf(f, "return error('Invalid formula')\n");
        else {
            import(f, Math, r);
            fprintf(f, "x =  ");
            write(f, Math);
            fprintf(f, "\n");
            fprintf(f, "return x");
        }
        fclose(f);
    }
    Compile(file);
    unlink(file);
}

Compute::~Compute()
{
    free_math(Math);
}

// Simple formula

Formula::Formula(const char* name, request* r,  Compiler* compiler) :
    Script(name, compiler)
{
    char* file = marstmp();


    FILE* f = fopen(file, "w");
    if (!f)
        marslog(LOG_EROR | LOG_PERR, "Cannot open %s", file);
    else {
        const char* p;
        if (mars.debug)
            fprintf(f, "trace(1)\n");
        fprintf(f, "x = arguments()\n");
        fprintf(f, "x = x[1]\n");
        if ((p = get_value(r, "FUNCTION", 0))) {
            fprintf(f, "return %s(", p);
            if ((p = get_value(r, "PARAMETER_2", 0)))
                fprintf(f, "x['PARAMETER_1'],x['PARAMETER_2']");
            else
                fprintf(f, "x['PARAMETER']");
            fprintf(f, ")");
        }
        if ((p = get_value(r, "OPERATOR", 0)))
            fprintf(f, "return x['PARAMETER_1'] %s x['PARAMETER_2']\n", p);

        fclose(f);
    }
    if (mars.debug) {
        char line[1024];
        f = fopen(file, "r");
        while (fgets(line, sizeof(line), f))
            std::cout << line;
        fclose(f);
        std::cout << std::endl;
    }
    Compile(file);
    unlink(file);
}


Formula::~Formula() = default;
