<?xml version="1.0" encoding="UTF-8"?>
<maxdQL version="0.1" name="GEOsample" >
	<description>Will describe an sample in softSOFTtext format</description>

	<arguments type="user">
		<var 
			name="MeasurementName" 
			comment="the name of the measurement you want to export" 
		/>
		<var 
			name="ValueColumn"
			comment="the column in the properties that will be made a GEO VALUE column"
		/>
		
		
	</arguments>
	
	<pfunction id="getLEid1" comment="returns the ids of 2 labelled extracts" method="text" >
		<![CDATA[
			// assumes there is only one original linked entry... shoddy!
			foreach ($input as $originalEntryID => $linkResult)
			{
				$keys = array_keys($linkResult["LabelledExtract"]["Name"]);				
				$output = $keys[0];
			} 
		]]>
	</pfunction>
	
	
	<pfunction id="getLEid2" comment="returns the id of the first labelled extract" method="text" >
		<![CDATA[
			 // assumes there is only one original linked entry... shoddy!
			foreach ($input as $originalEntryID => $linkResult)
			{
				$keys = array_keys($linkResult["LabelledExtract"]["Name"]);				
				$output = $keys[1];
			}
		]]>
	</pfunction>
	
	 
	<pfunction id="header" comment="this prints the platform header" method="text" >
		<![CDATA[
			
			
			// the next 3 loops again assume that link result 
			// has been generated from only one entry... super shoddy!
			
			foreach ($input as $linkID => $linkResult)
			{
				$allResultsSoFar[] = $linkResult;
			}
			
			foreach ($this->results[2] as $linkID => $linkResult)
			{
				$allResultsSoFar[] = $linkResult;
			}
			
			foreach ($this->results[3] as $linkID => $linkResult)
			{
				$allResultsSoFar[] = $linkResult;
			}
			
			
			
			$map = array (
				"!Sample_title" => "Measurement.Name",
				"!Sample_supplementary_file" => "Measurement.Data URL" ,
		
				"!Sample_source_name_ch" => "Source.Name",
				"!Sample_organism_ch" => "Source.Organism.Standard Ontology.Value",
				"!Sample_characteristics_ch" => "Source.Description",
				"!Sample_biomaterial_provider_ch" => "Source.Provider.Organisation",
				"!Sample_treatment_protocol_ch" => "TreatmentProtocol.Name",
				"!Sample_growth_protocol_ch" => "SamplingProtocol.Name",
				"!Sample_molecule_ch" => "Extract.Material Type",
				"!Sample_extract_protocol_ch" => "Extract.Name",
				"!Sample_label_ch" => "LabelledExtract.Labelling Compound",
				"!Sample_label_protocol_ch" => "LabellingProtocol.Description",
				
				"!Sample_hyb_protocol" => "HybridisationProtocol.Description",
				"!Sample_scan_protocol" => "ScanningProtocol.Description",
				"!Sample_data_processing" => "ImageAnalysisProtocol.Description",
				"!Sample_description" => "Measurement.Description",
				
				"!Sample_platform_id" => "ArrayType.Name",
				
			);
			
			
			
			// note only obvious equivalents are translated here... 
			// or else the value will be kept as in maxdLoad2
			$translations = array (
				"!Sample_molecule_ch" => array (
					"total_RNA" => "total RNA",
					"polyA_RNA"  => "polyA RNA",
					"cytoplasmic_RNA"  => "cytoplasmic RNA",
					"nuclear_RNA"  => "nuclear RNA",
					"genomic_DNA" => "genomic DNA",
					"protein" => "protein",
					"*"  => "other"
				)
				
			);
			
			function myunicode2ascii ($attributeval) {
		
				$attributeval = str_replace("\u000A", "\t", $attributeval);
				$attributeval = str_replace("\u00D0", "\t", $attributeval);
				$attributeval = str_replace("\u0009", "\t", $attributeval);
				$attributeval = str_replace("\u0020", " ", $attributeval);
				$attributeval = str_replace("\u00B5", "µ", $attributeval);
				$attributeval = str_replace("\u00BA", "º", $attributeval);
				$attributeval = str_replace("\u00EB", "ë", $attributeval);
				$attributeval = str_replace("\u00E6", "æ", $attributeval);
				return ($attributeval);
			}
			
			
			
			
			
			$string = "^SAMPLE = $MeasurementName";
			
			$found = array();
				
			foreach ($allResultsSoFar as $resultNum => $resultSoFar)
			{
				//print "\n".$resultNum;
				foreach ($resultSoFar as $table => $columns)
				{
					//print "\n" . $table;
					foreach ($columns as $colName => $col)
					{
						// i don't think you need to strip the -> because 
						// only Names and Attributes needed...
						
						//$colNameStripped = str_replace ("<-","",$colName);
						//$colNameStripped = str_replace ("->","",$colNameStripped);
						//print "\n\t" . $colNameStripped;
						
						$mapKey = "";
						if (in_array ($colName, $map) )
						{
							$mapKey = array_search ($colName, $map);
							$mapValue = $colName;
							//print "\n$mapKey\t" . $colName;
						} elseif (in_array ($table . "." . $colName, $map) ) 
						{
							$mapKey = array_search ($table . "." . $colName, $map);
							$mapValue = $table . "." . $colName;
							//print "\n$mapKey\t" . $table . "." . $colName;
						}
						
						if (strlen($mapKey) > 0) 
						{
							if (! isset($found[$mapKey][$mapValue]) ) {
								foreach ($col as $rkey => $row)
								{	
									$rowUni = myunicode2ascii($row);
									if ($mapKey == "!Sample_molecule_ch") {
										$rowUni = $translations	["!Sample_molecule_ch"][$rowUni];
									}
									if ($resultNum == 0)
									{
										$string .= "\n$mapKey = $rowUni";
									} else {
										$string .= "\n$mapKey$resultNum = $rowUni";
									}
								}
							}
						}
						
					}
				}
			
			}
			//print "\n";
			
			
		$output = $string;
		
		]]>
	</pfunction>
	
	<pfunction id="enumerateHeader" comment="prints the column metadata for the header" method="text" >
		<![CDATA[	
			//print "---" ;print_r($input);die();
			
			$keys = array_keys($input);
			$keyName = $keys[0];
			
			$string = "";
			foreach ($input[$keyName]["Column_Type"] as $typeID => $columnType)
			{
				
				if ($columnType == "Feature_ID")
				{
					$title = "ID_REF";
				} elseif ($columnType == $ValueColumn) {
					$title = "VALUE";
				} else {
					$title = $columnType;
				}
			
				$string .= "\n# $title = ";
				$separator = "";
				foreach ($input[$keyName] as $colName => $col)
				{

					$string .= "$separator $colName : $col[$typeID]";
					$separator = ",";
				}
			
			}
			//print $string;die();
			$output = $string;
		]]>
	</pfunction>
	
	<pfunction id="enumerateTabber" comment="formats the enumeration" method="text" >
		<![CDATA[
			//print_r($input);die();

			$keys = array_keys($input);
			$keyName = $keys[0];
			
			$featureKeys = array_keys($input[$keyName]["Feature"]);
			
			$tab = "";
			$string = "\n!sample_table_begin\n";
			foreach ($input[$keyName] as $colName => $column)
			{
				// change Feature to ID
				if ($colName == "Feature_ID")
				{
					$title = "ID_REF";
				} elseif ($colName == $ValueColumn) {
					$title = "VALUE";
				} else {
					$title = $colName;
				}
				$string .= $tab . $title;
				$tab = "\t";
			}
			
			
			foreach ($featureKeys as $featureID )
			{
				$string .= "\n" ; // . $featureID;
				$tab = "";
				foreach ($input[$keyName] as $colName => $column)
				{
					$string .= $tab . $column[$featureID];
					$tab = "\t";
				}
			}
			$string .= "\n!sample_table_end\n";
			
			$output = $string;
			
			
		]]>
	</pfunction>
		
	
	<query id="1" 
	       name="LinkMeasurementToLabelledExtract" 
	       comment="get the labelled extracts related to the measurement" 
	       type="maxdBrowse"
	       >
		<names uref="user" name="MeasurementName"  />
		<action>link</action>
		<table>Measurement</table>
		<desiredTable>LabelledExtract</desiredTable>
		<linkVersion>02</linkVersion>
		<format>array</format>
		<attributes>yes</attributes>
	</query>
	
	
	<query
		id="2" 
		name="LinkLabelledExtract1" 
		comment="get all the information related to the 1st labelled extract" 
		type="maxdBrowse"
	      >
		<ids pref="getLEid1" processResultID="1" />
		<action>link</action>
		<table>LabelledExtract</table>
		<desiredTable>Source,LabellingProtocol,ExtractionProtocol,TreatmentProtocol,SamplingProtocol</desiredTable>
		<format>array</format>
		<linkVersion>02</linkVersion>
		<attributes>yes</attributes>
	</query>
	
	
	
	<query
		id="3" 
		name="LinkLabelledExtract2" 
		comment="get a,, the information related to the 2nd labelled extract" 
		type="maxdBrowse"
	      >
		<ids pref="getLEid2" processResultID="1" />
		<action>link</action>
		<table>LabelledExtract</table>
		<desiredTable>Source,LabellingProtocol,ExtractionProtocol,TreatmentProtocol,SamplingProtocol</desiredTable>
		<format>array</format>
		<attributes>yes</attributes>
		<linkVersion>02</linkVersion>
	</query>
	
		 
	<query
		id="4" 
		name="LinkMeasurementToEverythingElse" 
		comment="get all the other information related to the measurement" 
		type="maxdBrowse"
	      >
		<names uref="user" name="MeasurementName"  />
		<action>link</action>
		<table>Measurement</table>
		<desiredTable>ImageAnalysisProtocol,ScanningProtocol,HybridisationProtocol,ArrayType</desiredTable>
		<linkVersion>02</linkVersion>
		<format>array</format>
		<attributes>yes</attributes>
	</query>
	
	<query
		id="5" 
		name="EnumerateMetadata" 
		comment="get enumeration metadata" 
		type="maxdBrowse"
	      >
		<names uref="user" name="MeasurementName"  />
	    <action>enumerate</action>
	    <table>Measurement</table>
	    <format>array</format>
	</query>
	
	<query
		id="6" 
		name="EnumerateMetadata" 
		comment="get enumeration metadata" 
		type="maxdBrowse"
	      >
		<names uref="user" name="MeasurementName"  />
	    <action>enumerate</action>
	    <table>Measurement</table>
	    <format>array</format>
	    <types>*</types>
	    <spots>Feature</spots>
	</query>
	
	<query 
		id="7" 
	       name="final report" 
	       comment="pools results together" 
	       type="export" 
	       format="text" 
	       >
		
		

		<sampleHeader pref="header" processResultID="4" >
			<var uref="user" name="MeasurementName" />
		</sampleHeader>
		
		<enumerateMetadataHeader pref="enumerateHeader" processResultID="5" >
			<var uref="user" name="ValueColumn" />
		</enumerateMetadataHeader>
		
		<enumerate pref="enumerateTabber" processResultID="6" >
			<var uref="user" name="ValueColumn"  />
		</enumerate>
		 
	</query>
	
</maxdQL>

