#  undos.pl -- ensure all text files are in UNIX text file format

require 5;

$tmpfile = "undos.tmp";

if ($ARGV[0] eq '-r') {
	shift @ARGV;
	$reverse = 1;
}

sub ProcessFile {
	local ($f) = @_;
	local ($path, $found, @dirlist);

	if ( -d $f ) {
		opendir (dir, $f);
		@dirlist = readdir (dir);
		closedir (dir);
		foreach (@dirlist) {
			next if ($_ eq '.' || $_ eq '..');

			$path = $f . "/" . $_;

			if ($_ =~ /\.[cC]$/ ||
				$_ =~ /\.[xX]$/ ||
				$_ =~ /\.[hH]$/ ||
				$_ =~ /\.[iI][nN]$/ ||
				$_ eq "README" ||
				$_ eq "inventory" ||
				$_ =~ /-scene$/ ||
				$_ =~ /\.[cC][pP][pP]$/ ||
				$_ =~ /\.[pP][lL]$/ ) {
				ProcessFile ( $path );
			}
			elsif ( -d $path ) {
				ProcessFile ( $path );
			}
		}
			
	}
	else {
		$found = 0;
		open (src, $f) || die "unable to open input: $f";
		binmode src;
		open (dst, ">$tmpfile") || die "unable to open temporary outfile";
		binmode dst;
		while (<src>) {
			$last = chop;
			$_ = $_ . $last if ($last ne "\n");
			if ($reverse) {
			if ( substr($_, length($_) - 1, 1) ne "\r" ) {
				++ $found;
				$_ = $_ . "\r";
			}
			}
			else {
			if ( substr($_, length($_) - 1, 1) eq "\r" ) {
				++ $found;
				chop;
			}
			}	
			print dst $_, "\n";
		}
		close (src);
		close (dst);
		if ($found != 0) {
			print "Converted $found line(s) in $f\n";
			rename ($f, $f . ".orig") || die "rename failed";
			rename ($tmpfile, $f) || die "rename failed";
#			unlink $tmpfile;
		}
		else {
			unlink $tmpfile;
		}
	}
}

ProcessFile ($ARGV[0])
