/*
   Copyright (C) 1999 T. Scott Dattalo

This file is part of gpsim.

gpsim is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

gpsim is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with gpsim; see the file COPYING.  If not, write to
the Free Software Foundation, 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.  */

#include <glib.h>

#include <stdio.h>

#include <iostream>
#include <string>

#include "command.h"
#include "cmd_load.h"
#include "misc.h"
#include "input.h"

#include "../src/eeprom.h"
#include "../src/fopen-path.h"
#include "../src/gpsim_object.h"
#include "../src/hexutils.h"
#include "../src/i2c-ee.h"
#include "../src/pic-processor.h"
#include "../src/processor.h"
#include "../src/program_files.h"
#include "../src/sim_context.h"
#include "../src/symbol.h"
#include "../src/ui.h"

class Register;

extern int parser_warnings;
extern void redisplay_prompt();  // in input.cc

// instead of including the whole symbol.h file, just get what we need:
void display_symbol_file_error(int);

cmd_load c_load;

#define CMD_LOAD_HEXFILE 1
#define CMD_LOAD_CMDFILE 2
#define CMD_LOAD_CODFILE 3 // s for Symbol file
#define CMD_LOAD_INCLUDE_CMDFILE 4  // like load, but don't change directories.
#define CMD_LOAD_EEPROM 5


static cmd_options cmd_load_options[] =
{
  {"h", CMD_LOAD_HEXFILE,    OPT_TT_BITFLAG},
  {"c", CMD_LOAD_CMDFILE,    OPT_TT_BITFLAG},
  {"s", CMD_LOAD_CODFILE,    OPT_TT_BITFLAG},
  {"i", CMD_LOAD_INCLUDE_CMDFILE,    OPT_TT_BITFLAG},
  {"e", CMD_LOAD_EEPROM,    OPT_TT_BITFLAG},
  {nullptr, 0, 0}
};


cmd_load::cmd_load()
  : command("load", "ld")
{
  brief_doc = "Load either a program or command file";

  long_doc = "    load programfile.cod [label] \
\n    load processortype programfile.hex [label] \
\n    load [i] cmdfile.stc\
\n\n\tLoad either a program or command file. Program files may be in\
\n\thex or cod (symbol) file format, however, a cod file is required for\
\n\tfull Gpsim functionality.\
\n\t(Gputil .cod files are the only program files with symbols\
\n\tthat are supported.)\
\n\
\n\t  processortype - Name of the processor type simulation for .hex file\
\n\t                  used. (e.g. p16f88)\
\n\t  programfile   - a hex or cod formatted file. Cod is often called\
\n\t                  a symbol file.\
\n\t  label         - optional field used to identify processor on\
\n\t                  breadboard and symbol table prefix.\
\n\t                  If not supplied processor type is used.\
\n\t  cmdfile       - a gpsim command file. Must have an .stc extension\
\n\t                  unless the 'i' option is used.\
\n\
\n\t By default, .stc files residing in other directories will change\
\n\t the working directory. The 'i' option overrides that behavior. \
\n\
\n    load e module_name hexfile\
\n\
\n\t This command loads the contents of either a module or processor\
\n\t EEPROM from an Intel hex format file. The address of the first\
\n\t cell of the EEPROM is 0x0000. \
\n\t This command will load a file generated by the 'dump e' command and\
\n\t thus can be used to restore state of EEPROM from a previous run.\
\n\
\n\tdeprecated:\
\n\t  load  h | c | s  file_name\
\n\t  load s perfect_program.cod\
\n\t    will load the symbol file perfect_program.cod\
\n\t    note that the .cod file contains the hex stuff\
\n";

  op = cmd_load_options; 
}

//--------------------
//
//
#define MAX_LINE_LENGTH 256
extern void process_command_file(const char * file_name, bool bCanChangeDirectory);

/**
  * cmd_load.load()
  * returns boolean
  */
