#!/usr/bin/perl

# ractip.pl ver. 1.2.0
# Copyright (C) 2012 Yuki Kato
# This script is used to access the web server RactIP for predicting RNA-RNA interactions with kissing hairpins and parse the output.
# Usage: Type "./ractip.pl" in your terminal.

use strict;
use warnings;
use Getopt::Long;
use HTTP::Request::Common qw(POST);
use LWP::UserAgent;
use HTML::TreeBuilder;

my %opt = (model => "CONTRAfold", internal => 1, external => 1, help => 0);
GetOptions(\%opt, qw(model=s internal=i external=i help)) or exit;

# Argument check
if (!exists $ARGV[0] || $opt{help} == 1) {
    print "ractip.pl ver. 1.2.0\n\n";
    print "This script is used to access the web server RactIP for predicting RNA-RNA interactions with kissing hairpins and parse the output.\n\n";
    print "Usage: ./ractip.pl [OPTIONS] [FILES]\n\n";
    print "[FILES]\n";
    print " Note: Each file for an input sequence must be specified in FASTA format.\n\n";
    print "[OPTIONS]\n";
    print " -m, --model     CONTRAfold or McCaskill (default: CONTRAfold)\n";
    print " -i, --internal  A positive weight for true internal base pairs (default: 1)\n";
    print " -e, --external  A positive weight for true external base pairs (default: 1)\n";
    print " -h, --help      Show this message\n\n";
    exit;
}

# File 1 input
open(FILE, $ARGV[0]) or die "$!";
my $sequence1;

while (my $line = <FILE>) {
	$sequence1 = $sequence1.$line;
}

close(FILE);

# File 2 input
open(FILE, $ARGV[1]) or die "$!";
my $sequence2;

while (my $line = <FILE>) {
	$sequence2 = $sequence2.$line;
}

close(FILE);

# Set the parameters
my %params = (
	seq1 => $sequence1,
	seq2 => $sequence2,
	model => $opt{model},
	gamma1 => $opt{internal},
	gamma2 => $opt{external},
);

# Create a request
my $req = POST("http://ws.sato-lab.org/rtips/ractip/process.php", [%params]);

# Retrieve the result for the request
my $ua = LWP::UserAgent->new;
my $res = $ua->request($req);

if ($res->is_success) {
	my $content = $res->content;
	my $tree = HTML::TreeBuilder->new;
	$tree->parse($content);
	
	my @h2 = $tree->find('h2');
	my $heading = $h2[0]->as_text;
	
	# Show an error
	if ($heading eq "Error") {
		print "Error!\n";
		my @warning = $tree->look_down('class', 'warning');
		print $_->as_text."\n" for @warning;
	}
	
	# Show the result
	else {
		my @structure = $tree->look_down('id', 'vienna')->find('pre');
		print $_->as_text."\n" for @structure;
	}

}

else {
	print $res->status_line, "\n";
}

print "\n";
