// SplitFileName -- directory stuff
// Copyright Xerox Corporation 1979

// E. McCreight
// last modified October 4, 1976  5:20 PM
// cribbed liberally from "ParseFileName" in the OS

// incoming procedures
external [
	Zero
	]

//  outgoing procedures
external [
	SplitFileName
	]

structure STRING:
	[ length byte
	char↑1,255 byte
	]


let SplitFileName(n, dn, fn)=valof
	[
// parses n into dn and fn, appending a $. if necessary.

	let L=n>>STRING.length; let fnBase=1; let dnBase=1
	let lastRealChar=0; let dnEnd=0

	for i=1 to L do
		switchon n>>STRING.char↑i into
			[
			case $>:
				if i-1 eq lastRealChar then
					dnEnd=i-1
				fnBase=i+1
				endcase
			case $<:
				dnBase=i+1
				endcase
			default:
				lastRealChar = i
			]

	ExtractLegalFileName(n, dnBase, dnEnd, dn)
	ExtractLegalFileName(n, fnBase, L, fn)
	]


and ExtractLegalFileName(S, first, last, fn) be

	[ let L = last-first+1
	if L ls 0 then L=0
	Zero(fn, (L+3) rshift 1)

	let c = nil
	for i=1 to L do
		[ c = S>>STRING.char↑(first+i-1)
		switchon c into
			[ case $A to $Z:
			case $a to $z:
			case $0 to $9:
			case $-: case $$: case $!: case $?: case $+:
			 case $.: case $>: case $<:
				endcase

			default: c=$-
			]
		fn>>STRING.char↑i = c
		]

	if (L gr 0) & (c ne $.) then
		[ L=L+1 ; fn>>STRING.char↑L=$. ]
	fn>>STRING.length=L
	]