#!/usr/bin/perl
use strict;
use FileHandle;


my $dfamFile = "Dfam.hmm.bak";
open IN,"<$dfamFile" or die "Could not open $dfamFile for reading!\n";
my $header = "";
my $tmpHeader = "";
my @hmmChunk = ();
my $chunkIdx = 0;
my %fileHandls = ();
my @thresholds = ();
while ( <IN> )
{
  if ( /^#/ && $header eq "" )
  {
    $tmpHeader .= $_;
  }elsif ( $tmpHeader )
  {
    $header = $tmpHeader;
    $tmpHeader = undef;
  }

  # Start of an entry
  if ( /^HMMER3\/f/ && $hmmChunk[0] )
  {
    foreach my $thresh ( @thresholds )
    {
      my $fileHandle = $thresh->[0];
      my $ga = $thresh->[1];
      my $tc = $thresh->[2];
      my $nc = $thresh->[3];
      print $fileHandle $hmmChunk[0];
      print $fileHandle "GA     $ga;\n";
      print $fileHandle "TC     $tc;\n";
      print $fileHandle "NC     $nc;\n";
      print $fileHandle $hmmChunk[1];
    }
    @hmmChunk = ();
    $chunkIdx = 0;
    @thresholds = (); 
  }
 
  #GA    33.14;
  #TC    33.14;
  #NC    33.14;
  #TH    TaxId:10090; TaxName:Mus musculus; GA:13.90; TC:33.14; NC:13.85; fdr:0.002;
  if (/^(GA|TC|NC)/ )
  {
    $chunkIdx++ if ( $1 eq "NC" );
    next;
  }elsif (/^TH\s+TaxId:\d+\s*;\s*TaxName:([^\;]+);\s*GA:([\d+\.]+);\s*TC:([\d+\.]+);\s*NC:([\d+\.]+);.*/ )
  {
    my $org = $1;
    my $ga = $2;
    my $tc = $3;
    my $nc = $4;
    if ( ! exists $fileHandls{$org} )
    {
      my $orgFile = lc($org);
      $orgFile =~ s/^\s+(.*)/$1/;
      $orgFile =~ s/(.*)\s+$/$1/;
      $orgFile =~ s/\s+/_/g;
      $orgFile .= "_dfam.hmm";
      my $fh = FileHandle->new;
      if ( ! $fh->open(">$orgFile") )
      {
        die "Could not open $orgFile for writing!\n";
      }
      print $fh "$header";
      $fileHandls{$org} = $fh;
    }
    push @thresholds, [ $fileHandls{$org}, $ga, $tc, $nc ];
  } 
  $hmmChunk[$chunkIdx] .= $_;
}
if ( $hmmChunk[0] )
{
  foreach my $thresh ( @thresholds )
  {
    my $fileHandle = $thresh->[0];
    my $ga = $thresh->[1];
    my $tc = $thresh->[2];
    my $nc = $thresh->[3];
    print $fileHandle $hmmChunk[0];
    print $fileHandle "GA     $ga;\n";
    print $fileHandle "TC     $tc;\n";
    print $fileHandle "NC     $nc;\n";
    print $fileHandle $hmmChunk[1];
  }
}
close IN;

foreach my $org ( keys(%fileHandls) )
{
  $fileHandls{$org}->close;
}

1;
