#!/usr/bin/perl -w

#A program to remove duplicate drill locations from a FreePCB created drill file.

#--------------------------------------------------------------------------------------

#The input file is always named "drill_file.drl"
#Open the to be processed textual DRILL file as Read Only
open(INPUTDRILL, '<drill_file.drl') or die "drill_file.drl could not be found!\n";

#The cleaned output file will always be named "drill_file_cleaned.drl"
open(OUTPUTDRILL, '>drill_file_cleaned.drl');

#Read in and write out all lines that are before the start of drill location data
while (<INPUTDRILL>){
    $DrillLine = $_;
    chomp($DrillLine);
    print OUTPUTDRILL "$DrillLine\n";
    if($DrillLine eq "G90"){last}
    }

#We are now ready to start processing the individual drills for each drill size in the file
$OriginalTotalDrillCount = 0;
$NewTotalDrillCount = 0;
$ToolNumber = <INPUTDRILL>;
chomp($ToolNumber);

NewTool:
$DrillCount = 0;
@ThisToolsDrillLocs = ();
@SortedDrillLocations = ();
print OUTPUTDRILL "$ToolNumber\n";

while (<INPUTDRILL>){
    $DrillLine = $_;
    chomp($DrillLine);
    if($DrillLine =~ /^T/){goto ProcessTool}
    if($DrillLine =~ /^M30/){goto ProcessTool}
    push(@ThisToolsDrillLocs, $DrillLine);
    }

ProcessTool:
push(@ThisToolsDrillLocs, "ZZZ_end_of_list");
@SortedDrillLocations = sort @ThisToolsDrillLocs;
$OriginalTotalDrillCount = $OriginalTotalDrillCount + $#ThisToolsDrillLocs + 1 - 1;
for ($i = 0; $i < $#SortedDrillLocations; $i = $i + 1){
    if(($SortedDrillLocations[$i]) ne ($SortedDrillLocations[($i + 1)])){
        print OUTPUTDRILL "$SortedDrillLocations[$i]\n";
        $DrillCount = $DrillCount + 1;
        $NewTotalDrillCount = $NewTotalDrillCount + 1;
        }
    }
print "For Tool " . $ToolNumber . " Drill count was = " . ($#ThisToolsDrillLocs + 1 - 1) . " Drill count now is = " . $DrillCount . "\n";

if($DrillLine =~ /M30/){
    print OUTPUTDRILL "$DrillLine\n";
    close(OUTPUTDRILL);
    print "\n" . "Duplicate Drills Eliminated = " . ($OriginalTotalDrillCount - $NewTotalDrillCount) . "\n";
    print "\n" . "Total Drill Count Now Is = " . $NewTotalDrillCount . "\n\n";
    die "\n" . "Finished Processing Drill File\n";
    }
if($DrillLine =~ /^T/){
    $ToolNumber = $DrillLine;
    goto NewTool;
    }
print "We should never get here!";
