'*****************************************************************************
'* INT 10H AH=05h (CGA BIOS) SET ACTIVE VIDEO PAGE
'* Params: AL - page/screen index
'*****************************************************************************

use module "Tools" 'cga tools

protected function Exec as boolean

//variables
dim page as byte, port as word, pos as word, buf_size as word
dim row as byte, col as byte, rows as word, cols as word
page=cpu.AL

//max 8 pages allowed (0-7)
if page>=8 then : result=false : exit : end

//calc pos (offset) from vram start
buf_size=mem.Word(0x44C) //size of page memory buffer
pos=page*buf_size 
if pos>(0x4000-buf_size) then exit //no more 16Kb then of VRAM

//write to memory
mem.Byte(0x462)=page : mem.Word(0x44E)=pos

//write to controller
Port=mem.Word(0x463) //controller port
pc.WritePort(Port,0xC) : pc.WritePort(Port+1,shr(pos,8))
pc.WritePort(Port,0xD) : pc.WritePort(Port+1,pos and 0xFF)

//cursor pos (read from memory and write to controller)
pos=mem.Word(0x450+page*2) : col=pos and 0xFF : row=shr(pos,8)
SetCursorPos(page,row,col)
{cols=mem.Word(0x44A) : rows=25 
pos=(page*rows+row)*cols+col //symbols from video memory start
pc.WritePort(Port,0xE) : pc.WritePort(Port+1,shr(pos,8))
pc.WritePort(Port,0xF) : pc.WritePort(Port+1,pos and 0xFF)}

//success
result=true : end