#!/usr/bin/perl

# Copyright 2002 Vlado Keselj www.cs.dal.ca/~vlado
#
# Smth like Linux command `tree'
#
# On some systems there is no command that would print recursively a
# directory structure like the Linux command `tree', so then this
# script can be used.

while ($#ARGV > -1) {
    print &dir_tree(shift);
}

sub dir_tree {
    my $dir = shift;
    my $dirbase = $#_ == -1 ? $dir : shift;

    # symbolic link
    if (-l $dir) { return "$dirbase -> ".readlink($dir)."\n" }

    return "$dirbase\n" unless -d $dir;

    local ($_, *DIR);
    opendir(DIR, $dir) || die "can't opendir $dir: $!";
    my (@r) = grep {$_} (map { /^\.\.?$/ ? '' : &dir_tree("$dir/$_", $_) } readdir(DIR));
    closedir(DIR);

    my $r = "$dirbase\n";
    return $r unless @r; # empty dir

    while (@r) {
	my $subdirresult = shift @r;
	if ($#r == -1) { $subdirresult = "`-- $subdirresult";
			 $subdirresult =~ s/\n(.)/\n    $1/g }
	else           { $subdirresult = "|-- $subdirresult";
			 $subdirresult =~ s/\n(.)/\n|   $1/g }
	$r .= $subdirresult;
    }

    return $r;
}
