<?php

$place = "Pertteli";
$apikey = "b37f3e99-cdb8-4858-b850-bfffea6542f9";
$root = "/home/web3/public_html/cache/";
ini_set('display_errors', '1');

$URL = 'http://data.fmi.fi/wfs?request=getFeature&storedquery_id=fmi::forecast::hirlam::ground::point::timevaluepair&fmi-apikey='.$apikey .'&timestep=30&crs=EPSG::4326&place='.$place;
$cacheName = $root.'fmifrcsshort_'.$place.'.txt';  // prototype for path/filename for cache file
$fetchSeconds = 3600;  // refresh every hour

if (file_exists($cacheName) and filemtime($cacheName) + $fetchSeconds > time()) {
  $html = file_get_contents($cacheName);
} else {
  $html = file_get_contents($URL);
  file_put_contents($cacheName,$html);;
  chmod($cacheName, 0666);
}

$xml=xml2array($html);
//print_r($xml);
$xml = $xml["wfs:FeatureCollection"]["wfs:member"]; 
  
for($i=0;$i<count($xml);$i++){
  if($i==0){
    $place = $xml[$i]["omso:PointTimeSeriesObservation"]["om:featureOfInterest"]["sams:SF_SpatialSamplingFeature"]["sams:shape"]["gml:MultiPoint"]["gml:pointMembers"]["gml:Point"][1]["gml:name"];
    $coords = $xml[$i]["omso:PointTimeSeriesObservation"]["om:featureOfInterest"]["sams:SF_SpatialSamplingFeature"]["sams:shape"]["gml:MultiPoint"]["gml:pointMembers"]["gml:Point"]["gml:pos"];
    $frctime = $xml[$i]["omso:PointTimeSeriesObservation"]["om:resultTime"]["gml:TimeInstant"]["gml:timePosition"];
  }
    
  $id = $xml[$i]["omso:PointTimeSeriesObservation"]["om:result"]["wml2:MeasurementTimeseries_attr"]["gml:id"];
  $vals = $xml[$i]["omso:PointTimeSeriesObservation"]["om:result"]["wml2:MeasurementTimeseries"]["wml2:point"];
  for($t=0;$t<count($vals);$t++) {
    $line = $vals[$t];
    if($i==0){$yrfr[times][] = strtotime($line["wml2:MeasurementTVP"]["wml2:time"]);}
    $yrfr[$id][] = $line["wml2:MeasurementTVP"]["wml2:value"];
  }
}
//print_r($yrfr);
$howmany = count($yrfr["mts-Temperature"]);
$tzoffs = date("Z");

//***************************************************************************/
$precs=0;
$clears=0;
$pcloud=0;
$cloudy=0;
$a=0;
for ($i = 0; $i < $howmany; $i++) {
  $time = $yrfr['times'][$i] + $tzoffs;
  $hr = date("Gi",$time);
  if(($hr==600 || $hr==1800) && ($i<>0 || $i==$howmany-1)){
    if($hr==600){$hr="night";}else{$hr="day";}
    $frc[$a]["time"] = $hr;
    $frc[$a]["maxtemp"] = max($temps);
    $frc[$a]["mintemp"] = min($temps);
    $frc[$a]["maxwind"] = max($wspds);
    $frc[$a]["maxgust"] = max($wgsts);
    $frc[$a]["icon"] = getfmiicon(max($ics));
    $array = array_count_values($ics);
    arsort($array);
    $w = key($array);
    next($array);
    $j = key($array);
    $sep = "";
    $onlyonce = array(31,32,33,51,52,53,62,63,64,81,82,83);
    $frc[$a]["desc"] = getfmidesc($w);
    if(!in_array($w,$onlyonce) || !in_array($j,$onlyonce)){
      if(max($ics) < 10 && count($array) > 1){$sep = "tai";}
      if(max($ics) > 10 && min($ics) < 10 && count($array) > 1){$sep = "ja";}
      $frc[$a]["desc"] = getfmidesc($w).' '.$sep.' '.getfmidesc($j);
    }
    
    $temps = array();
    $wspds = array();
    $wgsts = array();
    $ics = array();
    $clears=0;
    $pcloud=0;
    $cloudy=0;
    $a++;
  }
  $ics[] = intval($yrfr["mts-WeatherSymbol3"][$i]);
  if(round($yrfr["mts-WeatherSymbol3"][$i]) == 1){$clears++;}
  if(round($yrfr["mts-WeatherSymbol3"][$i]) == 2){$pcloud++;}
  if(round($yrfr["mts-WeatherSymbol3"][$i]) == 3){$cloudy++;}
  $rtemp = $yrfr["mts-Temperature"][$i];
  $rhum = $yrfr['mts-Humidity'][$i];
  $rwspd = $yrfr['mts-WindSpeedMS'][$i];
  $chills[] = wind_chill($rtemp, $rwspd);
  $heats[] = heat_index($rtemp, $rhum);
  $temps[] = $rtemp;
  $hums[] = $rhum;
  $wspds[] = $rwspd;
  $wdirs[] = $yrfr["mts-WindDirection"][$i];
  $wgsts[] = $yrfr['mts-HourlyMaximumGust'][$i];
  $baro = sprintf("%01.1f",$yrfr["mts-Pressure"][$i]);
  $precs+= $yrfr["mts-Precipitation1h"][$i];
  $cloud = round($yrfr['mts-TotalCloudCover'][$i]);
  $solar = round($yrfr['mts-RadiationGlobal'][$i]);
  $lasttime = $time;
}
//print_r($frc);

