// A utility to take a longitude latitude and return a time zone in olson posix string format
// by anselm@hook.org
// this was based on data from
// http://koordinates.com/layer/751-world-time-zones/
// which was loaded into mapserver and each layer rendered as a unique color to a large image
// this code looks up that color on the map and then returns the appropriate indexed string
// see also
// http://books.google.ca/books?id=tZ2rExM1hy8C&pg=PA136&lpg=PA136&dq=blue+marble+projection&source=bl &ots=46IcxdmJar&sig=sOwzkup4vASHQSADNIQgq35BpIs&hl=en&ei=iN8SSo-pO5iG8gT9qsCBBA&sa=X&oi=book_result&c t=result&resnum=6

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include "timezones.h"

#define CONVERTNAME "convert"
#define CONVERTPATH "/usr/local/bin/convert"
#define INCANTATION_BUFFER_SIZE 999

int main(int argc,char **argv) {
  if(argc <3 ) {
   printf("Usage: %s longitude latitude\n",argv[0]);
   return(0);
  }
  char incantation[INCANTATION_BUFFER_SIZE];
  int timezones_length = sizeof(timezones)/sizeof(timezones[0]);
  int zonecode = 0;
  // get user supplied location
  double lon = atof(argv[1]);
  double lat = atof(argv[2]);
  // convert to equidistant projection
  int x = 2048.0f/360.0f*(180.0f+lon);
  int y = 1024.0f/180.0f*(90.0f-lat);
  int r,g,b;
  printf("Given longitude,latitude %lf,%lf\n",lon,lat);
  printf("Given pixel location x,y epsg:4326 projection at %d,%d\n",x,y);
  snprintf(incantation,
           INCANTATION_BUFFER_SIZE,
           "convert timezone.tiff -format \"%%[pixel:u.p{%d,%d}]\" info:",x,y);
  printf("ImageMagic incantation is %s\n",incantation);
  FILE* f = popen(incantation,"r");
  while( fgets(incantation,INCANTATION_BUFFER_SIZE,f))
  printf("%s",incantation);
  fclose(f);
  sscanf(incantation,"rgb(%d,%d,%d)",&r,&g,&b);
  printf("Got colors %d,%d,%d\n",r,g,b );
  zonecode = ((r&248)<<1)+((g>>4)&15);
  if(zonecode > timezones_length) {
    printf("Illegal color in the image; doesn't seem to map with our range! %d\n", zonecode );
  } else {
    printf("The longitude latitude of %f,%f is in timezone %s\n",lon,lat,timezones[zonecode]);
  }
}
