/*
  Mem
*/

#include "mem.h"

#include "page.h"

/*
  Pointers into workspace
  May not assume that pages are contigous in memory or remain
  across calls to this routine ... allows swapping out of modified
  pages on small machines.
*/

static byte *ptr_from_addr(long_word addr)
{
  word page = pg_page(addr);
  word off  = pg_offset(addr);
  return ptr_from_seg(page, off);
}


byte rd_byte_addr(long_word addr)
{
  return *ptr_from_addr(addr);
}

/* Word reads */

word rd_word_ptr(byte *p)
{
  return make_word(p[0], p[1]);
}

word rd_word_seg(word page, word off)
{
  byte hi = rd_byte_seg(page, off);
  byte lo = off + 1 == BLOCK_SIZE
    ? rd_byte_seg(page + 1, 0)
    : rd_byte_seg(page, off + 1);
  return make_word(hi, lo);
}

word rd_word_addr(long_word addr)
{
  return rd_word_seg(pg_page(addr), pg_offset(addr));
}

/* Byte writes */

void wr_byte_addr(long_word addr, byte value)
{
  *ptr_from_addr(addr) = value;
}

/* Word writes */

void wr_word_ptr(byte *p, word value)
{
  p[0] = value >> 8;
  p[1] = value;
}

void wr_word_addr(long_word addr, word value)
{
  wr_byte_addr(addr, value >> 8);
  wr_byte_addr(addr+1, value);
}
