#!/perl -w
# NAME: inphones.pl
# AIM: A check of the number from one file, are present in another ...
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" );

my $in_file1 = "temp1.txt";
#my $in_file1 = "C:\\TXT\\innums2.txt";
my $in_file2 = "C:\\TXT\\phones.txt";
my $hadsep = 0;
my $currnm = '';
my $linnum = 0;
my $msg = '';
my @newnums = ();
if (open INF1, "<$in_file1") {
	my @lines1 = <INF1>;
	close INF1;
	if (open INF2, "<$in_file2") {
		my @lines2 = <INF2>;
		close INF2;
		prt( "Checking ".scalar @lines2." lines for ".scalar @lines1." lines ...\n" );
		foreach my $line1 (@lines1) {
			chomp $line1;
			$line1 = trim_all($line1);
			if (length($line1) && ($line1 =~ /\d+/)) {
				prt( "Finding $line1 ...\n" );
				$msg = "$line1";
				foreach my $line2 (@lines2) {
					$linnum++;
					chomp $line2;
					$line2 = trim_all($line2);
					if (length($line2)) {
						if ($line2 =~ /^;------------------------/) {
							$hadsep = 1;
						} else {
							if ($hadsep) {
								$currnm = $line2;
								$hadsep = 0;
							}
						}
						if ($line2 =~ /\d+/) {
							if (checklines( $line1, $line2 )) {
								$msg .= " $currnm (ln $linnum)";
								last;
							}
						}
					}
				}
				push(@newnums, $msg);
			}
		}
	} else {
		prt( "ERROR: Failed to open $in_file2 ...\n" );
	}
} else {
	prt( "ERROR: Failed to open $in_file1 ...\n" );
}

$msg = "\n";
$msg .= scalar localtime(time());
$msg .= "\n\n";
$msg .= "       CALLER ID IDENTIFICATION\n";
$msg .= "\n";
foreach my $nm (@newnums) {
	$msg .= "         $nm\n\n";
}
$msg .= "\nEOF\n";

write2file( "$msg", 'tempnums.txt' );
system('tempnums.txt');
close_log($outfile,0);
exit(0);

sub checklines {
	my ($ln1, $ln2) = @_;
	my $ll1 = length($ln1);
	my $ll2 = length($ln2);
	my $num1 = '';
	my ($ch1, $ch2, $lnum, $i, $j, $ch3, $ch4, $k, $n);
	for ($i = 0; $i < $ll1; $i++) {
		$ch1 = substr($ln1,$i,1);
		if ($ch1 =~ /\d/) {
			$num1 .= $ch1;
		}
	}
	$lnum = length($num1);
	if ($lnum) {
		$i = 0;
		$ch1 = substr($num1,0,1);	 # get FIRST - keep
		for ($j = 0; $j < $ll2; $j++) {
			$ch2 = substr($ln2,$j,1);
			if ($ch2 eq $ch1) {
				#first number matches - see if we can find the balance
				$n = $i + 1;
				$k = $j + 1;
				while (($n < $lnum)&&($k < $ll2)) {
					$ch3 = substr($num1,$n,1); # get next number
					$ch4 = substr($ln2,$k,1);
					if ($ch4 =~ /\d/) {
						if ($ch3 eq $ch4) {
							$n++;
							$k++;
						} else {
							last;
						}
					} else {
						$k++;
					}
				}
				if ($n == $lnum) {
					prt( "Found [$ln1] in [$ln2]...name = $currnm, around line $linnum ...\n" );
					return 1;
				}
			}
		}
	}
	return 0;
}

# eof
