// Program to decide whether a file that's been received is a
// PD file or a Press file, and invoke PDPrint or Press accordingly.
// Format of command line:
// Decide/switches filename
// Switches are passed on to PDPrint or Press
// First looks on Trident (drive 0, file system 0), and if not, on
// local disk.

// Bldr decide gp (tfs stuff)

get "streams.d"

external [
//TFS
	TFSInit
//GP
	SetupReadParam
	ReadParam
//Loadram
	LoadRam
	SetBLV
	RamImage
//OS
	OpenFile
	Closes
	Resets
	Gets
	Puts
	FileLength
	SetFilePos
	TruncateDiskStream
	DoubleAdd
	InitializeZone
	fpComCm
	StartIO
	Wss
	Ws
	CallSwat
	CallSubsys
	lvUserFinishProc
	AltoVersion
	MoveBlock
	]
static SavedUFP
static UseRam

let main() be
[
	let z=vec 3000
	let zone=InitializeZone(z, 3000)
	let trident=0
//Very first thing to do is load the RAM:
	UseRam=(AltoVersion rshift 12) le 3
	if UseRam then
		[
		let errs=LoadRam(RamImage, true)
		SetBLV(#177776)	//Prepare for a silent boot when finishing.
		SavedUFP=@lvUserFinishProc
		@lvUserFinishProc=UserFinishProc //Will boot to restore tasks to ROM
		trident=TFSInit(zone, false, 0)
		]

	let stringvec = vec 20
	let switchvec = vec 20
	let filename=vec 20
	let cs = OpenFile("com.cm", ksTypeReadWrite, charItem, 0, fpComCm)
	SetupReadParam(stringvec, switchvec, cs, 0)
	let globalswitchvec=vec 20
	MoveBlock(globalswitchvec, switchvec, 20)

	ReadParam($P, 0, filename, 0)

	let s=0
	if trident then
		s=OpenFile(filename, ksTypeReadOnly, 0,0,0,0, zone, 0, trident)
	if s eq 0 then s=OpenFile(filename, ksTypeReadOnly, wordItem)
	if s eq 0 then
		[
		Ws("Cannot find the file.")
		finish
		]

	let w1=Gets(s)		//First word
	let w2=0			//Press password
	let fl=vec 1
	FileLength(s, fl)
	if ((fl!1)&#777) eq 0 then
		[
		let recLen= table [ -1; -512 ]
		DoubleAdd(fl, recLen)
		SetFilePos(s, fl)
		w2=Gets(s)
		]
	Closes(s)
	UserFinishProc()		//Stop Trident, silent boot

	Resets(cs)
	let program=nil
	let typ=0
	if w1 eq #125252 then typ=typ+1
	if w2 eq 27183 then typ=typ+2
	switchon typ into
		[
		case 0: Ws("File is neither .press nor .pd."); finish
		case 1: program="Pdprint.run"; endcase
		case 2: program="Press.run"; endcase
		case 3: Ws("File type is ambiguous."); finish
		]

	Wss(cs, program)
	if globalswitchvec!0 ne 0 then
		[
		Puts(cs,$/)
		for i=1 to globalswitchvec!0 do Puts(cs, globalswitchvec!i)
		]
	Wss(cs, " print ")
	Wss(cs, filename)
	TruncateDiskStream(cs)
	Closes(cs)

	cs=OpenFile(program, ksTypeReadOnly, wordItem)
	if cs eq 0 then CallSwat("File not found", program)
	CallSubsys(cs)
]

and UserFinishProc() be if UseRam then
[
	StartIO(#100000)	//silent boot to stop trident
	@lvUserFinishProc=SavedUFP
]