// GDOC.SR clean docs

get "BRAVO.DF";
get "HEAP.DF";
// Incoming Procedures

external [
	movec;
	errck;
	ugt;
	ult;
	hpalloca;
	insertlf;
	setlf;
	errhlt;
	confirm;
	stcopy;
	cpadjust;
	enww;
	invalidatewindow;
	hpfree;
	enpspecs // **
	freespec // **
	createdocp // **
	];

// Incoming Statics

external [
	ckproc;
	vpzone;
	ckperr;
	macww;
	rgdoc;
	sbpast;
	dnlf;
	rgcfn;
	rgdirty // **
	rgsdoc
	rgpara
	rgsfile
	];

// Outgoing Procedures

external [
	ckdoc;
	createdoce;
	createdocm;
	docalloc;
// **	docunused;
	deleted;
	invalidatedoc;
	];

// Outgoing Statics

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

// Local Statics

static [
	rgpctb;
	rgmaccp;
	vpc;
	vcp;
	ppcd;
	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  rgcp = lv (tpctb >> PCTB.rgcp);
	for i = 1 to (macpc) do
		[ if ult(rgcp ! i, rgcp ! (i-1)) do 
			[ ckperr = rgcp+i;
			errck("pc");
			] 
		] 
	if rgcp ! macpc ne rgmaccp ! doc do 
		[ ckperr = rgcp+macpc;
		errck("ds");
		] 
// check piece descriptors
	let rgpcd = rgcp+(tpctb >> PCTB.maxpc)+1;
	for i = 0 to (macpc-1) lshift 1 by 2 do
		[ 
		ckperr = rgpcd+i;
		let addr = ckperr >> PCD.vpaddr;
		test ckperr >> PCD.live ifso 
			 if ugt(addr,hpmax) % ult(addr,hpmin) do
				errck("lp");
			 
		ifnot	[ 
			let fn = addr << VPA.fn;
			if fn ge maxfn do
				errck("fne");
			rgcfn ! fn = rgcfn ! fn+1;
			] 
		] 
	] 
] 
// C R E A T E D O C E 
// catalogue no. = SPE-99
and createdoce(doc,maxpc) be
[ 
rgpctb ! doc = hpalloca(maxpc*3+1+pctbl);
rgmaccp ! doc = 0;
(rgpctb ! doc) >> PCTB.maxpc = maxpc;
(rgpctb ! doc) >> PCTB.macpc = 0;
(rgpctb ! doc) >> PCTB.rgcp = 0;
createdocp(doc) // **
] 

// C R E A T E D O C M
//
and createdocm(doc) be
[
createdoce(doc,1);
// ** insertlf(doc,0,lfedoc,doc,4);
// **setlf(lfedoc,doc," *201"); // **
rgdirty ! doc = false	// **
]

// 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 O C U N S E D 
//
// ** GYPSY USES wipedoc IN GPARA.SR INSTEAD

// 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.rgcp = 0;
]
// I N V A L I D A T E D O C
//
and invalidatedoc(doc) be
	enww(invalidatewindow,doc);