Set DEST "{1}"
Set DEST_X "{TempFolder}LinkedPowerROM.x"
Shift

Echo "Hello from LinkPowerROM, the 21st-century PowerMac ROM linker"
Echo "DEST = {DEST}"

Set CTOOL "{0}".tool
Echo "Assuming that {CTOOL} is compiled"

Set CurOffset 0					# contains a decimal number throughout
Set LinkList ""					# contains space-separated quoted xcoff filenames
Set CksumOffset 0x30d000		# a good default

Echo "{#} arguments..."

Loop
	If !{#}
		Break
	End

	Echo ------------------------------
	Echo "ARG '{1}'"

	If "{1}" =~ /[0-9]+/ || "{1}" =~ /0x[0-9a-f]+/
		Echo "Move to offset."
		Set NewOffset `Evaluate "{1}"`

		If {NewOffset} ¶< {CurOffset}
			Echo "{0} failed: cannot pad to offset {NewOffset} because we are already past it!" >> Dev:Stderr
			Exit 1
		Else If {NewOffset} ¶> {CurOffset}
			Set Delta `Evaluate {NewOffset} - {CurOffset}`

			Set F "Zeros_{Delta}.s"
			Echo "Create {F}"
			Set F "{TempFolder}{F}"
			Echo "    DCB.B {Delta}, 0" > "{F}"
			PPCAsm "{F}"
			Set LinkList "{LinkList} '{F}.o'"

			Set CurOffset {NewOffset}
		End

	Else If "{1}" =~ /([A-Za-z0-9]+)¨1:/
		Echo "Insert label for linker."
		Set Label {¨1}

		Set F "{TempFolder}Label_{Label}.s"
		Echo "    EXPORT {Label}" > "{F}"
		Echo "{Label}:" >> "{F}"
		PPCAsm "{F}"
		Set LinkList "{LinkList} '{F}.o'"

	Else If "{1}" == CHECKSUM
		Echo "Put the ConfigInfo checksum here."

		Set CksumOffset {CurOffset}

	Else
		Echo "Link this file."
		Set F "{1}"

		# Convert to an xcoff if necessary
		If "{F}" !~ /Å.x/
			Echo "Converting to xcoff first."
			Set NewPath "`Echo {F} | StreamEdit -d -e '/(Å:)*([Â:]*)¨1/ print ¨1'`.x"
			Echo "Temporary file {NewPath}"
			Set NewPath "{TempFolder}{NewPath}"
			"{CTOOL}" tox "{F}" "{NewPath}"
			Set F "{NewPath}"
		End

		Set LinkList "{LinkList} '{F}'"

		Set TextLen `DumpXCOFF -do h "{F}" | StreamEdit -d -e '/s_nameÅ¶".(Å)¨1¶"/ Set CurSec ¨1' -e '/s_sizeÅ¶((Å)¨1¶)/ Print CurSec " " ¨1' | StreamEdit -d -e '/text (Å)¨1/ Print ¨1'`
		Echo -n "File size = "; Evaluate -h {TextLen}
		Set CurOffset `Evaluate {CurOffset} + {TextLen}`
	End

	Echo -n "CurOffset = "; Evaluate -h {CurOffset}

	Shift
End

Echo ------------------------------

Echo "Running PPCLink..."
PPCLink -xm library -codestart 0 -warn -o "{DEST_X}" {LinkList}

Echo "Dumping temp xcoff to DEST..."
"{CTOOL}" fromx "{DEST_X}" "{DEST}"

Echo "Checksumming DEST..."
"{CTOOL}" cksum "{DEST}" {CksumOffset}

Echo "All done."
