#!/afs/athena/contrib/perl/perl

sub recurse_path
{
    local ($pwd, $rest) = @_;
    print "pwd = $pwd\nrest = $rest\n";
    ($next, $rest) = split ('/', $rest, 2);
    print "next = $next\nrest = $rest\n";
   
    if ($next eq ".")
    {
	&recurse_path ($pwd, $rest);
    }
    else
    {
	print "good\n";
	if ($next eq "..")
	{
	    print "no way\n";
	    local ($offset) = rindex ($pwd, '/');
	    $pwd = substr ($pwd, 0, $offset);
	    $pwd = "/" if ! $pwd;
	    chdir ".." || die "$!";
	}
	else
	{
	    if (-l $next)
	    {
		print "reading link...\n";
		local ($lpath) = readlink ($next);
		print "link is $lpath\n";
		defined ($lpath) || die "$lpath: $!";
		$lpath =~ s!/+!/!g;
		$lpath eq "/" || $lpath =~ s!/+$!!;
		if ($lpath =~ m!^/!)
		{
		    $pwd = "";
		    chdir '/' || die "$!";
		    $lpath =~ s!^/!!;
		}
		print "about to recurse.. pwd is $pwd, next is $next, lpath is $lpath\n";
		&recurse_path ($pwd, $lpath);
	    }
	    else
	    {
		if (-d $next)
		{
		    print "im a dir: $next\n";
		    chdir $next || die "$next: $!";
		    $pwd = "" if $pwd eq "/";
		    if ($rest)
		    {
			&recurse_path (sprintf ("%s/%s", $pwd, $next), $rest);
		    }
		    else
		    {
			return sprintf ("%s/%s", $pwd, $next);
		    }
		}
		else
		{
		    local ($retval) = sprintf ("%s/%s", $pwd, $next);
		    print "returing $retval\n";
		    return $retval;
		}
	    }
	}
    }
}

sub unravel_path
{
    local ($path) = @_;
    die "`$path' is not an absolute path" if $path !~ m!^/!;

    chdir "/" || die "$!";
    # clean extra slashes from path
    $path =~ s!/+!/!g;
    $path =~ s!/+$!!;
    $path =~ s!^/!!;
    return &recurse_path ("/", $path);
}

print "> ";
while (<>)
{
    s/\s*$//;
    print &unravel_path ($_), "\n> ";
}
