/*
 * DANG_BEGIN_MODULE
 * 
 * PHASE1 initialization:
 *
 * This is where you initialize anything necessary to create a virtual
 * PC configuration.  Intialize the cpu, the various chips (pic, pit, etc.)
 * and then setup & initialize the BIOS, etc.
 * 
 * DANG_END_MODULE
 * 
 * DANG_BEGIN_CHANGELOG
 *
 * $Date: $
 * $Source: $
 * $Revision: $
 * $State: $
 *
 * $Log: $
 *
 * DANG_END_CHANGELOG
 */

#include "dosemu.h"
#include "base/memory.h"
#include "base/bios.h"
#include "base/mouse.h"
#include "base/iodev.h"
#include "base/shared.h"
#include "base/phase.h"
#include "base/misc.h"
#include "base/bios_entry.h"
#include "env/setup.h"

/* 
 * DANG_BEGIN_FUNCTION device_init
 * 
 * description:
 *  Calls all initialization routines for devices (keyboard, video, serial,
 *    disks, etc.)
 *
 * DANG_END_FUNCTION
 */
static inline void device_init(void)
{
  mouse_init();
}

static inline void device_reset(void)
{
  keyboard_flags_init();
  video_config_reset();
}

/* 
 * DANG_BEGIN_FUNCTION bios_mem_setup
 * 
 * description:
 *  Set up all memory areas as would be present on a typical i86 during
 * the boot phase.
 *
 * DANG_END_FUNCTION
 */
static inline void bios_mem_setup(void)
{
  keybuf_clear();

#if 0
  bios_ctrl_alt_del_flag = 0x0000;
  bios_keyboard_flags2   = 16;	/* 102-key keyboard */
#endif

  WRITE_WORD(LASTSCAN_ADD, 1);
}

/*
 * DANG_BEGIN_FUNCTION phase1_init
 * 
 * description:
 *  Fire up phase 1
 *
 * DANG_END_FUNCTION
 */
void phase1_init(void)
{
  emulator_init();              /* initialize the x86 emulator */
  a20_init();                   /* initialize A20 line */
  iodev_init();                 /* initialize the io-devices */
  device_init();		/* initialize keyboard, disk, video, etc. */
  bios_init();                  /* initialize the bios */
  dos_helper_init();            /* initialize halt block */
  env_phase1_init();            /* setup the environment */
  shared_memory_init();         /* shared memory init */
  shared_keyboard_init();
}

void phase1_reset(void)
{
  emulator_reset();             /* reset the x86 emulator */
  a20_reset();                  /* reset the A20 line */
  cpu_reset();                  /* reset the CPU regs */
  iodev_reset();                /* reset the io devices */
  device_reset();               /* reset the keyboard, disks, etc. */ 
  bios_init();                  /* reset the bios */
  bios_mem_setup();
  env_phase1_reset();           /* reset the environment */

  g_printf("BIOS: dosemu_banner, old CS:IP = 0x%04x:0x%04x\n", _CS, _IP);
  _CS = BIOSSEG;
  _IP = ROM_BIOS_SELFTEST;
}

void phase1_term(void)
{
  g_printf("PHASE1: calling mouse_close\n");
  mouse_close();

  g_printf("LEAVE: calling shared memory exit\n");
  shared_memory_exit();

  g_printf("LEAVE: calling iodev_term()\n");
  iodev_term();
}
