// pad with JSONP -- TMH 2012/07/20
$useJSONP = true;
// keep history -- TMH 2012/08/31
$keepHistory = false;
// grid Updated time
$updatedTime = -1;
$phpStart = microtime(true);
$queryManager = new QueryManager($readOnly);
$contourDataStore = new ContourCacheHelper($useGzip, $bandHelper->getSchemeId());
$phpTime = microtime(true) - $phpStart;
// Check if $txnAt for $timestamp is older than specified right now,
// then only proceed. Otherwise just exit from here
// Honour force flag if is set
$lastTxnAt = $txnAt;
if ($txnAt >= 0) {
    $lastTxnAt = $queryManager->getGridUpdatedTime($timestamp);
}
if ($txnAt >= 0 && $lastTxnAt >= $txnAt) {
    echo "Grid last updated with txn stamp [{$lastTxnAt}]," . " more recent than / equal to [{$txnAt}]\n";
    echo "Use force write if it was intended to forcefully update data";
    exit(0);
}
$midTime = microtime(true);
$queryStart = microtime(true);
$allData = $queryManager->getDataForWindBasedInterpolation($timestamp, 6);
if (empty($allData['ozoneValues'])) {
    echo "No data available for interpolation algorithm for {$timestamp}\n";
    exit(0);
}
$queryTime = microtime(true) - $queryStart;
$writeToGridStatus = true;
$grid = array();
$queryTime = 0;
//$driver = new Java('LatLongInterpolation.LatLngDriver', $bandHashMap);
for ($t = $timestamp; $t <= $timestamp2; $t += $interval) {
    $queryStart = microtime(true);
    if ($use_flat) {
        $loadedData = $queryManager->getPointData_from_json($t, $pointsOfInterest);
        if (!empty($loadedData)) {
            if ($loadedData[0]['gen_time'] > $latest_gen_time) {
                $latest_gen_time = $loadedData[0]['gen_time'];
            }
        }
    } else {
        $loadedData = $queryManager->getPointData($t, $pointsOfInterest, $gridReference, $useLatestDataWhenFail);
        if (!empty($loadedData)) {
            $latest_gen_time = $queryManager->getGridUpdatedTime($t);
        }
    }
    $queryTime += microtime(true) - $queryStart;
    // now prepare data
    if (!empty($loadedData)) {
        $latlngData = array();
        // count($pointsOfInterest) should be same as count($loadedData)
        for ($i = 0; $i < count($pointsOfInterest); $i++) {
            $labelId = $bandHelper->getLabelId($loadedData[$i]['o3']);
            $gridPoint = $loadedData[$i]['lat'] . ':' . $loadedData[$i]['lng'];
            $attr = array('ozone_level' => intval($loadedData[$i]['o3']), 'exp' => $loadedData[$i]['exp'], 'gridpoint' => "{$gridPoint}");
            if ($add_gen_time) {
                $attr['gen_time'] = $loadedData[$i]['gen_time'];
            }
            $latlngData[] = array('label_id' => $labelId, 'lat' => $pointsOfInterest[$i][0], 'lng' => $pointsOfInterest[$i][1], 'attr' => $attr);
            continue;
        }
        $lat = $stationData[$i][1];
        $lng = $stationData[$i][2];
        $o3 = floor($stationData[$i][3] + 0.5);
        $siteDesc = $stationData[$i][5];
        $responseObject['station'][] = array('lat' => $lat, 'lng' => $lng, 'o3' => $o3, 'desc' => $siteDesc);
    }
}
$end = microtime(true);
if (!$fsCacheDetected) {
    // TODO: Do we want to store the result?
}
if ($requestType == 'json') {
    header('Content-Type: text/javascript');
    $mod_timestamp = $queryManager->getGridUpdatedTime($timestamp);
    header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $mod_timestamp) . ' GMT');
    $now = time();
    // cache up to 5 min (at 3, 8, 13, ... min) if grid was timestamp is within 6 hours
    if ($now - $timestamp < 3600 * 6) {
        $expire_timestamp = floor(($now - 180 + 300) / 300) * 300 + 180;
        $max_age = 300;
    } else {
        // cache up to 1 hour otherwise
        $expire_timestamp = floor(($now - 180 + 3600) / 300) * 300 + 180;
        $max_age = 3600;
    }
    // else
    header('Cache-Control: max-age=' . $max_age);
    header('Expires: ' . gmdate("D, d M Y H:i:s", $expire_timestamp) . ' GMT');
    //echo "timestamp = '$timestamp' (".date($timestamp).")". " ; mod_timestamp = '$mod_timestamp' ; now = '$now' ; expire_timestamp = '$expire_timestamp'\n";