<?php
include ("connection.php");
include ("frames_header.php");
?>

<?php

if (isset($_POST["download"]))
	$download=$_POST["download"];
else $download='n';



// the 3 first letters of the UNIGENE species files
// now it's the species
if (isset($_POST["initial"]))
	$init=$_POST["initial"];
else 
{
	echo "<strong>Error :</strong> You must specify the species for the files to download. ex : Ciona intestinalis<br>";
	include ("Frames_footer.php");
	return;
}



function uncompress($fromFile, $toFile) 
{
   $zp = @gzopen($fromFile, "r");
   $fp = @fopen($toFile, "w");
   while(!@gzeof($zp)) {$string = @gzread($zp, 4096); @fwrite($fp, $string, strlen($string));}
   @gzclose($zp);
   @fclose($fp);
}

// if you want to know the client OS
$os=getenv("OS");


if ($download=='y')
{
	$ftp_server="ftp.ncbi.nih.gov";
	$conn_id = ftp_connect($ftp_server); 
	$ftp_user_name = "anonymous";
	$ftp_user_pass = "guest@all.com";
	$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); 

	if ((!$conn_id) || (!$login_result)) { 

   		echo "ftp connection  failed!<br>";
   		//echo "Trying to connect to $ftp_server <br>";
       	die;
   	} 
	else {
       	echo "<br> Connection to $ftp_server :DONE <br>";
	}
	
	/*
	$contents = ftp_nlist($conn_id, "./repository/UniGene");
	print_r($contents);
	*/
	
//Rajout pour la nouvelle config du FTP
$init=str_replace(" ","_",$init);
//print $init;

	if (! ftp_chdir($conn_id, "./repository/UniGene/$init/")) 
	{ 
   		echo "ERROR.\n";
	}
	$contents = ftp_nlist($conn_id, ".");
	//print_r($contents);
	for ($i=0; $i<count($contents); $i++)
	{
	//print $contents[$i]."<br>";
		if (ereg("gz$", $contents[$i], $tabname ))
		{
		print $contents[$i];
			//if ((!file_exists("./Unigene/".$tabname[1])) or (ftp_mdtm ($conn_id,"./".$contents[$i]) > filemtime("./Unigene/".$tabname[1])))
			//{
				//echo "<br>find :::::: $contents[$i]<br>";
				//echo "nom fichier : $tabname[1]";
				$local_file = "./Unigene/".$contents[$i];
				$server_file = "./".$contents[$i];
								
				if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) 
				{
	   				echo "file dowloaded: /Unigene/$contents[$i]<br>";
				} 
				else 
				{
	   				echo "ERROR<br>";
	   			}
	   			
	   			//uncompress("./Unigene/".$tabname[1].".gz", "./Unigene/".$tabname[1]);
				$newfile=str_replace(".gz","",$contents[$i]);
				uncompress("./Unigene/".$contents[$i], "./Unigene/$newfile");
				
				if(filesize("./Unigene/$newfile")<=0)
				{
					echo "Bad uncompressed GZ file";
					include("frames_footer.php");
					return;
				}
				else
				{
					unlink("./Unigene/".$contents[$i]);
				}

			//}
			//else
			//{
			//	echo "The unigene file is already up to date<br>";
			//}		
				
		}
	}	

}


	
?>

<?php
include ("frames_footer.php");
?>

