#!/usr/bin/perl  

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

#clean up empty archive files

print("CLEANING UP EMPTY TAR.GZs...\n");
@tars = `find . -iname "*.tar.gz"`;
foreach $tar (@tars) {
	chomp($tar);
	#remove files less than 1K
	if (-s $tar < 1000) {
		print("REMOVING $tar...\n");
		`rm -f $tar;`;
	}
}

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

print(PUBLIC_DATA "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
print(PUBLIC_DATA "<?xml-stylesheet type=\"text/xsl\" href=\"http://regis-web.systemsbiology.net/PublicDatasets/public_data.xsl\"?>\n");
#print(PUBLIC_DATA "<?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_DATA "<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(PUBLIC_DATA " <category title=\"$title\" url=\"$url\">\n");

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

		foreach $dataset (@datasets) {

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

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

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

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;
}




