#!/usr/bin/perl -w
use strict;
use CGI qw(:standard);

my $sequence = "";

# read data from our data.txt file (with our own demo sequence)
open( INFILE, "data.txt");
                while(<infile>){
                                my $line = $_;
                                chomp $line;
                                $sequence = $sequence . $line;
                }
close(INFILE);


# create a CGI object in order to create the HTML file
my $q = new CGI;


# read the parameters sent thru the form and do necessary initializations
my $new_seq = $q->param("sequence") || "No Sequence";

$new_seq =~ s/[\s\n\t]+//g unless $new_seq =~ /No Sequence/;
$new_seq = "No Sequence" if $new_seq =~ /[^AaCcTtGg]/;
$sequence = $new_seq unless $new_seq =~ /No Sequence/ ;
$sequence = uc $sequence;

# define the monomers
my $aw_monomers = { 'A' => [0], 'G' => [0], 'C' => [0], 'T' => [0] };

# start printing the HTML file
print $q->header();

# print the sequence that has been pasted
$q->print("<html><head><title>Sequence Results </title></head><body onLoad='javascript:focus()'>");
$q->print("<table border=0 cellpadding=3 cellspacing=2 width=\"700\"><tr width='650'><td width=\"650\">");

my $pp = $sequence;
$pp =~ s/(\w{40})/$1\n/g;
$q->print("$pp<br>\n");
undef $pp;
$q->print("</td></tr></table>");

# parameters initialization
my $no_of_As_and_Ts = 0;
my $no_of_Cs_and_Gs = 0;

#compute the requested parameters
for( my $i=0; $i<$size; $i++){
                my $base = substr( $sequence, $i, 1 );

                $aw_monomers->{$base}->[0]++ if defined $aw_monomers->{$base};
}

# print the monomers
&showMonomers($aw_monomers);

# close the HTML file
$q->print("</body></html>");


#__subs__#

sub showMonomers{
                my $aw_monomers = shift;

                foreach my $monos (sort keys %$aw_monomers){
                        $q->print("$monos\t $aw_monomers->{$monos}->[0]<br>\n");
                };

                $no_of_As_and_Ts = $aw_monomers->{'A'}->[0] + $aw_monomers->{'T'}->[0];
                $no_of_Cs_and_Gs = $aw_monomers->{'G'}->[0] + $aw_monomers->{'C'}->[0];

                my $ratio_of_As_and_Ts = sprintf("%d.02%d", 100 * $no_of_As_and_Ts / $size);
                my $ratio_of_Cs_and_Gs = sprintf("%d.02%d", 100 * $no_of_Cs_and_Gs / $size);

                $q->print("The number of As and Ts is: $no_of_As_and_Ts<br>\n");
                $q->print("The number of Cs and Gs is: $no_of_Cs_and_Gs<br>\n");
                $q->print("The ratio of As and Ts is: $ratio_of_As_and_Ts%<br>\n");
                $q->print("The ratio of Cs and Gs is: $ratio_of_Cs_and_Gs%<br>\n");

                return;
}