#!/usr/bin/perl -w
####
#### Fix PANTHER files coming in.
####

## Bring in necessaries.
use utf8;
use strict;
use Data::Dumper;
use Getopt::Long;
use File::Path; # old versions don't have this
use File::Find;
use Cwd;

my $verbose = '';
my $help = '';
my $execute = '';
GetOptions ('verbose' => \$verbose,
	    'help' => \$help,
	    'execute' => \$execute);

## Just a little printin' when feeling verbose.
sub ll {
  my $str = shift || '';
  print $str . "\n" if $verbose;
}
ll("Verbose ON.");

## Embedded help through perldoc.
if( $help ){
  system('perldoc', __FILE__);
  exit 0;
}

###
### Main.
###

sub arbre_file_process {
  my $fname = shift || die "no file name";

  my $file_text = '';
  my $file_buffer = [];

  ## Read in the file and make a buffer for counting lines.
  open(AFILE, "<$fname") or die "cannot open file for reading ($fname): $!";
  while(<AFILE>){
    $file_text .= $_;
    push @$file_buffer, $_;
  }
  close(AFILE);

  ## Test to see if this file has the error by buffer line count.
  if( scalar(@$file_buffer) == 2 ){
    ll('Error with: ' . $fname);
    #ll('Error with: ' . $file_text);

    ## Generate the replacement text.
    my $find = ";AN";
    my $replace = ";\nAN";
    $find = quotemeta $find; # escape regex metachars if present
    $file_text =~ s/$find/$replace/g;
    ll("Replace with: \n" . $file_text);

    ## Unlink the bad file.
    ll("Unlink: " . $fname);
    if( $execute ){
      unlink $fname or warn "could not unlink $fname: $!";
    }

    ## Put out the new version.
    ll("Rewrite: " . $fname);
    if( $execute ){
      open(OUTFILE, ">$fname") or die "could not open file: $!";
      print OUTFILE $file_text;
      close(OUTFILE);
    }
  }
}

ll("Scanning for .arbre files.");
sub scanner {
  ## Find the arbre files that aren't in SVN.
  my $ffile = $File::Find::name;
  #ll("Found: " . $ffile);
  if( $ffile =~ /\.arbre$/ && $ffile !~ /\.svn/ ){
    #ll("Matched: " . $ffile);

    arbre_file_process($ffile);
    #unlink $ffile if $execute;
  }
}
finddepth(\&scanner, getcwd());

###
### Perldoc.
###

=head1 NAME

fix-panther.pl

=head1 SYNOPSIS

fix-panther.pl [-h/--help] [-v/--verbose] [-e/--execute]

=head1 DESCRIPTION

This script adds takes all of the files provided on input and
reprocesses them into something not as bad.

=head1 OPTIONS

=over

=item -v/--verbose

Verbose

=item -h/--help

Help--this message.

=item -e/--execute

Actually execute the operations instead of just talking about them.

=back

=head1 SEE ALSO

http://wiki.geneontology.org/index.php/AmiGO_Manual:_Installation

=cut
