<?php
/**
 * @class ParamsInfoMgr 
 * @version  $Id: ParamsInfoMgr.php 2780 2015-02-26 12:02:37Z elena $
 * 
 */

 class ParamsInfoMgr {
 		protected $derivedParamMgr, $mydataParamMgr, $mySimuParamMgr;
 		
 		protected $missionDom, $localDom, $internalDom;
 		
 		protected $ddLocalMissionXPath;
 	
   function __construct() {
     $this->ddLocalMissionXPath = array();
   }

    /*
    * Get all info for a given REMOTE THEMIS parameter
    */
   public function getRemoteThemisParamInfo($param) {
    
         $info = array();

         if (sscanf($param,"%[^'('](%d:%d)",$par,$cstart,$cstop) == 3)
         {
                 $comp_start = $cstart;
                 $comp_stop  = $cstop;
         }
         else if (sscanf($param,"%[^'('](%d)",$par,$cstart) == 2)
         {
                 $comp_start = $cstart;
                 $comp_stop  = $cstart;
         }
         else
           $par = $param;  
           
         $paramXML = new DomDocument("1.0");
         if (!$paramXML->load(RemoteData."THEMIS/base.xml")) return null;
           
    
         $paramID =  $paramXML->getElementById($par);
         if($paramID  == null ) return null;
        
         $parent =  $paramID ->parentNode;
       
         $vi = $parent->getAttribute('xml:id'); 

         $info['base'] = '';
         $info['vi'] = $vi;
         
         return $info;

   }

    /*
    * Get all info for a given REMOTE parameter
    */
   public function getRemoteParamInfo($param) {
         
         if (substr($param,0,2) == 'th')
              return $this->getRemoteThemisParamInfo($param);
    
         $info = array();

         $ParamFile = RemoteData.'PARAMS/'.$param.'.xml';
         if (!file_exists($ParamFile)) return null;
                      
         $paramXML = new DomDocument("1.0");
         if (!$paramXML->load($ParamFile)) return null;

         $fieldname =  $paramXML->getElementsByTagName('paramID');
         if($fieldname->length == 0 ) return null;
         
         $base = $paramXML->getElementsByTagName('baseID'); 
         $vi = $paramXML->getElementsByTagName('viID'); 

         $info['base'] = $base->length == 0 ? 'undefined' :  $base->item(0)->nodeValue;
         $info['vi'] = $vi->length == 0 ? 'undefined' :  $vi->item(0)->nodeValue;

         $info['title'] =  $fieldname->item(0)->nodeValue;
 
         return $info;

   }

   /*
    * Get all info for a given parameter
    */
   public function GetParamInfo($param)
   { 
       // to correct 'restricted' parameters  
        if (strpos($param, restricted) !== false) {
             $param = str_replace(restricted,"",$param);  
        }  

        //get components
   	 if (sscanf($param,"%[^'('](%d:%d)",$par,$cstart,$cstop) == 3)
   	 {
   	 	 $comp_start = $cstart;
   	 	 $comp_stop  = $cstop;
   	 }
   	 else if (sscanf($param,"%[^'('](%d)",$par,$cstart) == 2)
   	 {
   	 	 $comp_start = $cstart;
   	 	 $comp_stop  = $cstart;
   	 }
   	 else
   	   $par = $param;

   	 if (strncmp(strtolower($par), 'ws_', 3) == 0)
   	  return $this->GetDerivedParamInfo(substr($par,3),$comp_start,$comp_stop);
   	 else if (strncmp(strtolower($par), 'wsd_', 4) == 0)
   	   return $this->GetMyDataParamInfo(substr($par,4),$comp_start,$comp_stop);
   	 else if (strncmp(strtolower($par), 'spase_', 6) == 0)
   	   return $this->GetSimuDataParamInfo($par,$comp_start,$comp_stop);

   	 return $this->GetLocalParamInfo($par,$comp_start,$comp_stop);
   }
   
   /*
    * Get a full list of available missions (only missions with the status 'required') that come from Mission.xml file
    */
   public function GetMissionsList()
   {
   	 if (!$this->missionDom)
   	 {
   	 	 $this->missionDom = new DomDocument("1.0");
    	  if (!$this->missionDom->load(missionXml))
    	    return array('success' => false, 'message' => 'Cannot load missions file');
   	 }
   	 
   	 $missions = $this->missionDom->getElementsByTagName('MissionID');
   	 
   	 $missions_array = array('success' => true);
   	 
   	 foreach ($missions as $mission)
   	 {
//    	   if ($mission->getAttribute('status') != 'required')
//    	     continue;	
   	   $id    = $mission->nodeValue;
   	   $group = $mission->getAttribute('group');
   	   $missions_array[$id] = array("group" => $group);
   	 }
   	 
   	 return $missions_array;
   }
   
   /*
    * Extract sub mission info from a node (DD_*.xml file)
    */
   private function ExtractDDSubMissionInfoFromNode($node)
   {
        $name  = $node->getAttribute('name');
        $desc  = $node->getAttribute('desc');
        $help  = $node->getAttribute('attention');
        $class = $node->getAttribute('class');
   	if ($node->hasAttribute('xml:id')) {
                   $id = $node->getAttribute('xml:id');
        }
        else {
           $tmp =  explode("@",$name);
           $id = $tmp[0];
        } 
 
   	 return array(
   	   "name"  => $name,
   	   "desc"  => $desc,
   	   "help"  => $help,
   	   "class" => $class,
           "id"    => $id
   	 );
   }
   
   /*
    * Extract instrument info from a node (DD_*.xml file)
    */
   private function ExtractDDInstrumentInfoFromNode($node)
   {
     $name   = $node->getAttribute('name');
   	 $desc   = $node->getAttribute('desc');
   	 $help   = $node->getAttribute('attention');
   	 $id     = $node->getAttribute('xml:id');
   	 $refURL = $node->getAttribute('refURL');
   	 
   	 $alternatenode = $node->getElementsByTagName('alternateName');
   	 $alt = array();
   	 foreach ($alternatenode as $a)
   	   array_push($alt,$a->nodeValue);
   	   
   	 $classnode = $node->getElementsByTagName('class');
   	 $class = array();
   	 foreach ($classnode as $c)
   	   array_push($class,$c->nodeValue);
   	   
   	 $pinode = $node->getElementsByTagName('pi');
   	 $pi = ($pinode->length > 0) ? $pinode->item(0)->nodeValue : '';
   	 
   	 return array(
   	   "name"          => $name,
   	   "desc"          => $desc,
   	   "help"          => $help,
   	   "pi"            => $pi,
   	   "id"            => $id,
   	   "refURL"        => $refURL,
   	   "alternamename" => $alt,
   	   "class"         => $class
   	 );
   }
   
   /*
    * Extract parameter info from a node (DD_*.xml file)
    */
   private function ExtractDDDatasetInfoFromNode($node)
   { 
     $id   = $node->getAttribute('xml:id');
   	 $name = $node->getAttribute('name');
   	 $help = $node->getAttribute('attention');
   	 $sampnode = $node->getElementsByTagName('sampling');
   	 $min_samp = ($sampnode->length > 0) ? $sampnode->item(0)->nodeValue : '0';
   	 $sampnode = $node->getElementsByTagName('maxSampling');
   	 $max_samp = ($sampnode->length > 0) ? $sampnode->item(0)->nodeValue : $min_samp;
   	 $startnode = $node->getElementsByTagName('dataStart');
   	 $start = ($startnode->length > 0) ? $startnode->item(0)->nodeValue : '1970/01/01';
   	 $stopnode = $node->getElementsByTagName('dataStop');
   	 $stop = ($stopnode->length > 0) ? $stopnode->item(0)->nodeValue : '1970/01/01';
   	 $sourcenode = $node->getElementsByTagName('dataSource');
   	 $source = ($sourcenode->length > 0) ? $sourcenode->item(0)->nodeValue : '';
   	 
   	 $infonode = $node->getElementsByTagName('info');
   	 $infonode = ($infonode->length > 0) ? $infonode->item(0) : NULL;
   	 
   	 $title = '';
   	 $des   = '';
   	 $creator = '';
   	 $calibration = '';
   	 $subject = array();
   	 $contributor = array();
   	 $target = array();
   	 
   	 if (isset($infonode))
   	 {
   	 	 $titlenode = $infonode->getElementsByTagName('title');
   	 	 $title = ($titlenode->length > 0) ? $titlenode->item(0)->nodeValue : '';
   	 	 
   	 	 $desnode = $infonode->getElementsByTagName('description');
   	 	 $des = ($desnode->length > 0) ? $desnode->item(0)->nodeValue : '';
   	 	 
   	 	 $creatornode = $infonode->getElementsByTagName('creator');
   	 	 $creator = ($creatornode->length > 0) ? $creatornode->item(0)->nodeValue : '';
   	 	 
   	 	 $calibrationnode = $infonode->getElementsByTagName('calibration');
   	 	 $calibration = ($calibrationnode->length > 0) ? $calibrationnode->item(0)->nodeValue : '';
   	 	 
   	 	 $subjectnode = $infonode->getElementsByTagName('subject');
   	 	 foreach ($subjectnode as $s)
   	     array_push($subject,$s->nodeValue);
   	     
   	   $contributornode = $infonode->getElementsByTagName('contributor');
   	 	 foreach ($contributornode as $c)
   	     array_push($contributor,$c->nodeValue);
   	     
   	   $targetnode = $infonode->getElementsByTagName('target');
   	 	 foreach ($targetnode as $t)
   	     array_push($target,$t->nodeValue);
   	 }
   	 
   	 return array(
   	   "id"          => $id,
   	   "name"        => $name,
   	   "help"        => $help,
   	   "minsampling" => $min_samp,
   	   "maxsampling" => $max_samp,
   	   "starttime"   => $start,
   	   "stoptime"    => $stop,
   	   "source"      => $source,
   	   "title"       => $title,
   	   "description" => $des,
   	   "creator"     => $creator,
   	   "calibration" => $calibration,
   	   "subject"     => $subject,
   	   "contributor" => $contributor,
   	   "target"      => $target
   	 );
   }
   
   /*
    * Extract parameter info from a node (DD_*.xml file)
    */
   private function ExtractDDParameterInfoFromNode($node, $comp_start = NULL, $comp_stop = NULL)
   { 
   	 $units = $node->getAttribute('units');
     $display_type = $node->getAttribute('display_type');
   	   
   	 $components = $node->getElementsByTagName('component');
   	 
   	 //additionals info
     $infonode = $node->getElementsByTagName('info');
   	 $infonode = ($infonode->length > 0) ? $infonode->item(0) : NULL;
   	 
   	 $des = "";
   	 $ucd = "";
   	 $type = "";
   	 	 
   	 if (isset($infonode))
   	 {
   	 	 $desnode = $infonode->getElementsByTagName('description');
   	 	 $des = ($desnode->length > 0) ? $desnode->item(0)->nodeValue : '';
   	 	 
   	 	 $ucdnode = $infonode->getElementsByTagName('ucd');
   	 	 $ucd = ($ucdnode->length > 0) ? $ucdnode->item(0)->nodeValue : '';
   	 	 
   	 	 $typenode = $infonode->getElementsByTagName('type');
   	 	 $type = ($typenode->length > 0) ? $typenode->item(0)->nodeValue : '';
   	 	 
   	 }
   	 
   	 //size of the full parameter
   	 if ($node->getAttribute('size') != '')
   	   $fullsize = intval($node->getAttribute('size'));
   	 else
   	 {
   	   if ($components->length > 0)
   	     $fullsize = $components->length;
   	   else
   	     $fullsize = 1;
   	 }
   	     
   	 //get all components labels
   	 $comps_all_labels = array();
   	 if ($fullsize > 1)
   	 {
   	   if (($fullsize != $components->length)&& ($name !=''))
   	   {
   	 	   for ($i = 0; $i < $fullsize; $i++)
   	 	     $comps_all_labels[] = $name.'_'.$i;
   	   }
   	   else
   	   {
   	   	 $i = 0;
   	 	   foreach ($components as $comp)
   	 	   {
   	 	 	   $comps_all_labels[] = $comp->getAttribute('name');
   	 	     $i++;
   	 	   }
   	   }
   	 }
   	   
   	 //real size 	 
   	 if (isset($comp_start))
   	 {
   	 	 if (isset($comp_stop) && ($comp_start != $comp_stop))
   	 	   $size = $comp_stop - $comp_start;
   	 	 else
   	 	 {
   	 	   $size = 1;
   	 	   $comp_stop = $comp_start;
   	 	 }
   	 }
   	 else
   	 {
   	 	 $comp_start = 0;
   	 	 $comp_stop = $fullsize-1;
   	   $size = $fullsize;
   	 }
   	   
   	 if ($size != $fullsize)
   	 {
   	 	 if ($size == 1)
   	 	 {
   	 	 	 $id    = $node->getAttribute('xml:id')."_".$comp_start;
   	     $name  = $comps_all_labels[$comp_start];
   	 	 }
   	 	 else
   	 	 {
   	 	 	 $id    = $node->getAttribute('xml:id')."_".$comp_start."_".$comp_stop;
   	 	 	 $name  = $node->getAttribute('name')."_".$comp_start."_".$comp_stop;
   	 	 	 $comps_label = "";
   	 	 	 for ($i = $comp_start; $i <= $comp_stop; $i++)
   	 	 	 {
   	 	 	 	 if ($i != $comp_start)
   	 	 	 	   $comps_label .= " ";
   	 	 	 	 $comps_label .= $comps_all_labels[$i];
   	 	 	 }
   	 	 }
   	 }
   	 else
   	 {
   	 	 $name = $node->getAttribute('name');
   	 	 $id   = $node->getAttribute('xml:id');
   	 	 $comps_label = "";
   	   for ($i = 0; $i < $size; $i++)
   	 	 {
   	 	 	 if ($i != 0)
   	 	 	   $comps_label .= " ";
   	 	 	 $comps_label .= $comps_all_labels[$i];
   	 	 }
   	 }
   	 
   	 return array(
                "id"   => $id,
                "name"  => $name,
                "units" => $units,
                "size" => $size,
                "display_type" => $display_type,
                "comps_label" => $comps_label,
                "description" => $des,
                "ucd" => $ucd,
                "type" => $type
   	 );
   }
   

   
   /*
    * Get the DD_*.xml XPath from a mission id
    */
   public function GetDDMissionXPath($mission_id)
   {
   	 if ($this->ddLocalMissionXPath[$mission_id])
   	   return $this->ddLocalMissionXPath[$mission_id];
   	   
   	 $mission_file = LocalData.'DD_'.$mission_id.'.xml';
   	 
   	 if (!file_exists($mission_file))
   	   return null;
   	   
   	 $ddDom = new DomDocument("1.0");
    	$ddDom->load($mission_file);
    	
    	$this->ddLocalMissionXPath[$mission_id] = new DOMXPath($ddDom);
    	
    	return $this->ddLocalMissionXPath[$mission_id];
   }
   
   /*
    * Get sub-missions info available in the DD_*.xml file from mission id
    * (a DD_*.xml file can contain more than one mission, for example THEMIS-A, THEMIS-B, etc..., this is what we called "sub-mission")
    */
   public function GetDDMissionInfo($mission_id)
   {
   	 $ddPath = $this->GetDDMissionXPath($mission_id);
   	 
   	 if (!$ddPath)
   	   return array('success' => false, 'message' => 'Error to parse DD mission file '.$mission_id);
   	   
   	 $subMiss = $ddPath->query("//mission");
   	 
   	 $sub_array = array();
   	 
   	 foreach($subMiss as $sub)
   	 {
	      $infos = $this->ExtractDDSubMissionInfoFromNode($sub);
	      $inst  = $this->GetDDInstrumentsInfo($mission_id, $infos['name']);
   	 
	      $sub_array[$infos['name']] = array(
                               "desc"        => $infos['desc'], 
                               "help"        => $infos['help'],
                               "class"       => $infos['class'],
                               "instruments" => $inst);
   	 }
   	 
     return $sub_array;
   }
   
   /*
    * Get instruments info available in the DD_*.xml file from mission id and sub mission name
    */
   public function GetDDInstrumentsInfo($mission_id, $sub_name)
   {
   	 $ddPath = $this->GetDDMissionXPath($mission_id);
   	 
   	 if (!$ddPath)
   	   return array('success' => false, 'message' => 'Error to parse DD mission file '.$mission_id);
   	   
   	 $instruments = $ddPath->query("//mission[@name='".$sub_name."']/instrument");
   	 
   	 $inst_array = array();
   	 
   	 foreach($instruments as $inst)
   	 {
   	 	 $infos = $this->ExtractDDInstrumentInfoFromNode($inst);
   	        $datasets = $this->GetDDDatasetsInfo($mission_id, $sub_name, $infos["name"]);
   	   
   	   $inst_array[$infos['name']] = array(
                               "desc"          => $infos['desc'], 
                               "help"          => $infos['help'],
				                           "pi"            => $infos['pi'],
   	                           "id"            => $infos['id'],
   	                           "refURL"        => $infos['refURL'],
   	                           "alternamename" => $infos['alternamename'],
   	                           "class"         => $infos['class'],
                               "datasets"      => $datasets);
   	 }
   	 
   	 return $inst_array;
   }
   
   /*
    * Get datasets info available in the DD_*.xml file from mission id, sub mission name and instrument name
    */
   private function GetDDDatasetsInfo($mission_id, $sub_name, $inst_name)
   {
   	 $ddPath = $this->GetDDMissionXPath($mission_id);
   	 
   	 if (!$ddPath)
   	   return array('success' => false, 'message' => 'Error to parse DD mission file '.$mission_id);
   	   
   	 $datasets = $ddPath->query("//mission[@name='".$sub_name."']//instrument[@name='".$inst_name."']//dataset");
   	 
   	 $datas_array = array();
   	 
   	 foreach ($datasets as $data)
   	 {
   	 	 $infos = $this->ExtractDDDatasetInfoFromNode($data);
   	 	 $params = $this->GetDDParametersInfo($mission_id, $sub_name, $inst_name, $infos['id']);
   	 	 
   	 	 $datas_array[$infos['id']] = array(
   	 	                        "name"        => $infos['name'],
   	 	                        "help"        => $infos['help'],
   	 	                        "minsampling" => $infos['minsampling'],
   	 	                        "maxsampling" => $infos['maxsampling'],
   	 	                        "starttime"   => $infos['starttime'],
   	 	                        "stoptime"    => $infos['stoptime'],
   	 	                        "source"      => $infos['source'],
   	                          "title"       => $infos['title'],
   	                          "description" => $infos['description'],
   	                          "creator"     => $infos['creator'],
   	                          "calibration" => $infos['calibration'],
   	                          "subject"     => $infos['subject'],
   	                          "contributor" => $infos['contributor'],
   	 	                        "target"      => $infos['target'],
   	 	                        "parameters"  => $params
   	 	 );
   	 }
   	 
   	 return $datas_array;
   }
   
   /*
    * Get parameters info available in the DD_*.xml file from mission id, sub mission name, instrument name and dataset id
    */
   public function GetDDParametersInfo($mission_id, $sub_name, $inst_name, $data_id)
   {
   	 $ddPath = $this->GetDDMissionXPath($mission_id);
   	 
   	 if (!$ddPath)
   	   return array('success' => false, 'message' => 'Error to parse DD mission file '.$mission_id);
   	   
   	 $parameters = $ddPath->query("//mission[@name='".$sub_name."']//instrument[@name='".$inst_name."']//dataset[@xml:id='".$data_id."']/parameter");
   	 
   	 $params_array = array();
   	 
   	 foreach ($parameters as $param)
   	 {
   	 	 $infos = $this->ExtractDDParameterInfoFromNode($param);
   	 	 
   	 	 $params_array[$infos['id']] = array(
   	 	                          "name"         => $infos["name"],
   	 	                          "units"        => $infos["units"],
   	 	                          "size"         => $infos["size"],
   	 	                          "display_type" => $infos["display_type"],
   	                            "comps_label"  => $infos["comps_label"],
   	                            "description"  => $infos["description"],
   	                            "ucd"          => $infos["ucd"],
   	                            "type"         => $infos["type"]
   	 	 );
   	 }
   	 
   	 return $params_array;
   }
   
   /*
    * Get all DD_*.xml info from parameter id
    */
   public function GetDDInfoFromParameterID($param_id, $comp_start = NULL, $comp_stop = NULL)
   {
   	 $missions = $this->GetMissionsList();
   	 
        foreach ($missions as $mission_id => $mission_val)
        {
            $ddPath = $this->GetDDMissionXPath($mission_id);
   	 
   	   if (!$ddPath)
   	     continue;
   	     
   	   $parameters = $ddPath->query("//instrument//dataset/parameter[@xml:id='".$param_id."']");
   	   
   	   if ($parameters->length < 1)                         
                                continue;                        
 

   	   $parameter_node = $parameters->item(0);

   	   //parameter info
   	   $param_infos      = $this->ExtractDDParameterInfoFromNode($parameter_node, $comp_start, $comp_stop);
   	   
   	   //dataset info
   	   $dataset_node  = $parameter_node->parentNode;
   	   $dataset_infos = $this->ExtractDDDatasetInfoFromNode($dataset_node);
   	   
   	   //instrument info                      
   	   $instrument_node = $dataset_node->parentNode->nodeName == 'instrument' ? $dataset_node->parentNode : $dataset_node->parentNode->parentNode;
   	   $instrument_infos = $this->ExtractDDInstrumentInfoFromNode($instrument_node);
   	   
   	   //sub mission info
   	   $tmp = $instrument_node->parentNode;

   	   if ($tmp->nodeName == "group" ) $submission_node = $tmp->parentNode;
   	   else $submission_node = $tmp;
   	   $submission_infos = $this->ExtractDDSubMissionInfoFromNode($submission_node);
  	   
   	   return array(
   	     'success'    => true,
   	     'parameter'  => $param_infos,
   	     'dataset'    => $dataset_infos,
   	     'instrument' => $instrument_infos,
   	     'submission' => $submission_infos,
   	     'mission_id' =>  $mission_id
   	   );
			  }
			  
	  return array('success' => false,
			'message' => 'No such param '.$param_id);
   }
      
    /*
    * Get dataset info
    */
   public function GetDDInfoFromDatasetID($datasetId)
   {
   	 $missions = $this->GetMissionsList();
   	 
			  foreach ($missions as $mission_id => $mission_val)
			  {
			  	 $ddPath = $this->GetDDMissionXPath($mission_id);
   	 
   	   if (!$ddPath)
   	     continue;
   	     
   	   $datasets = $ddPath->query("//instrument/dataset[@xml:id='".$datasetId."']");
   	   
   	   if ($datasets->length < 1)                          
                                continue;                        
  
   	   $dataset_node = $datasets->item(0);
   	   $dataset_infos = $this->ExtractDDDatasetInfoFromNode($dataset_node);
   	   
   	   //instrument info
   	   $instrument_node = $dataset_node->parentNode;
   	   $instrument_infos = $this->ExtractDDInstrumentInfoFromNode($instrument_node);
   	   
   	   //sub mission info
   	   $submission_node = $instrument_node->parentNode;
   	   $submission_infos = $this->ExtractDDSubMissionInfoFromNode($submission_node);
   	   
   	   //parameters info
   	   $param_infos = $this->GetDDParametersInfo($mission_id, $submission_infos['name'], $instrument_infos['name'], $datasetId);
   	   
   	   return array(
   	     'success'    => true,
   	     'parameter'  => $param_infos,
   	     'dataset'    => $dataset_infos,
   	     'instrument' => $instrument_infos,
   	     'submission' => $submission_infos,
   	     'mission_id' => $mission_id
   	   );
			  }
			  
			  return array('success' => false,
			               'message' => 'No such dataset '.$datasetId);
   }
   
   public function ExtractLocalParamsInfoFromNode($theParam)
   {     
     $name = $theParam->getAttribute("name");
     $vi = $theParam->getAttribute("vi");
     $size = $theParam->getElementsByTagName("SIZES")->item(0)->nodeValue;
     $tensor = $theParam->getElementsByTagName("TENSOR_ORDER_VALUE")->item(0)->nodeValue;
     $value_type = $theParam->getElementsByTagName("VALUE_TYPE")->item(0)->nodeValue;
     $fillNodes = $theParam->getElementsByTagName("FILLVAL");
     if ($fillNodes->length > 0)  
       $fill_value = $fillNodes->item(0)->nodeValue;
     else
       $fill_value = "NaN";
     //if ($fill_value == "NaN") $fill_value = "!Values.F_NAN";
     $units = $theParam->getElementsByTagName("UNITS")->item(0)->nodeValue;
     $sampling = $theParam->getElementsByTagName("TIME_RESOLUTION")->item(0)->nodeValue;
     $maxSamplingNode = $theParam->getElementsByTagName("MAX_TIME_RESOLUTION"); 
     if ($maxSamplingNode->length > 0)  $maxSampling =  $maxSamplingNode->item(0)->nodeValue;
     else   $maxSampling =  $sampling;
     $frame = $theParam->getElementsByTagName("COORDINATE_SYSTEM")->item(0)->nodeValue;
     $legend = $theParam->getElementsByTagName("LABEL_I")->item(0)->nodeValue;
     $title = $theParam->getElementsByTagName("YTITLE")->item(0)->nodeValue;
     $plottype =  $theParam->getElementsByTagName("DISPLAY_TYPE")->item(0)->nodeValue;
 //    if ($plottype == "TICK_MARKS")   //BRE - why put mission name in DISPLAY_TYPE tag? (for the moment, keep for compatibility)
 //      $mission = $theParam->getElementsByTagName("DISPLAY_TYPE")->item(0)->getAttribute("name");     
 //    else  
 //    		$mission = "n/a";
     $energychannel = $theParam->getAttribute("energy");
     if ($energychannel == '')
       $energychannel = 'Energy';

     $validMinNode = $theParam->getElementsByTagName("VALID_MIN");
     if ($validMinNode->length > 0) $validmin = $validMinNode->item(0)->nodeValue;
     else $validmin = 'unknown';

     $conversionNode = $theParam->getElementsByTagName("UNITS_CONVERSION");
     if ($conversionNode->length > 0) {
		  $infoProvider = new InfoProvider();
		  $conversion = $infoProvider->getConversion($conversionNode->item(0)->nodeValue); 
      }
     else $conversion = '-1';


     $processNode = $theParam->getElementsByTagName("PROCESS");
     if ($processNode->length > 0) $process = $processNode->item(0)->nodeValue;
     else $process = '';

     //$ytitle = $units != NULL ? $title.",!C".$units : $title;
     
     return array(
       'name'          => $name,
       'vi'            => $vi,
       'size'          => $size,
       'tensor'        => $tensor,
       'valuetype'     => $value_type,
       'fillvalue'     => $fill_value,
       'units'         => $units,
       'minsampling'   => $sampling,
       'maxsampling'   => $maxSampling,
       'frame'         => $frame,
       'legend'        => $legend,
       'title'         => $title,
       'plottype'      => $plottype,
  //     'mission'       => $mission, //BRE - why put mission name in DISPLAY_TYPE tag? (for the moment, keep for compatibility)
       'conversion'    => $conversion,
       'validmin'      => $validmin,
       'process'       => $process,
       'energychannel' => $energychannel
     );
   }   
   
   public function GetLocalParamInfo($param, $comp_start = NULL, $comp_stop = NULL)
   {

   	 if (!$this->localDom)
   	 {
	  $this->localDom = new DomDocument("1.0");
    	  if (!$this->localDom->load(paramXml))
    	    return array('success' => false, 'id' => $param, 'message' => 'Cannot load local param file');
   	 }
   	 
   	 $theParam = $this->localDom->getElementById($param);
    	  
   	 $comp_array = array();
   	 
   	 if (isset($comp_start) && isset($comp_stop) && ($comp_start != $comp_stop))
   	   $par_id = $param."(".$comp_start.":".$comp_stop.")";
   	 else if (isset($comp_start))
   	   $par_id = $param."(".$comp_start.")";
   	 else
   	   $par_id = $param;
   	 
   	 if (!$theParam)
   	   $ddinfos = $this->GetDDInfoFromParameterID($par_id);
   	 else {
   	   $ddinfos = $this->GetDDInfoFromParameterID($param, $comp_start, $comp_stop);
           $isInternal = $theParam->hasAttribute('internal'); 
        }
   	 
   	 if (!$ddinfos['success'] && !$isInternal)
   	    return array('success' => false, 'id' => $param, 'message' => $ddinfos['message']);
   	           
     if (!$theParam)
     		return array('success'  => true, 
                    'id'       => $par_id,
                    'type'     => 'local',
                    'withcode' => true,
                    'ddinfos'  => $ddinfos);
     
     
     $codeinfos = $this->ExtractLocalParamsInfoFromNode($theParam);  
     	   
     return array('success'   => true, 
                  'id'        => $par_id,
                  'type'      => 'local',
                  'withcode'  => false,
                  'ddinfos'   => $ddinfos,
                  'codeinfos' => $codeinfos);
   }
   
   protected function GetDerivedParamInfo($param, $comp_start = NULL, $comp_stop = NULL)
   {
        if (!$this->derivedParamMgr)
        $this->derivedParamMgr = new DerivedParamMgr('derivedParam');
        
        $obj = $this->derivedParamMgr->getObjectByName($param);
        
        if ($obj['error'])
            return array('success' => false, 'id' => $param, 'message' => $obj['error']);
 	   
        return array(
        'success'     => true,
        'id'          => $param,
        'type'        => 'derived',
        'infos'       => $obj
        );
   }
   
    protected function GetMyDataParamInfo($param, $comp_start = NULL, $comp_stop = NULL)
    {
        if (!$this->mydataParamMgr)
            $this->mydataParamMgr = new DerivedParamMgr();
        
        $obj = $this->mydataParamMgr->getObjectByName($param);
       
       if ($obj['error'])
                return array('success' => false, 'id' => $param, 'message' => $obj['error']);
     
        return array(
        'success'     => true,
        'id'          => $param,
        'type'        => 'mydata',
        'infos'       => $obj
        );
   }
   
    protected function GetSimuDataParamInfo($param, $comp_start = NULL, $comp_stop = NULL)
    {
        if (!$this->mySimuParamMgr)
            $this->mySimuParamMgr = new DerivedParamMgr('mySimuParam');
        
        $obj = $this->mySimuParamMgr->getObjectByName($param);
       
        if ($obj['error'])
                return array('success' => false, 'id' => $param, 'message' => $obj['error']);
        
        return array(
        'success'     => true,
        'id'          => $param,
        'type'        => 'mydata',
        'infos'       => $obj
        );
   }
      public function GetInternalParamInfo($param) {
      	 if (!$this->internalDom)
   	 {
	  $this->internalDom = new DomDocument("1.0");
    	  if (!$this->internalDom->load(internalParams))
    	    return array('success' => false, 'id' => $param, 'message' => 'Cannot load local internal params file');
   	 }
   	 
   	 $theParam = $this->internalDom->getElementById($param);
	
	$parentDataset =  $theParam->parentNode;
	$parentInstrument =  $parentDataset->parentNode;
	$parentMission =  $parentInstrument->parentNode;
        $missionName = isset($parentMission) ? $parentMission->getAttribute('name') : 'undefined';
        
	return array(
	      'success'     => true,
	      'id'          => $param,
	      'mission'     => $missionName,
	      'instrument'  => array('id'	=>$parentInstrument->getAttribute('xml:id'),
				     'name'	=>$parentInstrument->getAttribute('name'),
				     'desc'	=>$parentInstrument->getAttribute('desc')),
	      'dataset'	    =>	array('id'	=>$parentDataset->getAttribute('xml:id'),
				     'name'	=>$parentDataset->getAttribute('name'),
				     'sampling'	=>$parentDataset->getElementsByTagName('sampling')->item(0)->nodeValue,
				     'dataStart'=>$parentDataset->getElementsByTagName('dataStart')->item(0)->nodeValue,
				     'dataStop' =>$parentDataset->getElementsByTagName('dataStop')->item(0)->nodeValue)
		);
	           
   }
   
   public function ParamInfosToString($infos)
   {
   	 $str = $infos['id'];
   	
   	 if (!$infos['success'])
   	   return $str." - ".$infos['message'];
   	
   	 switch($infos['type'])
   	 {
   	 	 case 'local'   :
   	 	 	 $str .= (" - Type : Local Parameter @ CDPP/AMDA");
			    if ($infos['ddinfos']['parameter']['name'] != '')
 	 	 	 	 $str .= (" - Name : ".$infos['ddinfos']['parameter']['name']);
			    else
				 $str .= (" - Name : ".$infos['codeinfos']['title']);

			    if ($infos['ddinfos']['parameter']['units'] != '')
 	 	 	 	 $str .= (" - Units : ".$infos['ddinfos']['parameter']['units']);
			    else
				 $str .= (" - Units : ".$infos['codeinfos']['units']);

			    if ($infos['ddinfos']['parameter']['size'] != '')
 	 	 	 	 $str .= (" - Size : ".$infos['ddinfos']['parameter']['size']);
			    else
				 $str .= (" - Size : ".$infos['codeinfos']['size']);

			  if (!$infos['withcode'])
				  if ($infos['codeinfos']['frame'] != '')
				    $str .= (" - Frame : ".$infos['codeinfos']['frame']);
			    if ($infos['ddinfos']['submission']['name'] != '')
				 $str .= (" - Mission : ".$infos['ddinfos']['submission']['name']);
			    else
				 $str .= (" - Mission : ".$infos['codeinfos']['name']);

 	 	 	 	 $str .= (" - Instrument : ".$infos['ddinfos']['instrument']['name']);
			    if ($infos['ddinfos']['dataset']['name'] != '')
 	 	 	 	 $str .= (" - Dataset : ".$infos['ddinfos']['dataset']['name']);
			    else
				 $str .= (" - Dataset : ".$infos['codeinfos']['plottype']);

   	 	 	 break;
   	 	 case 'derived' :
   	 	 	 $str .= (" - Type : Derived Parameter @ CDPP/AMDA");
   	 	 	 $str .= (" - Name : ".$infos['infos']['name']);
   	 	 	 $str .= (" - Units : ".$infos['infos']['units']);
   	 	 	 $str .= (" - Build chain : ".htmlentities($infos['infos']['buildchain']));
   	 	 	 $str .= (" - Time Step : ".$infos['infos']['timestep']);
   	 	 	 break;
   	 	 case 'mydata'  :
   	 	 	 $str .= (" - Type : My Data Parameter @ CDPP/AMDA");
   	 	 	 $str .= (" - Name : ".$infos['infos']['name']);
   	 	 	 $str .= (" - Units : ".$infos['infos']['units']);
   	 	 	 $str .= (" - Size : ".$infos['infos']['size']);
   	 	 	 $str .= (" - From : ".$infos['infos']['file']);
   	 	 	 break;
   	 	 default :
   	 	 	 return $str." - Unknown parameter type (maybe not yet implemented?)";
   	 }
	  		
	  		return $str;
   }
  
   
   function forEachAllDDParameters($callback_func)
   {
   	 $missions = $this->GetMissionsList();
   	 foreach ($missions as $mis_key => $mis_val)
   	 {
   	 	 if ($mis_key == 'success')
   	 	   continue;
   	 	 $subs = $this->GetDDMissionInfo($mis_key);
   	 	 foreach ($subs as $sub_key => $sub_val)
		    foreach($sub_val['instruments'] as $inst_key => $inst_val)
			foreach ($inst_val["datasets"] as $data_key => $data_val)
			    foreach ($data_val["parameters"] as $param_key => $param_val)
   	 	        	 call_user_func($callback_func, array("mission"    => array("id"   => $mis_key,   "infos" => $mis_val),
                                                     "submission" => array("name" => $sub_key,   "infos" => $sub_val),
                                                     "instrument" => array("name" => $inst_key,  "infos" => $inst_val),
                                                     "dataset"    => array("id"   => $data_key,  "infos" => $data_val),
                                                     "parameter"  => array("id"   => $param_key, "infos" =>  $param_val)));
   	 }
   }
   
   function forEachAllDDDatasets($callback_func)
   {
   	 $missions = $this->GetMissionsList();
   	 foreach ($missions as $mis_key => $mis_val)
   	 {
   	 	 if ($mis_key == 'success')
   	 	   continue;
   	 	 $subs = $this->GetDDMissionInfo($mis_key);
   	 	 foreach ($subs as $sub_key => $sub_val)
   	 	 	 foreach($sub_val['instruments'] as $inst_key => $inst_val)
   	 	 	   foreach ($inst_val["datasets"] as $data_key => $data_val)
   	 	 	      call_user_func($callback_func, array("mission"    => array("id"   => $mis_key,   "infos" => $mis_val),
                                                   "submission" => array("name" => $sub_key,   "infos" => $sub_val),
                                                   "instrument" => array("name" => $inst_key,  "infos" => $inst_val),
                                                   "dataset"    => array("id"   => $data_key,  "infos" => $data_val)));
   	 }
   }
 }
 
?>