#!/usr/bin/perl -w
#< fix-diff.pl - change windows patch file to unix patch file
# 2010-05-09 - some small improvements...
use strict;
use warnings;
use File::Basename;

my $bn = basename($0);
my $in_file = "";
my $out_file = "tempdiff.txt";
my $os = $^O;

sub prt($) {
   print shift;
}

sub process_file($) {
   my ($inf) = shift;
   my @nlines = ();
   if (open INF, "<$inf") {
      my @lines = <INF>;
      close INF;
      my $lncnt = scalar @lines;
      my $lnnum = 0;
      prt( "Processing $lncnt lines from $inf...\n" );
      for (my $i = 0; $i < $lncnt; $i++) {
         $lnnum++;
         my $line = $lines[$i];
         chomp $line;
         $line =~ s/\r$//;
         next if ($line =~ /^Only in /);
         if ($line =~ /^(---|\+\+\+)\s+.+/) {
            $line =~ s/\\/\//g;
         }
         push(@nlines,$line);
      }
      my $nlc = scalar @nlines;
      prt("Done $lncnt lines, and got $nlc lines of output\n");
   } else {
      prt( "ERROR: Unable to open $inf...\n" );
   }
   return @nlines;
}

sub write2file($$) {
   my ($txt,$fil) = @_;
   unlink $fil if (-f $fil);
   if (open WOF, ">$fil") {
       if ($os =~ /^MSWin/) {
           binmode WOF;
       }
      print WOF $txt;
      close WOF;
      prt( "Written test to $fil...\n" );
   } else {
      prt( "ERROR: failed to write file $fil\n" );
   }
}

prt("Running in OS [$os]\n");
if (@ARGV) {
   $in_file = shift @ARGV;
   if (@ARGV) {
      $out_file = shift @ARGV;
   }
} else {
   prt("Usage: in_file [out_file]\n");
   prt("Process the input 'diff' patch file into unix form,\n");
   prt("and output to [$out_file] if not out file given...\n");
   exit(1);
}

if ( ( length($in_file) == 0 ) || ( ! -f $in_file ) ) {
   if ( length($in_file) ) {
      prt( "ERROR: can not locate $in_file...\n" );
      exit(1);
   } else {
      prt( "ERROR: Must supply the in-file to process...\n" );
      exit(1);
   }
}

my @clns = process_file($in_file);
if (@clns) {
   my $txt = join("\n",@clns);
   $txt .= "\n";
   write2file( $txt, $out_file );
} else {
   prt( "No file written...\n" );
}

exit(0);
