#!/perl -w
# NAME: utils.pl
# AIM: Various utility subs
# 22/09/2010 - now see lib_utils.pl for these...

sub trim_tail {
	my ($ln) = shift;
	while ($ln =~ /\s$/) {
		$ln = substr($ln,0,length($ln) - 1); # remove all TRAILING space
	}
	return $ln;
}

sub unix_2_dos {
	my ($f) = shift;
	$f =~ s/\//\\/g;
	return $f;
}

# fix relative directory - fix relative path - path fix
# Remove any DOT or DOUBLE DOT from the PATH
sub fix_rel {
	my ($path) = shift;
	$path = unix_2_dos($path);	# ensure DOS separator
	my @a = split(/\\/, $path);	# split on DOS separator
	my $npath = '';
	my $wmsg = '';
	my $max = scalar @a;
	my @na = ();
	for (my $i = 0; $i < $max; $i++) {
		my $p = $a[$i];
		if ($p eq '.') {
			# ignore this
		} elsif ($p eq '..') {
			if (@na) {
				pop @na;	# discard previous
			} else {
				$wmsg = "WARNING: Got relative .. without previous!!! [$path]";
				prtw( "$wmsg\n" );
			}
		} else {
			push(@na,$p);
		}
	}
	foreach my $pt (@na) {
		$npath .= "\\" if length($npath);
		$npath .= $pt;
	}
	return $npath;
}

sub sub_common_folder {
	my ($f1, $f2) = @_;
	my $off = 0;
	my $df1 = lc(unix_2_dos($f1));
	my $df2 = lc(unix_2_dos($f2));
	while ( substr($df1,$off,1) && substr($df2,$off,1) &&
			( substr($df1,$off,1) eq substr($df2,$off,1) ) ) {
		$off++;
	}
	return substr($f1,$off);
}

1;

# eof - utils.pl
