#!/usr/bin/perl -w
die "Usage: sl [filenames]\n" unless @ARGV;
$| = 1;
$cwd = '';
$indent = 0;
chomp($cwd = `pwd`) || die "Can't find current directory: $!\n" if @ARGV > 1;

foreach $name (@ARGV) {
    @indent = ();
    if ($name eq ".") {
	chomp($name = `pwd`);
    } else {
	print "$name:\n";
    }
    @path = split(m;/;, $name);

    if (@path && $path[0] eq '') {
	chdir '/';
	shift @path;
	print '/';
	$indent = 1;
    }

    while (@path) {
	$elem = shift @path;
	$new = readlink($elem);
	if (defined $new) {
	    print "$elem -> $new\n";
	    unshift(@path,split(m;/;, $new));
	    if (@path && $path[0] eq '') {
		chdir '/';
		shift @path;
		print '/';
		$indent = 1;
		@indents = ();
		next;
	    }
	    while (@indents && $path[0] eq '..') {
		$indent = pop(@indents);
		chdir '..' || die "\n\nCan't cd to ..: $!\n";
		shift @path;
	    }
	    print "\t" x ($indent / 8), ' ' x ($indent % 8);
	} else {
	    print $elem;
	    push(@indents,$indent);
	    $indent += length($elem)+1;
	    if (@path) {
		print '/';
		chdir $elem || die "\n\nCan't cd to $elem: $!\n";
	    }
	}
    }
    print "\n";
    $indent = 0;
    chdir $cwd || die "Can't cd back: $!\n" if $cwd ne '';
}

