

/*
 * Allots the memory for processor.
 * memory_buffer is a global variable.
 *
 */

 int create(void)
 {
  memory_buffer = (int *)malloc(3360 * sizeof(int)); 
  return(0);
 }


/*
 * 
 * To read data from simulated memory.
 * Returns the data at the desired address only if the address is within 
 * the range.
 * 
 */


 int memr(int read_addr) 
 {
  if( read_addr < 0x2000 || read_addr > 0x2d20) return(-1);
  return(memory_buffer[read_addr - 0x2000]);
 }


/*
 * 
 * To write data to simulated memory address only if the address is within 
 * the range.
 * 
 */
 int memw(int write_addr,int data) 
 {
  if(write_addr < 0x2000 || write_addr >= 0x2c00)  return(-1);
  memory_buffer[write_addr - 0x2000] = data;
  return(0);
 }


/*
 * 
 * Reads data at address pointed by "hl" pair
 * 
 */
 int mhlr(void)
 {
  return memr(reg[4] * 0x100 + reg[5]);
 }


/*
 * 
 * Writes data at address pointed by "hl" pair
 * 
 */
 int mhlw(int data)
 {
  memw(reg[4] * 0x100 + reg[5], data);
  return(0);
 }


/*
 * 
 * Pushs  given word on to the stack and decrements the stack pointer 
 * accordingly by two bytes.
 */
 int push_word(int word)
 {
  memw(rsp - 1,  word / 0x100);
  memw(rsp - 2,  word % 0x100);
  rsp -= 2;
  return(0);
 }


/*
 * 
 * Pops word on from the stack and increments the stack pointer 
 * accordingly by two bytes.
 * 
 */
 int pop_word(void)
 {
  int ms,md;
  ms = memr(rsp);
  rsp++;
  md = memr(rsp);
  rsp++;
  return( md * 0x100 + ms );
 }



/*
 * 
 * Checks whether address is within the range or not.
 *
 * return 1 if address is within the range else returns 0.
 * 
 */
 int check(int addr)
 {
  return (addr >= 0x2000 && addr <= 0x2d00);
 }

