# vim:sw=4:ts=4

=head2 rel2abs()

Converts a relative path to an absolute path.

    $abs_path = rel2abs( $path ) ;
    $abs_path = rel2abs( $path, $base ) ;

If C<$base> is not present or '', then the current working directory is used.
If C<$base> is relative, then it is relative to the current working directory.

This only works reliably on UNIX systems.

=cut

sub rel2abs {
	my $fname = shift;
	$fname =~ s|/{2,}|/|g;
	$fname =~ s|/$||;

	if (substr($fname, 0, 1) ne '/') {
		my $base;
		if (@_) {
			$base = shift;
			if (substr($base, 0, 1) ne '/') {
				chomp(my $wd = `pwd`);
				$base = "$wd/$base";
			}
		}
		else {
			chomp($base = `pwd`);
		}
		$fname = "$base/$fname";
	}
	$fname =~ s|^/||;
	my @src = split('/', $fname);
	my @dst;
	while (@src) {
		my $comp = shift @src;
		next if $comp eq '.';
		if ($comp eq '..') {
			pop @dst;
		}
		else {
			push @dst, $comp;
		}
	}
	return '/'.join('/', @dst);
}

# Test script
use File::Spec;
while (<>) {
	my ($rel, $base) = split(' ', $_);
	print "rel2abs(): ", rel2abs($rel, $base), "\n";
	print "File::Spec->rel2abs(): ", File::Spec->rel2abs($rel, $base), "\n";
}
