#!/perl -w
# NAME: lineendings.pl
# AIM: Check the line ending of a file
use strict;
use warnings;
require 'logfile.pl' or die "Unable to load logfile.pl ...\n";
# log file stuff
my ($LF);
my $pgmname = $0;
if ($pgmname =~ /\w{1}:\\.*/) {
	my @tmpsp = split(/\\/,$pgmname);
	$pgmname = $tmpsp[-1];
}
my $outfile = "temp.$pgmname.txt";
open_log($outfile);
prt( "$0 ... Hello, World ...\n" );
# debug
my $dbg1 = 0;	# show lines as processed ...

# my $in_file = 'genalt.pl';
#my $in_file = 'C:\\FG\\FGCOM\\xmlrpc-c\\Windows';
my $in_file = 'C:\\FGCVS\\xmlrpc-c\\Windows';
my @fnd_files = ();
my %fnd_hash = ();
my $typ = '';
if (-f $in_file) {
	$typ = process_file($in_file);
	add_2_found($typ, $in_file);
} elsif (-d $in_file) {
	process_directory($in_file);
} else {
	prt( "ERROR: [$in_file] is NOT file or folder???\n" );
}
foreach my $key (keys %fnd_hash) {
	my $val = $fnd_hash{$key};
	$val =~ s/\*/, /g;
	prt( "$key = $val\n" );
}
close_log($outfile,1);
exit(0);

##########################################

sub add_2_found {
	my ($ty, $fi) = @_;
	push(@fnd_files, [$ty, $fi]);
	$fnd_hash{$ty} .= '*' if (defined $fnd_hash{$ty});
	$fnd_hash{$ty} .= $fi;
	while (length($ty) < 8) {
		$ty .= ' ';
	}
	prt( "$ty $fi\n" );
}

sub process_directory {
	my ($inf) = shift;
	prt( "Processing $inf folder ...\n" );
	if ( opendir( DIR, $inf ) ) {
		my @files = readdir(DIR);
		closedir DIR;
		foreach my $fl (@files) {
			if (($fl eq '.') || ($fl eq '..')) {
				next;
			}
			my $ff = $inf . "\\" . $fl;
			if (-f $ff) {
				$typ = process_file($ff);
				add_2_found( $typ, $fl );
			}
		}
	} else {
		prt( "ERROR: Could not open folder [$inf] ...\n" );
	}
}

sub process_file {
	my ($if) = shift;
	my $type = "UNKNOWN";
	if (open INF, "<$if") {
		binmode INF;
		my @lines = <INF>;
		close INF;
		my $cnt = scalar @lines;
		prt( "Got $cnt lines to process from [$if] ...\n" ) if ($dbg1);
		my $crlfcnt = 0;
		my $crcnt = 0;
		my $lfcnt = 0;
		my $ncnt = 0;
		my $lcnt = 0;
		foreach my $line (@lines) {
			$lcnt++;
			my $ll = length($line);
			my $ch = '';
			my $gotcr = 0;
			my $gotlf = 0;
			for (my $i = $ll - 1; $i >= 0; $i--) {
			###for (my $i = 0; $i < $ll; $i++) {
				$ch = substr($line, $i, 1);
				if ($ch eq "\n") {
					$gotlf = 1;
				} elsif ($ch eq "\r") {
					$gotcr = 1;
				} else {
					last;
				}
			}
			if( $gotcr && $gotlf ) {
				$crlfcnt++;
			} elsif ( $gotcr ) {
				$crcnt++;
			} elsif ( $gotlf ) {
				$lfcnt++;
			} else {
				$ncnt++;
			}
		}
		if (($crlfcnt == $cnt)||($crlfcnt == ($cnt - 1))) {
			$type = "CRLF";
		} elsif (($crcnt == $cnt)||($crcnt == ($cnt - 1))) {
			$type = "MAC";
		} elsif (($lfcnt == $cnt)||($lfcnt == ($cnt - 1))) {
			$type = "UNIX";
		} else {
			$type = "MIXED";
		}
		prt( "$type - both=$crlfcnt cr=$crcnt lf=$lfcnt none=$ncnt ...\n" ) if ($dbg1);

	} else {
		prt( "ERROR: Failed to open [$if] ...\n" );
	}
	return $type;
}


# eof
