/*
 * copy.ftw - support routine for files.ftw. It copies the minimal subtree
 * that includes it's arguments to directory found in the tw.copyname clip.
 *
 * Note: will copy directories if you ask it to. This is probably not what
 * you want, so it's best not to ask it.
 */
address command

directory = arg(1)
file = arg(2)
root = twpath()
dest = getclip("tw.copyname")

/* patch up the copy name, if we need to */
if index(":/", right(dest, 1)) = 0 then do
	if index(dest, ":") ~= 0 then dest = dest'/'
	else dest = dest':'
	call setclip 'tw.copyname', dest
	end

/* Verify that we've got a good path */
if index(directory, root) ~= 1 then return 1

outname = dest || substr(directory, length(root) + 1) || file
inname = directory || file

/* Walk up outname until we find a directory that really exists */
outdex = lastpos('/', outname)
do while outdex > 0
	outdir = substr(outname, 1, outdex - 1)
	if exists(outdir) then break
	outdex = lastpos('/', outname, outdex - 1)
	end
outdex = index(outname, '/', outdex + 1)

/* Now, walk back down what's left creating directories */
do while outdex > 0
	outdir = substr(outname, 1, outdex - 1)
	'makedir' outdir
	outdex = index(outname, '/', outdex + 1)
	end

'copy' inname 'to' outname
return 1
