#!/usr/bin/perl

#    This library is free software; you can redistribute it and/or
#    modify it under the terms of the GNU Lesser General Public
#    License as published by the Free Software Foundation; either
#    version 2.1 of the License, or (at your option) any later version.
#
#    This library is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#    Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public
#    License along with this library ('COPYING'); if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

use strict;
use warnings;
use XML::Twig;

=head1 NAME

mipe2dbSTS.pl - Generates input file for submission to dbSTS
  included in output: STS section of dbSTS submission
  based on MIPE version v1.1
  arguments: * mipe_file
             * config file
             * (optional) list of PCR IDs

  The config file consists of lines containing a key and a value, separated by an equal sign ('=').
  The key consists of the lowercase name of the NCBI submission file (see website dbSTS), followed by
  an underscore and the lowercase name of the field in that file.
  The following fields should be defined in the config file:
     pub_title=
     pub_authors=
     source_name=
     source_organism=
     cont_name=
     cont_fax=
     cont_tel=
     cont_email=
     cont_lab=
     cont_inst=
     cont_addr=
     protocol_name=
     protocol_protocol=
     buffer_name=
     buffer_buffer=
     sts_pcr_profile=
   For protocol_protocol, buffer_buffer and sts_pcr_profile, more lines are necessary (see example).
   
   An example of a config file look like this:
     pub_title=Genetic mapping of chicken SNPs
     pub_authors=Aerts,J.A.; Veenendaal,T.; Crooijmans,R.P.M.A; Groenen,M.A.M
     source_name=Chicken genomic DNA
     source_organism=Gallus gallus
     cont_name=Jan Aerts
     cont_fax=+31 317 483929
     cont_tel=+31 317 483397
     cont_email=jan.aerts@wur.nl
     cont_lab=Animal Breeding and Genomics Group
     cont_inst=Wageningen University
     cont_addr=PO Box 338, 6700 AH Wageningen, The Netherlands
     protocol_name=Protocol_Aerts
     protocol_protocol=Template:    30-60 ng
     protocol_protocol=Primer:     each 4 uM
     protocol_protocol=dNTPs:    each 200 uM
     protocol_protocol=Taq:        0.3 units
     protocol_protocol=Volume:         12 ul
     buffer_name=Buffer_Aerts
     buffer_buffer=MgCl2:         1.5 mM
     buffer_buffer=(NH4)2SO4:      20 mM
     buffer_buffer=Tris-HCl:       75 mM
     buffer_buffer=Tween 20: 0.01% (w/v)
     buffer_buffer=pH:               8.8

=head1 BUGS

Unknown. If you encounter one, please let me know (jan.aerts@wur.nl).

=head1 SYNOPSIS

mipe2dbSTS.pl your_file.mipe dbSTS.config <pcr_id1> <pcr_id2>

=head1 ADDITIONAL INFO

See http://mipe.sourceforge.net

=head1 AUTHOR

Jan Aerts (jan.aerts@bbsrc.ac.uk)

=cut

my %amb_codes = ( M => ['A', 'C']
                , R => ['A', 'G']
		, W => ['A', 'T']
		, S => ['C', 'G']
		, Y => ['C', 'T']
		, K => ['G', 'T']
		, V => ['A', 'C', 'G']
		, H => ['A', 'C', 'T']
		, D => ['A', 'G', 'T']
		, B => ['C', 'G', 'T']
		, N => ['A', 'C', 'G', 'T']
		);

my ( $mipe_file, $config_file ) = @ARGV;
if ( not defined $mipe_file or not defined $config_file ) { die "Please provide filenames\n" };

chomp (my @pcr_ids = grep { /[a-zA-Z0-9]/ } (<STDIN>));

my %config;
open CONFIG, $config_file || die "Cannot open config file $config_file\n";
chomp ( my @config = ( <CONFIG> ) );
close CONFIG;
foreach ( @config ) {
  my ( $key, $value ) = split /=/, $_;
  if ( $key ne 'protocol_protocol' and $key ne 'buffer_buffer' and $key ne 'sts_pcr_profile' ) {
    $config{$key} = $value;
  } elsif ( $key eq 'protocol_protocol' ) {
    push @{$config{'protocol_protocol'}}, $value;
  } elsif ( $key eq 'buffer_buffer' ) {
    push @{$config{'buffer_buffer'}}, $value;
  }
}

print pub();
print source();
print contact();
print protocol();
print buffer();
print sts();

sub pub {
  my $to_print;
  
  $to_print .= "TYPE: PUB\n";
  $to_print .= "TITLE:\n";
  $to_print .= $config{'pub_title'} . "\n";
  $to_print .= "AUTHORS:\n";
  $to_print .= $config{'pub_authors'} . "\n";
  $to_print .= "STATUS: 1\n";
  $to_print .= "||\n";
  
  return $to_print;
}

sub source {
  my $to_print;
  
  $to_print .= "TYPE: SOURCE\n";
  $to_print .= "NAME: " . $config{'source_name'} . "\n";
  $to_print .= "ORGANISM: " . $config{'source_organism'} . "\n";
  $to_print .= "||\n";
  
  return $to_print;
}

