//
// Print micro-PC histogram
// last edited December 5, 1980  12:31 PM
//

//	>pcprint (input file) (.MB file) (output file)
// Local flags on input file:
//	input/l means input is in Lisp format
//	bank,addr/a means input is in XM

	get "streams.d"
	get "altodefs.d"	// for bankRegs

external
[		// OS
	Closes
	DoubleAdd
	Endofs
	MoveBlock
	OpenFile
	ReadBlock
	dsp
	fpComCm
		// GP
	SetupReadParam; ReadParam; EvalParam
		// Template
	PutTemplate
		// PCHist
	ReadLispPCHist
	ScanMBForPCHist
	PrintPCHist
]


manifest
[	lHist = 10000b
]


let PCPrint(nil, nil, nil) be
[	let com = OpenFile(0, ksTypeReadOnly, charItem, 0, fpComCm)
	let nv, swv = vec 100, vec 100
	SetupReadParam(nv, swv, com, swv)
	let dnv = vec 100
	let mnv = vec 100
	let lispf = false
	let hist = vec lHist*2
	let xaddr = vec 2
	xaddr!0 = -1
	ReadParam($P, "Data input: ", dnv)
	switchon (swv!0 eq 0? 0, swv!1 & 137b) into
	[ case $A:
	    getAddr(nv, xaddr)
	    getXMHist(xaddr, hist)
	    dnv!0 = 0
	    endcase
	  case $L:
	    lispf = true
	  default:
	]
	ReadParam($P, ".MB file: ", mnv)
	let lst = ReadParam($O, "Listing output file: ")
	let in = nil
	if dnv!0 ne 0 then
	[ [ in = OpenFile(dnv, ksTypeReadOnly, wordItem)
	    if in ne 0 then
	    [ let r = 0
	      test lispf
	       ifso r = ReadLispPCHist(in, hist)
	       ifnot
	      [ if (ReadBlock(in, hist, lHist*2) ne (lHist*2)) % not Endofs(in) then
	          r = "Incorrect file length" 
	      ]
	      Closes(in)
	      if r eq 0 break
	      PutTemplate(dsp, "$S*N", r)
	    ]
	    ReadParam($P, "Data input file: ", dnv)
	  ] repeat
	]
	[ in = OpenFile(mnv, ksTypeReadOnly, wordItem)
	  if in ne 0 then
	  [ let r = ScanMBForPCHist(in)
	    Closes(in)
	    if r eq 0 break
	    PutTemplate(dsp, "$S*N", r)
	  ]
	  ReadParam($P, ".MB file: ", mnv)
	] repeat
	Closes(com)
	PutTemplate(lst, "Data from $S / $S*N*N", (dnv!0 eq 0? "XM", dnv), mnv)
	PrintPCHist(lst, hist)
	Closes(lst)
]

and fail(str) be
[	PutTemplate(dsp, "*N$S*N", str)
	finish
]

and getAddr(argvec, xaddr) be
[	let dgt = vec 2
	dgt!0 = 0
	xaddr!0, xaddr!1 = 0, 0
	let xbank = 0
	for i = 1 to argvec!0 do
	[ test argvec!i eq $,
	   ifso [ xbank = xaddr!1; xaddr!1 = 0 ]
	   ifnot
	  [ xaddr!0 = (xaddr!0 lshift 3) + (xaddr!1 rshift 13)
	    xaddr!1 = xaddr!1 lshift 3
	    dgt!1 = argvec!i-$0
	    DoubleAdd(xaddr, dgt)
	  ]
	]
	xaddr!0 = xaddr!0 + xbank
]

and getXMHist(xaddr, hist) be
[	if xaddr!0 eq -1 then fail("No XM address specified")
	let XMLDA = table[
	  105000b	// mov 0 1
	   61025b	// xmlda
	    1401b	// jmp 1,3
	 ]
	@bankRegs = xaddr!0
	let addr = xaddr!1
	for i = 0 to lHist*2-1 do
	  hist!i = XMLDA(addr+i)
]