int cmd_load::load(int bit_flag,const char *filename)
{
  int iReturn = (int)TRUE;
  bool bCanChangeDirectories = true;
  switch (bit_flag) {

  case CMD_LOAD_HEXFILE:
    FILE *file;
    Processor *cpu;

    std::cout << "cmd_load::load hex file " << filename << '\n';
    if ((cpu = get_active_cpu()) == nullptr) {
      fprintf(stderr, "cmd_load:: load hex, Processor not defined\n");
      iReturn = (int)FALSE;
    }
    else if ((file = fopen(filename, "r")) == nullptr) {
      perror(filename);
      iReturn = (int)FALSE;
    }
    else {
      IntelHexProgramFileType::readihex16(cpu, file);
      fclose(file);
      //cmd_cpu->regwin_eeprom->Update();
    }
    break;

  case CMD_LOAD_CODFILE:
    if (verbose) {
      switch(bit_flag) {
      case CMD_LOAD_HEXFILE:
        std::cout << "cmd_load::load hex file " << filename << '\n';
        break;

      case CMD_LOAD_CODFILE:
        std::cout << " cmd_load::load cod file "  << filename << '\n';
        break;
      }
    }
    iReturn = CSimulationContext::GetContext()->LoadProgram(filename);
    break;

  case CMD_LOAD_INCLUDE_CMDFILE:
    bCanChangeDirectories = false;
    // ... fall through

  case CMD_LOAD_CMDFILE:
    /* Don't display parser warnings will processing the command file */
    parser_warnings = 0;
    process_command_file(filename, bCanChangeDirectories);
    parser_warnings = 1;
    break;

  default:
    std::cout << "Unknown option flag\n";
    iReturn = (int)FALSE; // as a boolean
  }

  // Most of the time diagnostic info will get printed while a processor
  // is being loaded.

  redisplay_prompt();

  return iReturn;
}

int cmd_load::load(int bit_flag, gpsimObject* module, const char *filename)
{
  Register ** fr;
  gint32 mem_size;
  char s1[256];
  std::string symName;
  pic_processor *pic;
  I2C_EE *eeprom;
  FILE *fd;
  PromAddress *sym;
  int iReturn = (int)TRUE;

  module->name(s1, sizeof(s1));
  symName = s1;
  symName += ".eeprom";
  fprintf(stdout, "cmd_load module=%s file=%s\n", s1, filename);

  if (bit_flag != CMD_LOAD_EEPROM)
  {
      std::cout << "Unknown option flag with module, filename\n";
      return  (int)FALSE;
  }

  if ((fd = fopen(filename, "r")) == nullptr)
  {
      perror(filename);
      return  (int)FALSE;
  }

  if (( pic = dynamic_cast<pic_processor *> (module)) && pic->eeprom)
  {
        fr = pic->eeprom->get_rom();
        mem_size = pic->eeprom->get_rom_size();
        iReturn = IntelHexProgramFileType::readihex8(fr, mem_size, fd, 0x0) == SUCCESS;
  }
  else if ((sym = dynamic_cast<PromAddress *>(globalSymbolTable().find(symName))))
  {
        sym->get(eeprom);
        fr = eeprom->get_rom();
        mem_size = eeprom->get_rom_size();

        iReturn = IntelHexProgramFileType::readihex8(fr, mem_size, fd, 0x0000) == SUCCESS;
  }
  else
  {
	 std::cout << "*** Error cmd_load module " << s1 << " not EEPROM\n";
	 iReturn = (int)FALSE;
  }

  if (fd)
      fclose(fd);
  return iReturn;
}

//------------------------------------------------------------------------
//
// load 

static int load1(const char *s1, const char *s2)
{
  FILE *fp = fopen_path(s1, "rb");
  if (fp) {
    fclose (fp);
    return gpsim_open(get_active_cpu(), s1, s2, 0);
  }
  if (!s2) // can be called s1=name s2=file
      perror(s1); 

  return s2 ? gpsim_open(get_active_cpu(), s2, 0, s1) : 0;
}

int cmd_load::load(gpsimObject *file, gpsimObject *pProcessorType)
{
  std::cout << '\n';

  char s1[256];
  file->toString(s1, sizeof(s1));

  if (pProcessorType) {
    char s2[256];
    pProcessorType->toString(s2, sizeof(s2));
    return load1(s1, s2);
  }
  return load1(s1, nullptr);
}

int cmd_load::load(const char *file, const char *pProcessorType)
{
  return load1(file, pProcessorType);
}
