/***************************** 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 "compile.h"
#include "Cached.h"

extern "C" {

extern int zzlineno;

int parse_macro(void);
void zzerror(char* msg)
{
    Compiler::compileError(msg, zzlineno + 1);
}
}

int Compiler::compileCore(const char* filename, int* lineNo, FILE** fpIn)
{
    //	extern int zzc_debug;
    /* zzc_debug = 1; */

    Cached oldDir(script_->MacroMainPath());  //-- save previous path

    char pwd[1024];
    getcwd(pwd, sizeof(pwd) - 1);

    script_->MacroPath(makepath(pwd, filename));
    script_->MacroMainPath(makepath(pwd, filename));  //-- E.Monreal INM. 2003-02-26

    if (filename)
        *fpIn = fopen(filename, "r");
    else
        *fpIn = stdin;

    if (*fpIn == 0) {
        marslog(LOG_EROR | LOG_PERR, "Cannot open %s", filename);
        script_->SetError(1);
        return script_->GetError();
    }

    *(lineNo) = 0;

    Step* i = script_->Instruction;
    Context* c = script_->Current;
    Script* s = script_->Compiled;
    script_->Instruction = 0;
    script_->Current = script_->Compiled = script_;

    parseIt();

    script_->Instruction = i;
    script_->Current = c;
    script_->Compiled = s;
    fclose(*fpIn);

    script_->MacroMainPath((const char*)oldDir);  //-- revert to previous path

    return script_->GetError();
}


int ScriptCompiler::compile(const char* filename)
{
    extern FILE* zzin;

    return compileCore(filename, &zzlineno, &zzin);
}

void ScriptCompiler::parseIt()
{
    parse_macro();
}
