/* macro.c : part of The Bastard disassembly environment ======================
 *
 * Contains the code for interfacing with the SeerC interpreter, as well as the
 * "interpreter" commands [i.e. LOAD, SHOW, etc] which are really wrappers for
 * API routines.
 */
#include <script/script_main.h>
#include <stdlib.h>
#include <extension.h>
#include <debug.h>

extern struct DISASM_TGT target;
extern struct DISASM_ENV disasm_env;

         
/* =================================================== EiC Stuff */
extern int EicLoadApi( void) ;

/* note ": call this and initDB from an API Init() routine */
void InitInterpreter(){
   char cmd[2048];

   EiC_init_EiC();
   stdClib();
   EicLoadApi();
   sprintf(cmd, "-I%s/include -I%s/include/script/eic  -D_EiC", 
         disasm_env.home, disasm_env.home);
   EiC_switches(cmd);
   //EiC_switches("-A -I./include -I./include/script/eic  -D_EiC");
   sprintf(cmd, "#pragma push_unsafeptr\n#define PATH_MAX %d\n"
                "#include <bdb.h>\n"
                "#include <bastard.h>\n", PATH_MAX);
   EiC_parseString(cmd);
   EiC_parseString("#include <stdlib.h>"); /* autoinclude stdlib */
   EiC_parseString("#include <stdio.h>"); /* autoinclude stdio */
   EiC_parseString("#define exit(x) {int y; y=x;}"); /* fix EiC exit prob */
   return;
}

/* =================================================== ExecMacroLine */
int ExecMacroLine(char *cmd) {
   int x;
   char line[1024];
   
   disasm_env.flags &= IN_EIC;
   //free_env_code();   
  // EiC_parseString(":reset here");
   DEBUG_PrintMsg("Sending to EiC: %s\n", cmd);
   EiC_parseString(cmd);
   //EiC_parseString(":reset");
   //EiCp_ResetStart();
   disasm_env.flags &= ~IN_EIC; 
   return(1);
}
int ExecScript(char *name, int argc, char **argv){
   char cmd[2048] = ":clear ";
   char *tmparg[] = { name };
   int rv;

   if (argv) argv[0] = name;
   else argv = tmparg;
   if (!argc) argc = 1;
   //EiC_parseString("#include <stdlib.h>"); /* autoinclude stdlib */
   //EiC_parseString("#define exit(x) {int y; y=x;}"); /* fix EiC exit prob */
   disasm_env.flags &= IN_EIC;
   rv = EiC_run(argc, argv);
   /* Full Reset :  EiCp_setResetStart();  */
   strncat(cmd, name, 2048);
   EiC_parseString(cmd); /* fix EiC_run environment weirdness */
   disasm_env.flags &= ~IN_EIC; 
   return(rv);
}
int LoadScript(char *name){
   /* this is used to load scripts without a main() routine */
   struct stat statbuf;
   char cmd[2048], *script;
   

   if (  name[0] == '.' &&
         name[1] == '/' )
      script = &name[2];
   else  script = name;

   if (! stat(script, &statbuf)) {
      //EiC_loadFile(name);
      sprintf(cmd, "#include \"%s\"\n", script);
      EiC_parseString( cmd );
      return(1);
   } 

   return(SetLastError(9020));
}
   
