// buffer.sr
// Carol Hankins
// April 26, 2976

get "bravo1.df"
get "com.df"
get "rn1.df"
get "display.df"
get "doc.df"

//incoming procedures
external
	[
	MapRi
	SetRegionA
	SetRegionB
	updatewindow
	binsearcha
	ugt
	]

//incoming statics
external
	[
	vrldsys
	rgpctb
	doctxcurrent
	]

//outgoing procedures
external
	[
	ClearBuf
	InsertBuf
	MakeCurrentBuf
	BufToRi
	]

//outgoing statics

//local manifests
manifest
	[
	chMax = 16
	chPerSide = chMax/2
	bufConst = 6
	]

let InsertBuf(bufno,docinsert,cpinsert,dcpinsert) be
[

let tpcfirst,tpclast = nil,nil
let tfn,tcp,tdcp = nil,nil,nil
let pctb,mppccp = nil,nil
let rino,cpstart = nil,nil
let trgrid = vec 1

rino = BufToRi(bufno)

test ugt(dcpinsert,chMax)  ifso
	[
	SetRegionB(vrldsys,rino,docinsert,cpinsert,chPerSide)
	trgrid!0 = 27;					//...
	SetRegionA(vrldsys,rino+1,1,trgrid)
	cpstart = cpinsert + dcpinsert - chPerSide
	SetRegionB(vrldsys,rino+2,docinsert,cpstart,chPerSide)
	]
ifnot	[
	ClearBuf(bufno)
	SetRegionB(vrldsys,rino,docinsert,cpinsert,dcpinsert)
	]

pctb = rgpctb!docsys
mppccp = lv (pctb>>PCTB.rvmppccp)
MapRi(vrldsys,rino,lv tfn, lv tcp,lv tdcp)
tpcfirst = binsearcha(mppccp,pctb>>PCTB.macpc,tcp)
MapRi(vrldsys,rino+2,lv tfn,lv tcp,lv tdcp)
tpclast = binsearcha(mppccp,pctb>>PCTB.macpc,tcp+tdcp) - 1

for tpc = tpcfirst to tpclast do
	[
	let pcd = pctb + pctb>>PCTB.rgpcd + tpc lshift 2
	pcd>>PCD.visibuf = true
	]
]


and ClearBuf(bufno) be
[

let rino = BufToRi(bufno)

for i = 0 to 2 do
	SetRegionA(vrldsys,rino+i,0,0)

]


and MakeCurrentBuf(bufno) be
[

let rino = BufToRi(bufno) - 2
let trgrid = vec 1

if bufno eq doctxcurrent then return
if doctxcurrent then
	[		// clear current "current buffer"
	trgrid ! 0 = 30
	SetRegionA(vrldsys,doctxcurrent*bufConst,1,trgrid)
	]
trgrid!0 = 31;	SetRegionA(vrldsys,rino,1,trgrid)
doctxcurrent = bufno

updatewindow(wwsys)

]


// B U F T O R I
// gives region number of first region of buffer.
// bracket is ri-1, space is ri-2
and BufToRi(bufno) = bufno*bufConst+2