<?php

// Utility functions dealing with GPS coordinates from EXIF data

define('NO_ALTITUDE', -1024);  // null doesn't work :-(

// Convert a lat or lon 3-array to decimal degrees
function exif_degrees($a) {
  @eval("\$deg = $a[0]; \$min = $a[1]; \$sec = $a[2];");
  return $deg + $min / 60.0 + $sec / 3600.0;
}

// Extract lat, lon and altitude from an EXIF GPS array
function exif_gps_vars($exif, &$lat, &$lon, &$alt) {
  $gps = $exif['GPS'];
  $lat = exif_degrees($gps['GPSLatitude']);
  if ($gps['GPSLatitudeRef'] == 'S')
    $lat *= -1;
  $lon = exif_degrees($gps['GPSLongitude']);
  if ($gps['GPSLongitudeRef'] == 'W')
    $lon *= -1;
  if (array_key_exists('GPSAltitude', $gps))
    @eval("\$alt = {$gps['GPSAltitude']};");
  else
    $alt = NO_ALTITUDE;
}

// Convert decimal degrees to deg° min' sec" H
function exif_dec_to_DMS($dec, $hemis) {
  $absdec = abs($dec);
  $deg = intval($absdec);
  $absdec = ($absdec - $deg) * 60;
  $min = intval($absdec);
  $sec = ($absdec - $min) * 60;
  return sprintf("%d° %02d′ %05.2f″ %s",
    $deg, $min, $sec, $dec >= 0 ? $hemis[0] : $hemis[1]
  );
}

// Convert an EXIF GPS array to HTML-usable text, optionally adorned
// with a h-geo microformat; see http://microformats.org/wiki/h-geo
function exif_to_html($exif, $geo=false) {
  exif_gps_vars($exif, $lat, $lon, $alt);
  $hlat = exif_dec_to_DMS($lat, 'NS');
  $hlon = exif_dec_to_DMS($lon, 'EW');
  $alt = intval($alt);
  if ($geo) {
    $ret = "<span class=\"h-geo\">
    <abbr class=\"p-latitude\" title=\"$lat\">$hlat</abbr>,
    <abbr class=\"p-longitude\" title=\"$lon\">$hlon</abbr>\n";
    if ($alt !== NO_ALTITUDE)
      $ret .= "    <abbr class=\"p-altitude\">$alt</abbr>\n";
    $ret .= "</span>";
  } else {
    $ret = "$hlat, $hlon";
    if ($alt !== NO_ALTITUDE)
      $ret .= " ($alt m)";
  }
  return $ret;
}

?>