#!/usr/bin/perl  

#make bkup of old
`mv -f public_data.xml public_data.xml.bkup;`;

open(PUBLIC_DATA, ">public_data.xml"); 

print("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
print("<?xml-stylesheet type=\"text/xsl\" href=\"http://regis-web.systemsbiology.net/data3/search/public_data/public_data.xsl\"?>\n");

#Get Directories
@dirs = </data3/search/public_data/*>;
$prefix = "/data3/search/public_data";
print("<public_datasets>\n");

foreach $dir (@dirs) {

	if (-d $dir) {

		#MAKE DATA 'BOX'
		$dir =~ m/.*\/(.*)/;
		$title = $1;
		$title =~ s/_/ /;

		#GET TITLE FROM title FILE
		if (-e "$dir/title") {
			open(TITLE, "$dir/title");
			@content = <TITLE>;
			close(TITLE);
			$title = $content[0];
			chomp($title);
		}
		$dir =~ m/$prefix(.*)/;
		$url = $1;
		
		print (" <category title=\"$title\" url=\"$url\">\n");

		#GET DATASET DIRECTORIES
		@datasets = <$dir/*>;		

		foreach $dataset (@datasets) {

			if (-d $dataset) {
				$dataset =~ m/.*\/(.*)/;
				$title = $1;
				$title =~ s/_/ /;
				print("  <dataset title=\"$title\">\n");
				
				@instruments = <$dataset/*>;

				foreach $instrument (@instruments) {
					if (-d $instrument) {
						$instrument =~ m/.*\/(.*)/;
						print("    <instrument name=\"$1\">\n");
						
						#ARCHIVES
						@archives = <$instrument/*.tar.gz>;
						foreach $archive (@archives) {
							print("     " . printArchive($archive) . "\n");
						}
						
						print("    </instrument>\n");
					}
				}
				print("  </dataset>\n"); 	
			} #end is dataset
		}
		print (" </category>\n");
	} #end is dir
}

print("</public_datasets>\n\n");

sub printArchive {
	$path = shift();
	#GET DATA TYPE OF ARCHIVE
	$type = "undefined";
	if ($path =~ m/.*ALL.tar.gz/) {
		$type = "all";
	}
        elsif ($path =~ m/.*RAW_Data.tar.gz/) {
                $type = "raw";
        }
        elsif ($path =~ m/.*mzXML.tar.gz/) {
                $type = "mzXML";
        }
        elsif ($path =~ m/.*Search_Results.tar.gz/) {
                $type = "search_results";
        }
        
	$path =~ m/.*\/(.*)/;
	$name = $1;
	$size = -s $path;
	$path =~ s?$prefix??;
	$retval = "<archive name=\"$name\" type=\"$type\" url=\"$path\" size=\"$size\"/>";
	return $retval;
}