file_put_contents($root.'fmishort.son',json_encode($frc));

//*********************************************************

function getfmidesc($ic){
if($ic==1){$ic = "selkeää";}
if($ic==2){$ic = "puolipilvistä";}
if($ic==21){$ic = "heikkoja sadekuuroja";}
if($ic==22){$ic = "sadekuuroja";}
if($ic==23){$ic = "voimakkaita sadekuuroja";}
if($ic==3){$ic = "pilvistä";}
if($ic==31){$ic = "heikkoa vesisadetta";}
if($ic==32){$ic = "vesisadetta";}
if($ic==33){$ic = "voimakasta vesisadetta";}
if($ic==41){$ic = "heikkoja lumikuuroja";}
if($ic==42){$ic = "lumikuuroja";}
if($ic==43){$ic = "voimakkaita lumikuuroja";}
if($ic==51){$ic = "heikkoa lumisadetta";}
if($ic==52){$ic = "lumisadetta";}
if($ic==53){$ic = "voimakasta lumisadetta";}
if($ic==61){$ic = "ukkoskuuroja";}
if($ic==62){$ic = "voimakkaita ukkoskuuroja";}
if($ic==63){$ic = "ukkosta";}
if($ic==64){$ic = "voimakasta ukkosta";}
if($ic==71){$ic = "heikkoja räntäkuuroja";}
if($ic==72){$ic = "räntäkuuroja";}
if($ic==73){$ic = "voimakkaita räntäkuuroja";}
if($ic==81){$ic = "heikkoa räntäsadetta";}
if($ic==82){$ic = "räntäsadetta";}
if($ic==83){$ic = "voimakasta räntäsadetta";}
if($ic==91){$ic = "utua";}
if($ic==92){$ic = "sumua";}
return $ic;
}

function getfmiicon($ic){
if($ic==1){$ic = "clear";}
if($ic==2){$ic = "partlycloudy";}
if($ic==21){$ic = "drizzle";}
if($ic==22){$ic = "rainshowers";}
if($ic==23){$ic = "rainshowers";}
if($ic==3){$ic = "cloudy";}
if($ic==31){$ic = "rain1";}
if($ic==32){$ic = "rain3";}
if($ic==33){$ic = "rain4";}
if($ic==41){$ic = "snowshowers";}
if($ic==42){$ic = "snowshowers";}
if($ic==43){$ic = "snowshowers";}
if($ic==51){$ic = "snow2";}
if($ic==52){$ic = "snow3";}
if($ic==53){$ic = "snow4";}
if($ic==61){$ic = "rainshowersthunder";}
if($ic==62){$ic = "tsorms2";}
if($ic==63){$ic = "tsorms1";}
if($ic==64){$ic = "tsorms3";}
if($ic==71){$ic = "sleetshowers";}
if($ic==72){$ic = "sleetshowers";}
if($ic==73){$ic = "sleetshowers";}
if($ic==81){$ic = "sleet";}
if($ic==82){$ic = "sleet";}
if($ic==83){$ic = "sleet";}
if($ic==91){$ic = "hazy";}
if($ic==92){$ic = "hazy";}
return $ic;
}

function wind_chill($TEMP, $WGST) {
    $tempF = round((1.8 * $TEMP) + 32.0,1);
    $windspeed = round(2.23693629 * $WGST,1);
        $chillF = 35.74 + 0.6215 * $tempF - 35.75 * pow($windspeed, 0.16) + 0.4275 * $tempF * pow($windspeed, 0.16);
        $chillF = round($chillF);
        $chillC = sprintf("%01.1f",(round((($chillF - 32) / 1.8),1)));
	if($chillC > $TEMP) {
	$chillC = $TEMP;
	}
   return $chillC;	
}

