#!/usr/bin/perl
# related article: http://newtoypia.blogspot.tw/2014/08/osm-mashup.html

# data file airports.csv is taken from
# http://www.partow.net/miscellaneous/airportdatabase/
# and renamed from GlobalAirportDatabase.txt inside the zip file.
# You need to install the JSON module for perl.
# For example, in debian: apt-get install libjson-perl
# Usage: perl airports.txt airports.csv > airports.json

use JSON;

while (<>) {
    # AYGA:GKA:GOROKA:GOROKA:PAPUA NEW GUINEA:06:04:54:S:145:23:30:E:5282
    (
	$ICAO, $IATA, $name, $city, $country,
	$lat_d, $lat_m, $lat_s, $lat_sgn,
	$lon_d, $lon_m, $lon_s, $lon_sgn
    ) = split ":";

    next if ($IATA eq "N/A" or $lat_sgn eq "U" or $lon_sgn eq "U");
    $lon = $lon_d + ($lon_m + $lon_s / 60.0) / 60.0;
    $lon = - $lon if $lon_sgn eq "W";
    $lat = $lat_d + ($lat_m + $lat_s / 60.0) / 60.0;
    $lat = - $lat if $lat_sgn eq "S";
    push @out, {
	id => $IATA,
	name => $name,
	city => $city,
	country => $country,
	lon => $lon,
	lat => $lat,
    };
}

print JSON->new->allow_nonref->pretty->encode(\@out);
