#! /usr/bin/perl -w

##### Program description #######
#
# Title:     cgi3.pl
# Author(s): Mattias Ohlsson
# Description:
#   Small example of how to use the CGI module.
#
##################################

use CGI;
use strict;

my $cgi = new CGI;

print $cgi->header,
    $cgi->start_html(-title=>'A Simple Example'),
    $cgi->h1('Amino Acid Frequencies'),
    $cgi->start_form,
    "Enter or paste an amino-acid sequence? ",
    $cgi->p,
    $cgi->textarea(-name=>'name', rows=>10, columns=>30),
    $cgi->p,
    $cgi->submit,
    $cgi->end_form,
    $cgi->hr;

if ( $cgi->param() ) {
    my $seq = $cgi->param('name');
    Count($seq);
}
print $cgi->end_html();


sub Count {
    my ($seq) = @_;

    my %amino = (
	'Ala','A',  'Cys','C',  'Asp','D',  'Glu','E',
	'Phe','F',  'Gly','G',  'His','H',  'Ile','I',
	'Lys','K',  'Leu','L',  'Met','M',  'Asn','N',
	'Pro','P',  'Gln','Q',  'Arg','R',  'Ser','S',
	'Thr','T',  'Val','V',  'Trp','W',  'Tyr','Y');
    my @amino_keys = keys %amino;

    # Make it into an array
    my @seq2 = split //, $seq;
    my $len = scalar @seq2;

    my %count;
    foreach my $aa ( @seq2 ) {
        chomp $aa;
        $count{uc($aa)} += 1;
    }
    print "Frequencies for the different amino acids", $cgi->br;
    foreach my $aa ( @amino_keys ) {
        my $oneletter = $amino{$aa};
        if ( exists $count{$oneletter} ) {
            my $frac =  100.0 * $count{$oneletter} / $len;
            print $cgi->em($aa);
            printf ": %5.2f%", $frac;
            print $cgi->br;
        }
    }
    
} # End of Count 