function heat_index($TEMP, $HUMID) { 
  if($TEMP < 15){ return $hiC;}
	$tempF = round((1.8 * $TEMP) + 32,1);
	$rh = $HUMID;
      $hiF = -42.379 + 2.04901523 * $tempF + 10.14333127 * $rh - 0.22475541 * $tempF * $rh;
      $hiF += -0.00683783 * pow($tempF, 2) - 0.05481717 * pow($rh, 2);
      $hiF += 0.00122874 * pow($tempF, 2) * $rh + 0.00085282 * $tempF * pow($rh, 2);
      $hiF += -0.00000199 * pow($tempF, 2) * pow($rh, 2);
      $hiF = round($hiF);
      $hiC = sprintf("%01.1f",(round((($hiF - 32) / 1.8),1)));
      return $hiC;
}

function xml2array($contents, $get_attributes=1, $priority = 'tag') {
    if(!$contents) return array();

    if(!function_exists('xml_parser_create')) {
        //print "'xml_parser_create()' function not found!";
        return array();
    }

    //Get the XML parser of PHP - PHP must have this module for the parser to work
    $parser = xml_parser_create('');
    xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); # http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($parser, trim($contents), $xml_values);
    xml_parser_free($parser);

    if(!$xml_values) return;//Hmm...

    //Initializations
    $xml_array = array();
    $parents = array();
    $opened_tags = array();
    $arr = array();

    $current = &$xml_array; //Refference

    //Go through the tags.
    $repeated_tag_index = array();//Multiple tags with same name will be turned into an array
    foreach($xml_values as $data) {
        unset($attributes,$value);//Remove existing values, or there will be trouble

        //This command will extract these variables into the foreach scope
        // tag(string), type(string), level(int), attributes(array).
        extract($data);//We could use the array by itself, but this cooler.

        $result = array();
        $attributes_data = array();
        
        if(isset($value)) {
            if($priority == 'tag') $result = $value;
            else $result['value'] = $value; //Put the value in a assoc array if we are in the 'Attribute' mode
        }

        //Set the attributes too.
        if(isset($attributes) and $get_attributes) {
            foreach($attributes as $attr => $val) {
                if($priority == 'tag') $attributes_data[$attr] = $val;
                else $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
            }
        }

        //See tag status and do the needed.
        if($type == "open") {//The starting of the tag '<tag>'
            $parent[$level-1] = &$current;
            if(!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag
                $current[$tag] = $result;
                if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
                $repeated_tag_index[$tag.'_'.$level] = 1;

                $current = &$current[$tag];

            } else { //There was another element with the same tag name

                if(isset($current[$tag][0])) {//If there is a 0th element it is already an array
                    $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
                    $repeated_tag_index[$tag.'_'.$level]++;
                } else {//This section will make the value an array if multiple tags with the same name appear together
                    $current[$tag] = array($current[$tag],$result);//This will combine the existing item and the new item together to make an array
                    $repeated_tag_index[$tag.'_'.$level] = 2;
                    
                    if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well
                        $current[$tag]['0_attr'] = $current[$tag.'_attr'];
                        unset($current[$tag.'_attr']);
                    }

                }
                $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
                $current = &$current[$tag][$last_item_index];
            }

        } elseif($type == "complete") { //Tags that ends in 1 line '<tag />'
            //See if the key is already taken.
            if(!isset($current[$tag])) { //New Key
                $current[$tag] = $result;
                $repeated_tag_index[$tag.'_'.$level] = 1;
                if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;

            } else { //If taken, put all things inside a list(array)
                if(isset($current[$tag][0]) and is_array($current[$tag])) {//If it is already an array...

                    // ...push the new element into that array.
                    $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
                    
                    if($priority == 'tag' and $get_attributes and $attributes_data) {
                        $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
                    }
                    $repeated_tag_index[$tag.'_'.$level]++;

                } else { //If it is not an array...
                    $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
                    $repeated_tag_index[$tag.'_'.$level] = 1;
                    if($priority == 'tag' and $get_attributes) {
                        if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well
                            
                            $current[$tag]['0_attr'] = $current[$tag.'_attr'];
                            unset($current[$tag.'_attr']);
                        }
                        
                        if($attributes_data) {
                            $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
                        }
                    }
                    $repeated_tag_index[$tag.'_'.$level]++; //0 and 1 index is already taken
                }
            }

        } elseif($type == 'close') { //End of tag '</tag>'
            $current = &$parent[$level-1];
        }
    }
    
    return($xml_array);
}      
?>