sub contact {
  my $to_print;
  
  $to_print .= "TYPE: CONT\n";
  $to_print .= "NAME: " . $config{'cont_name'} . "\n";
  $to_print .= "FAX: " . $config{'cont_fax'} . "\n";
  $to_print .= "TEL: " . $config{'cont_tel'} . "\n";
  $to_print .= "EMAIL: " . $config{'cont_email'} . "\n";
  $to_print .= "LAB: " . $config{'cont_lab'} . "\n";
  $to_print .= "INST: " . $config{'cont_inst'} . "\n";
  $to_print .= "ADDR: " . $config{'cont_addr'} . "\n";
  $to_print .= "||\n";
  
  return $to_print;
}

sub protocol {
  my $to_print;
  
  $to_print .= "TYPE: PROTOCOL\n";
  $to_print .= "NAME: " . $config{'protocol_name'} . "\n";
  $to_print .= "PROTOCOL:\n";
  foreach ( @{$config{'protocol_protocol'}} ) {
    $to_print .= "  " . $_ . "\n";
  }
  $to_print .= "||\n";
  
  return $to_print;
}

sub buffer {
  my $to_print;
  
  $to_print .= "TYPE: BUFFER\n";
  $to_print .= "NAME: " . $config{'buffer_name'} . "\n";
  $to_print .= "BUFFER:\n";
  foreach ( @{$config{'buffer_buffer'}} ) {
    $to_print .= "  " . $_ . "\n";
  }
  $to_print .= "||\n";
  
  return $to_print;
}






sub sts {
  my $twig = XML::Twig->new( TwigHandlers => { pcr => \&pcr }
                         , pretty_print => 'indented' );
  $twig->parsefile($mipe_file);
  exit;
}

sub pcr {
  my ( $twig, $pcr ) = @_;

  my $to_include = 0;
  my $pcr_id = $pcr->{att}->{id};
  if ( scalar @pcr_ids > 0 ) {
    $to_include = 0;
    foreach ( @pcr_ids ) {
      if ( $pcr_id =~ /$_/i ) {
        $to_include = 1;
      }
    }
  } else {
    $to_include = 1;
  }
  
  if ( $to_include ) {
    my $design = $pcr->first_child('design');
    my %snps;
    
    print "TYPE: STS\n";
    print "STATUS: New\n";
    print "CONT_NAME: ", $config{'cont_name'}, "\n";
    print "PROTOCOL: ", $config{'protocol_name'}, "\n";
    print "BUFFER: ", $config{'buffer_name'}, "\n";
    print "SOURCE: ", $config{'source_name'}, "\n";
    print "CITATION:\nGenetic mapping of chicken SNPs\n";
    print "STS#: ", $pcr_id, "\n";
    print "SIZE: ", length $design->first_child('seq')->text, "\n";
    print "F_PRIMER: ", $design->first_child('primer1')->first_child('seq')->text, "\n";
    print "R_PRIMER: ", $design->first_child('primer2')->first_child('seq')->text, "\n";
    print "DNA_TYPE: Genomic\n";
    print "PCR_PROFILE:\n";
    if ( defined $design->first_child('profile') ) {
      my $profile = $design->first_child('profile');
      if ( defined $profile->first_child('predenaturation') ) {
        print "  Presoak: ", $profile->first_child('predenaturation')->first_child('temp')->text, " for ", $profile->first_child('predenaturation')->first_child('time')->text, "\n";
      }
      if ( defined $profile->first_child('cycle') ) {
        my @cycles = $profile->children('cycle');
        foreach ( @cycles ) {
          print "  Denaturation: ", $_->first_child('denaturation')->first_child('temp')->text, " for ", $_->first_child('denaturation')->first_child('time')->text, "\n";
          print "  Annealing: ", $_->first_child('annealing')->first_child('temp')->text, " for ", $_->first_child('annealing')->first_child('time')->text, "\n";
          print "  Elongation: ", $_->first_child('elongation')->first_child('temp')->text, " for ", $_->first_child('elongation')->first_child('time')->text, "\n";
          print "  PCR cycles: ", $_->first_child('number')->text, "\n";
        }
      }
      if ( defined $profile->first_child('postelongation') ) {
        print "  Presoak: ", $profile->first_child('postelongation')->first_child('temp')->text, " for ", $profile->first_child('postelongation')->first_child('time')->text, "\n";
      }
      
    } else {
      print "  UNKNOWN\n";
    }
    print "PUBLIC:\n";

    if ( defined $pcr->first_child('use') ) {
      my $use = $pcr->first_child('use');
      my @snps = $use->children('snp');
      if ( scalar @snps > 0 ) {
        print "COMMENT:\n";
	print "  Polymorphism(s) (positions as in sequence):\n";
      }
      foreach my $snp ( @snps ) {
        if ( defined $snp->first_child('pos_design') ) {
          my $snp_amb = $snp->first_child('amb')->text;
          if ( $use->first_child('revcomp')->text == 1 ) {
            $snp_amb =~ tr/ACGTMRWSYKVHDBN
                          /TGCAKYWSRMBDHVN
                          /s;
          }
          print "    ID=", $snp->{att}->{id}, "\n";
          print "      Position=", $snp->first_child('pos_design')->text, "\n";
          print "      Ambiguity=", $snp_amb, "\n";
        }
      }
    }
    print "SEQUENCE:\n";
    my $seq = $design->first_child('seq')->text;
    $seq =~ s/(.{50})/$1\n/g;
    print $seq, "\n";

    print "||\n";
  }
}
