#!/usr/bin/perl -w
# Badri Adhikari, 5/2/2016

use strict;
use warnings;
use Carp;
use Cwd 'abs_path';
use File::Basename;

my $rr     = shift;
my $target = shift;
my $N      = shift;
my $Neff   = shift;
my $aln    = shift;

confess "$0 <RR-file> <target-id> <method> <author>" if !$rr;
confess "$rr does not exit!"   if not -f $rr;
confess "target-id not supplied!" if !$target;

$N    = "??" if ! $N;
$Neff = "??" if ! $Neff;
$aln  = "??" if ! $aln;

print "PFRMAT RR\n";
print "TARGET $target\n";
print "AUTHOR DNCON2\n";
print "METHOD DNCON2\n";
print "REMARK Number of sequences in the alignment = $N\n";
print "REMARK Effective number of sequences in the alignment = $Neff\n";
print "REMARK Alignment generated using $aln\n";
print "MODEL  1\n";
print "".wrap_seq(seq_rr($rr))."\n";
open RR, $rr or confess "ERROR! Could not open $rr $!";
while(<RR>){
	next if $_ !~ m/^[0-9]/;
	print $_;
}
close RR;
print "END\n";

sub seq_rr{
	my $file_rr = shift;
	confess ":(" if not -f $file_rr;
	my $seq;
	open RR, $file_rr or confess "ERROR! Could not open $file_rr! $!";
	while(<RR>){
		chomp $_;
		$_ =~ tr/\r//d; # chomp does not remove \r
		$_ =~ s/^\s+//;
		next if ($_ =~ /^>/);
		next if ($_ =~ /^PFRMAT/);
		next if ($_ =~ /^TARGET/);
		next if ($_ =~ /^AUTHOR/);
		next if ($_ =~ /^SCORE/); 
		next if ($_ =~ /^REMARK/);
		next if ($_ =~ /^METHOD/);
		next if ($_ =~ /^MODEL/); 
		next if ($_ =~ /^PARENT/);
		last if ($_ =~ /^TER/);   
		last if ($_ =~ /^END/);
		# Now, I can directly merge to RR files with sequences on top
		last if ($_ =~ /^[0-9]/);
		$seq .= $_;
	}
	close RR;
	$seq =~ s/\s+//;
	confess ":( no sequence header in $file_rr" if not defined $seq;
	return $seq;
}

sub wrap_seq{
	my $seq = shift;
	confess ":(" if !$seq;
	my $seq_new = "";
	while($seq){
		if(length($seq) <= 50){
			$seq_new .= $seq;
			last;
		}
		$seq_new .= substr($seq, 0, 50)."\n";
		$seq = substr($seq, 50);
	}
	return $seq_new;
}
