#!/usr/bin/perl -w 

use strict;
use warnings;
use lib '/home/s171333/.cpan/modules/lib/perl5/site_perl/5.8.5';
require LWP::UserAgent;
 
 my $ua = LWP::UserAgent->new;
 $ua->agent("$0/0.1 " . $ua->agent);

#Module
use DBI;
# defining global variables
my %species_domstruct_hoa;
# DB definitions and connection
my $dbh=DBI->connect('DBI:Pg:dbname=smart_new;host=wbbi105','s171333', 'PinkY');
# Fehler beim Verbinden?
die $DBI::errstr unless $dbh;
my $sth = $dbh->prepare("select t.name, r.domstruct from red_domstruct_lcaid_ensembl_all as r, tree as t where t.id=r.lcaid and t.rank ='species' group by t.name,r.domstruct;");
	$sth->execute;
	while ((my @row) = $sth->fetchrow_array) {
		my $species = $row[0];
		$species =~s/ /_/g;
		push @{$species_domstruct_hoa{$species}},$row[1];
	}
	$sth->finish;



#create protein
for my $key (sort keys %species_domstruct_hoa) {
	my $i=1;
	system("mkdir $key");
	# index.html
	open( OutID, ">$key/index.htm" );
	print OutID "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN", "\n";
	print OutID "\"  http://www.w3.org/TR/html4/transitional.dtd\">", "\n";
	print OutID "<html>", "\n";
	print OutID "<head>", "\n";
	print OutID "<title>$key</title>", "\n";
	print OutID "</head>", "\n";
	print OutID "<h2>architectures invented in $key</h2>", "\n";
	print OutID "<h6>red squares stand for ZnF_Gen</h6>", "\n";
	print OutID "<body>", "\n";
	while (scalar(@{$species_domstruct_hoa{$key}}) > 0) {
		my $protein = shift @{$species_domstruct_hoa{$key}};
#		print $protein,"\n";
		my $search;
		my $count=25;
		my @domains = split(/ /,$protein);
		for my $dom (@domains) {
			my $count2 = $count+150;
			$search .= "$dom"."($count|$count2)+";
			$count +=160;
			#unless (length @domains == 0) {$search .= "+"}
		}
		$count +=25;
		$search = $count.":".$search;
		print $search,"\n";
		my $req = HTTP::Request->new(GET => "http://smart.embl-heidelberg.de/smart/DD2.cgi?smart=$search");
		 # Das Ergebnis in der Datei fullsize.jpg lokal speichern
		 my $res = $ua->request($req, "$key/$i.png");				 
		if ($res->is_success) { 
		       # Hier ist alles ok 
		       #print "Protein $i \n";
		       print OutID"<img src=\"$i.png\" alt=\"$protein\"><br>", "\n";
		       $i++;
		} else { 
		       # und hier ist etwas faul im Staate Dänemark.
		       print $res->status_line, "\n";
		 }	
	}
	print OutID "</body>", "\n";
	print OutID "</html>", "\n";
	close(OutID);
}
exit;