#include <api/api_main.h>
#include <extension.h>

extern struct DISASM_TGT target;
extern struct DISASM_ENV disasm_env;
extern struct DISASM_PREFS disasm_prefs;

/* API sections:
 *    16. Macros               :: User-defined/recorded seer scripts
 */

/* NOTE: These functions are redundant with ones macro.c and should replace them */
/* ---------------------------------------------------------------Macros */
   int RunScriptText(char *cmd) {
      return(ExecMacroLine(cmd));
   
   }

   int RunScript(char *name) {
      //LoadExtension( name, EXT_SCRIPT, ext_script );
      //return( ext_script->fn_main(0, NULL) );
      struct stat s;
      int len;
      char *path, tmp[PATH_MAX];

      if (name[0] == '"') { /* remove quotes if they exist */
         len = strlen(name);
         name[len - 1] = '\0';
         name++;
      }
      if ( stat(name, &s) ){
         sprintf( tmp, "%s/scripts/%s", disasm_env.home, name);
         if (stat(tmp, &s))
            // return(RunMacro)...
            return(0);
         path = tmp;
      } else {
         path = name;
      }
      return(ExecScript(path, 0, NULL));
   }

/* OBSOLETE !! */
   int RunCompiledScript(char *name){
      return(0);
   }

/* OBSOLETE !! */
   int CompileScript(char *name){
   /* This calls the external SeerC compiler to compile a .sc [Seer source]
    * script to a .scx [Seer binary] bytecode file */
   /* TODO: Fix the "#include bastard" problem */
      return(1);
   }


   /* MACROs stored in the DB 
    * TODO -- we need some provision for saving this
    * across databases */

   int DefineMacro( char *name, char *macro ){
      struct bc_macro m;

      memset(&m, 0, sizeof(struct bc_macro));
      strncpy(m.name, name, 31);
      m.id = ++seq.bc_macro;
      m.name[31] = 0;
      if (strlen(macro) > 2047) {
         m.type = 2;
         
         /* write to file in $HOME/scripts/macros */
      } else {
         m.type = 1;
         strcpy(m.macro, macro);
      }
      if ( d_fillnew(BC_MACRO, &m) != S_OKAY) 
              return(SetLastError(dbError()));
      return(m.id);
      
   }

   int UndefineMacro( char *name ){
      disasm_env.flags |= DB_MOD;
      if ( DBRecordDelete(BC_MACRO_NAME, name) )
         return(1);
      return(SetLastError(4601));
   }

   int RunMacro( char *name ){
      /* if type 1, compile macro */
      /* if type 2, read file and compile macro */
      ExecScript(name);
      /* run seer script */

   }
   int RecordMacro( char *name ){
      struct bc_macro m;
      /* 'enter xxx to exit' */
      /* while !xxx */
      /* gets, add to buff[2048] */
      /* DefineMacro */

   }
