#!/usr/bin/perl -w

$sep = '/';
$cwd = "/";
prompt();

clparse: while($_ = <>)
{
if($_ =~ /^\s*ls\s*$/)
	{
	while($files = <$cwd/*>)
		{
		$files =~ s/^.*$sep//;
		print $files . "\n";
		}
	prompt();
	next clparse;
	}
if($_ =~ /^\s*cd\s+\"(.*)\"\s*$/)
			# ls with quotes, needed to tag dirs with spaces in them
	{
	my $targetdir = $1;
	mycd($targetdir);
	prompt();
	next clparse;
	}
if($_ =~ /^\s*cd\s+(\S*)\s*$/)
	{
        my $targetdir = $1;
	mycd($targetdir);
        prompt();
        next clparse;
	}
if($_ =~ /^\s*$/)
	{
	prompt();
	next clparse;
	}
if($_ =~ /^\s*pwd\s*$/)
	{
	print("$cwd\n");
	prompt();
	next clparse;
	}
if($_ =~ /^\s*exit\s*$/)
	{
	print "\n";
	exit(0);
	}
if($_ =~ /^\s*touch\s+\"(.*)\"/)
	{
	my $ftt = $1;
	mytouch($ftt);
	prompt();
	next clparse;
	}
if($_ =~ /^\s*rm\s+\"(.*)\"/)
	{
	my $ftrm = $1;
	myrm($ftrm);
	prompt();
	next clparse;
	}
if($_ =~ /^\s*cat\s+\"(.*)\"/)
	{
	my $ftcat = $1;
	mycat($ftcat);
	prompt();
	next clparse;
	}
if($_ =~ /^\s*help/)
	{
	myhelp();
	prompt();
	next clparse;
	}
			# Inset new commands here!!

print "Unknown command\n";
prompt();
}
print "\n";
exit(0);

sub mycd
{
$targetdir = shift(@_);
return if(($targetdir eq '..' ) && ($cwd eq '/'));
$tcwd = $cwd;
if($targetdir =~ m[^/])
	{
	$tcwd = "";
	}
$tcwd = $tcwd . $sep . $targetdir;
while($tcwd =~ s[/./][/]){}
while($tcwd =~ s[/.$][/]){}

$dblsep = $sep . $sep;
$tcwd =~ s[$dblsep][$sep]g;
$tcwd =~ s/$sep$//;
while($tcwd =~ /\.\./ )
	{
	last if(! ($tcwd =~ s[/[^/]+/\.\.][]g)); 
	}
if($tcwd =~ /^\s*$/) {$tcwd = "/";}
if(! -d ($tcwd) )
	{
	print "$tcwd : No such file or directory\n";
	prompt();
	next clparse;
	}
$cwd = $tcwd;
}

sub prompt
{
print "[$cwd] \$ ";
}

sub mytouch
{
my $ftt = pop(@_);
chomp($ftt);
my $fto = $cwd . '/' . $ftt;
if($cwd eq '/'){$fto = $cwd . $ftt;}
if($ftt =~ m[^/]) {$fto = $ftt;}
open(F,">$fto") || print "Couldn't open file [$fto]\n";
close(F);
}

sub myrm
{
my $ftt = pop(@_);
chomp($ftt);
my $fto = $cwd . '/' . $ftt;
if($cwd eq '/'){$fto = $cwd . $ftt;}
if($ftt =~ m[^/]) {$fto = $ftt;}
unlink($fto) || print "Couldn't remove file [$fto]\n";
close(F);
}

sub mycat
{
my $ftcat = pop(@_);
chomp($ftcat);
my $ftcr = $cwd . '/' . $ftcat;
if($cwd eq '/'){$ftcr = $cwd . $ftcat;}
if($ftcat =~ m[^/]) {$ftcr = $ftcat;}
if(! open(FCAT,"$ftcr") ) {print "Couldn't open file [ $ftcr ] \n"; sleep 1; return;}
my $line;
while($line = <FCAT>)
	{
	chomp($line);
	print $line . "\n";
	}
close(FCAT);
}

sub myhelp
{
print <<END;
Commands supported:
cat
cd
exit
ls
pwd
rm
touch
END
}
