'******************************************************************************
'* 
'* SPECTRUM-48K MOTHERBOARD v.1.0 (MOTHERBOARD DEVICE)
'*
'* Supported platform/bus: Spectrum
'*
'* Version history:
'*  - v.0.1 by WadiM (initial emulation)
'*
'****************************************************************************** 

//DEBUG.ON 'uncomment to enable debug messages (can be slow for hi-freq events)

//parent DEVSET implementation
public use object DEVSET

//motherboard name
DeviceName="Spectrum-48K Motherboard"
DebugName="SPEC48_MB"

//variables
dim i as integer

'--------------------------------- Chipset ------------------------------------

//Video
public use object VID_SPECTRUM as ULA : AddDevice(ULA)
for i=0x4000/1024 to 0x5AFF/1024 //video memory
 mem.KBReader(i)=ULA.ReadMemory : mem.KBWriter(i)=ULA.WriteMemory 
next

//Keyboard
public use object KBC_SPECTRUM as KBC : AddDevice(KBC)
pc.HandleKey=KBC.HandleKey
for i=0 to 0xFFFE step 2 //one handler for all even ports
 pc.ReadPort(i)=KBC.PORTS 
next

'------------------------------ IRQ Emulation ---------------------------------

//IRQs counter 
dim IRQCount as byte=0

//Set IRQ
public function SetIRQ(Index as integer, State as boolean) as boolean
 //?? DebugPrefix;"SetIRQ(";Hex(Index,2);"h, ";State;")"
 if IRQCount<255 then IRQCount=IRQCount+1
end

//Get IRQ
public function GetIRQ(Process as boolean,byref Address as dword) as integer
 if IRQCount>0 then
    result=0 : Address=0xFF : if Process then IRQCount=IRQCount-1
 else : result=-1 : end if
 //?? DebugPrefix;"GetIRQ(";Process;")=";result
end

//Configure IRQs
pc.SetIRQ=SetIRQ : pc.GetIRQ=GetIRQ

'---------------------------- DEVICE Interface --------------------------------

//Device initialization
protected function DEV_INIT(stream as object,byref EventFreq as integer) as boolean
 dim i as integer
  
 'parent call
 if not DEV_INIT(stream,EventFreq) then exit(false)

 'load ROM BIOS file 
 mem.Bytes(0)=ArrayFile("bin\zx48.rom")  'main BIOS

 'mark first 16K of memory area as read-only (ROM)
 for i=0 to 15 : mem.KBAccess(i)=memReadOnly : next
 'mark next 48K of memory area as read-write (RAM)
 for i=16 to 63 : mem.KBAccess(i)=memReadWrite : next

 'success 
 result=true
end
