/*  TilEm, TI-Linux Emulator
 *  Copyright (C) 2001 Solignac Julien <x1cygnus@xcalc.org>
 *  Portions copyright (C) 2004 Benjamin Moody <benjamin@ecg.mit.edu>
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#define FLASH_READ 0
#define FLASH_AA   1
#define FLASH_55   2
#define FLASH_PROG 3
#define FLASH_ERASE 4
#define FLASH_ERAA 5
#define FLASH_ER55 6

/* Autoselect mode is not implemented.
 * Status bits are not implemented (all operations occur within one
 * clock cycle)
 * Erase suspend is not implemented (there's no chance for it to
 * happen anyway.)
 */

struct sect {long start, size; byte s;};

struct sect x7_sectors[]={{0x000000, 0x10000, 1},
			  {0x010000, 0x10000, 1},
			  {0x020000, 0x10000, 1},
			  {0x030000, 0x10000, 1},
			  {0x040000, 0x10000, 1},
			  {0x050000, 0x10000, 1},
			  {0x060000, 0x10000, 1},
			  {0x070000, 0x08000, 1},
			  {0x078000, 0x02000, 1},
			  {0x07A000, 0x02000, 1},
			  {0x07C000, 0x04000, 3},
			  {0, 0, 0}};


void xp_flash_write(byte *mem, unsigned long pa, byte v, byte lastpage,
		    struct sect* secs);


void x7_Z80_WRMEM(dword A, byte v)
{
  unsigned long pa;

  pa = (A & 0x3FFF) + 0x4000*pager[(A)>>14];

  if (pa<0x80000)
    xp_flash_write(mpages,pa,v,0x1F,x7_sectors);

  else if (pa < 0x88000)
    *(mpages+pa) = v;
}


unsigned x7_Z80_RDMEM(dword A)
{
  extern Z80_Regs R;
  byte page;

  A &= 0xFFFF;
  page = pager[A>>14];
  
  if (page == 0x1E) {
    if (flashlock) {
      /* Bitmask for apps, starting with bit 1, 0 = Enabled, 1 = Disabled ;) */
      if ((A & 0x1FFF) == 0x1FE0 || (A & 0x1FFF) == 0x1FE1)
	return(0x00);
    }
    else {
      printf("** reading from read-protected sector **\n");
      return 0xff;
    }
  }

  return(*(mpages + 0x4000 * page + (A & 0x3FFF)));
}
