#!/bin/csh -fx

echo $#argv

if (! -d $argv[$#argv]) then
	if ($#argv != 2) then 
		echo -n "Usage: mv f1 f2 or mv f1 ... fn d1 " > /dev/tty
		echo "(<fn> is a file or directory)" > /dev/tty
		exit 1

	endif
endif

#
#	mv file1 file2, where file1 and file2 are plain files
#	N.B. If the last file is a plain file we know there are only two
#	from the above
#
if (-f $argv[$#argv]) then 	
	/bin/mv $argv[1] $argv[2]
	exit $status
endif


#
#	destination is a directory and it already exists. If we're moving
#	a plain file we can simply use /bin/mv. If we're moving a directory
#	we need to tar it. We generate an absolute path name for the 
#	destination directory so we don't get lost when we're moving
#	around.
#
set destdir = `pwd`/$argv[$#argv]
while ($#argv > 1)
        switch ($argv[1])

	case -*:
		echo -n "Usage: mv f1 f2 or mv f1 ... fn d1 " > /dev/tty
		echo "(<fn> is a file or directory)" > /dev/tty
		exit 1
		breaksw
	default:
		if (-f $argv[1]) then
			/bin/mv $argv[1] $destdir
			if ($status != 0) then
				exit $status
			endif
		else
			set pushed = 0
			if ("$argv[1]:t" != "$argv[1]") then
				pushd $argv[1]:t
				set pushed = 1
			endif
			set dir = $argv[1]:h
			tar -cf - $dir | (cd $destdir; tar -xBf -);
			if ($status != 0) then
				exit $status
			endif
			/bin/rm -r $dir
			if ($status != 0) then
				exit $status
			endif

			if ($pushed) then
				popd
			endif
			
		endif
	endsw
	shift
end

