// doc.sr


get "BRAVO1.DF";
get "HEAP.DF";
get "MSG.DF";
get "doc.DF";
get "vm.DF";
get "RN1.DF";

// Incoming Procedures

external [
	movec;
	errhlta;
	ugt;
	ult;
	hpalloca;
	insertlp;
	cpadjust;
	enww;
	invalidatewindow;
	hpfree;
	cpfc;
	msgtomi;
	SetPcMax
	setlp;
	MapRi
	mapfc
	insertd
	];

// Incoming Statics

external [
	ckproc;
	vpzone;
	ckperr;
	rgcfn;
	vrlfsys;
	vbifr;
	];

// Outgoing Procedures

external [
	ckdoc;
	createdoce;
	createdocm;
	docalloc;
	deleted;
	invalidatedoc;
	];

// Outgoing Statics

external [
	rgpctb;
	rgmaccp;
	ppcd;
	vpc;
	vcp;
	macdoc;
	]; 

// Local Statics

static [
	rgpctb;
	rgmaccp;
	ppcd;
	vpc;
	vcp;
	macdoc;
	];

// C K D O C
// catalogue no. = 89
let ckdoc( ) be
[ ckproc = "ckdoc";
movec(rgcfn,rgcfn+maxfn-1,0);
let hpmax = vpzone >> ZONE.max;
let hpmin = vpzone >> ZONE.min;
for doc = 0 to maxdoc-1 do
	[ let tpctb = rgpctb ! doc;
	if tpctb eq -1 then loop;
	let macpc = tpctb >> PCTB.macpc;
	let  mppccp = lv (tpctb >> PCTB.rvmppccp);
	for i = 1 to macpc do
		[ unless ugt(mppccp ! i,mppccp ! (i-1)) do 
			[ ckperr = mppccp+i;
			errhlta(166);
			] 
		] 
	if mppccp ! macpc ne rgmaccp ! doc do 
		[ ckperr = mppccp+macpc;
		errhlta(167);
		] 
// check piece descriptors
	let rgpcd = tpctb+tpctb >> PCTB.rgpcd;
	for i = 0 to (macpc-1) do
		[ 
		let j = i lshift 2;
		ckperr = rgpcd+j;
		let addr = ckperr >> PCD.vpa;
		let fn = addr << VPA.fn;
		test ckperr >> PCD.live ifso 
			 if fn ge maxlp then
				errhlta(168)
		ifnot	[ 
			if fn ge maxfn do
				errhlta(168);
			rgcfn ! fn = rgcfn ! fn+1;
			] 
		] 
	] 
] 

// C R E A T E D O C E 
// catalogue no. = SPE-99
and createdoce(doc,maxpc) be
[ 
let pctb = hpalloca(maxpc*5+1+pctbovhd);
rgpctb ! doc = pctb;
rgmaccp ! doc = 0;
pctb >> PCTB.maxpc = maxpc;
pctb >> PCTB.macpc = 0;
pctb >> PCTB.rgpcd = (offset PCTB.rvmppccp)/16+maxpc+1;
pctb >> PCTB.rvmppccp = 0;
] 

// C R E A T E D O C M
//
and createdocm(doc) be
[
createdoce(doc, 1);
let fn = nil;
let fc = nil;
let dfc = nil
MapRi(vrlfsys, riEndOfDoc, lv fn, lv fc, lv dfc)
mapfc(fn, fc)
insertd(doc, 0, dfc, fn, fc, vbifr)
]

// D O C A L L O C
// catalogue no. = 127
and docalloc( ) = valof
[ for doc = 0 to maxdoc-1 do
	if rgpctb ! doc eq -1 then resultis doc;
resultis -1;
] 

// D E L E T E D
// SPE catalogue no.

and deleted(doc) be
[
cpadjust(doc,0,-(rgmaccp ! doc));
rgmaccp ! doc = 0;
let pctb = rgpctb ! doc;
pctb >> PCTB.macpc = 0;
pctb >> PCTB.rvmppccp = 0;
SetPcMax(doc,deltamaxpc)
]

// I N V A L I D A T E D O C
//
and invalidatedoc(doc) be
	enww(invalidatewindow,doc);