#!/usr/bin/env perl

=head1 NAME

locarnap-revcomp.pl

=head1 SYNOPSIS

locarnap-revcomp.pl [options] <fasta files>

=head1 DESCRIPTION

locarnap-revcomp.pl generates a file of reverse complement of
sequences. The script is intended for the use in the LocARNA-P
pipeline for refining RNAz hits.


=head1 OPTIONS

=over 4

=item  B<--help>

Brief help message

=item  B<--man>

Full documentation

=back

Produce reverse complement of sequences in the given fasta files and
write a corresponding file with -rc suffix.

The script is used to reverse-complement the sequences in
Realign-Sequences as generated by locarnap-revisit-RNAz-hits. Assume
simple fasts format (only one line per sequence after sequence
header).  Reverse left_context/right_context annotation in sequence
names.


=cut

use warnings;
use strict;


## ----------------------------------------
##
#constants

##------------------------------------------------------------
## options
use Getopt::Long;
use Pod::Usage;

my $help;
my $man;
my $quiet;
my $verbose;


## Getopt::Long::Configure("no_ignore_case");

GetOptions(
	   "verbose" => \$verbose,
	   "quiet" => \$quiet,
	   "help"=> \$help,
	   "man" => \$man,
	   ) || pod2usage(2);

pod2usage(1) if $help;
pod2usage(-exitstatus => 0, -verbose => 2) if $man;

if ($#ARGV<0) {print STDERR "No fasta files given.\n"; pod2usage(-exitstatus => -1);}

my @files=@ARGV;

## ------------------------------------------------------------
##
sub rev_compl {
    my ($seq)=@_;

    my $rcseq=reverse($seq);
    $rcseq =~ tr/ACGUTacgut/TGCAAtgcaa/;

    return $rcseq;
}



## ------------------------------------------------------------
## main part


foreach my $file (@files) {
    if ($file =~ /(.+)\.([^\.]+)$/) {
	my $base=$1; my $suf=$2;

	my $outfile="$base-rc.$suf";

	open(my $IN, "<", "$file") || die "Cannot read $file: $!";
	open(my $OUT, ">", "$outfile") || die "Cannot write $outfile: $!";

	while(<$IN>=~/^>(\S+)\s+(.+)$/) {
	    my $name=$1;
	    my $anno=$2;

 	    if ($anno=~/(.*)left_context=(\d+); right_context=(\d+);(.*)/) {
 		my $before=$1;
 		my $lc=$2;
 		my $rc=$3;
 		my $after=$4;
 		$anno = "$before"."left_context=$rc; right_context=$lc;$after";
 	    }

	    print $OUT ">".$name." ".$anno." strand=-\n";

	    my $line=<$IN>;
	    chomp $line;
	    print $OUT rev_compl($line)."\n";
	}

	close $OUT;
	close $IN;
    }
}


## ------------------------------------------------------------
