#!/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

removeSnpFromMipe.pl - Removes SNP data from MIPE file
  based on MIPE version v0.9
  arguments: * mipe_file
             * STDIN: tab-delimited list of data, in the following order:
	           PCR ID, SNP ID

=head1 SYNOPSIS

removeSnpFromMipe.pl my_file.mipe < my_data.txt

=head1 AUTHOR

Jan Aerts (jan.aerts@wur.nl)

=cut

my $file = shift;
if ( not defined $file ) { die "Please provide filename\n" };
my $twig = XML::Twig->new( pretty_print => 'indented'
#                          , keep_atts_order => 1
			 , TwigHandlers => { pcr => \&pcr }
			 );

my @snp_data = ( <STDIN> );
my %snp_passed;

foreach ( @snp_data ) {
  chomp;
  my ( $pcr_id_in, $snp_id_in ) = split /\t/, $_;
  $snp_passed{$snp_id_in} = 0;
}

$twig->parsefile($file);
$twig->print;

foreach ( sort keys %snp_passed ) {
  if ( $snp_passed{$_} == 0 ) {
    print STDERR "Data for $_ could not be removed from MIPE file; $_ not present\n";
  }
}

sub pcr {
  my ( $twig, $pcr ) = @_;
  
  my $pcr_id = $pcr->first_child('id')->text;
  
  foreach my $input_line ( @snp_data ) {
    chomp $input_line;
    my ( $pcr_id_in, $snp_id_in ) = split /\t/, $input_line;
    
    if ( $pcr_id eq $pcr_id_in ) {
      my @snps = $pcr->next_elt('use')->children('snp');
      foreach my $snp ( @snps ) {
        if ( $snp->first_child('id')->text eq $snp_id_in ) {
	  $snp->delete;
	  $snp_passed{$snp_id_in} = 1;
	}
      }
      my @samples = $pcr->next_elt('use')->children('sample');
      foreach my $sample ( @samples ) {
        my @genotypes = $sample->children('genotype');
	foreach my $genotype ( @genotypes ) {
	  if ( $genotype->first_child('snp_id')->text eq $snp_id_in ) {
	    $genotype->delete;
	  }
	}
      }
    }
  }
}
