package orc.lib.net;

import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;

import kilim.Pausable;
import orc.runtime.values.TupleValue;

/**
 * API for http://geocoder.us. This service returns a latitude/longitude tuple
 * given a city/state, zip code, or full address in the United States.
 * 
 * @author quark
 */
public class Geocoder {
	private static String baseURL = "http://geocoder.us/service/csv/geocode?";

	private static TupleValue parseCSV(String csv) {
		String[] parts = csv.split(",");
		if (parts.length < 3) return null;
		try {
			return new TupleValue(Double.parseDouble(parts[0].trim()), Double.parseDouble(parts[1].trim()));
		} catch (NumberFormatException e) {
			return null;
		}
	}
	
	public static TupleValue locateAddress(String address) throws IOException, Pausable {
		return parseCSV(HTTPUtils.getURL(new URL(baseURL + "address="
				+ URLEncoder.encode(address, "UTF-8"))));
	}
	
	public static TupleValue locateCity(String city, String state) throws IOException, Pausable {
		return parseCSV(HTTPUtils.getURL(new URL(
			baseURL + "city=" + URLEncoder.encode(city, "UTF-8")
			+ "&state=" + URLEncoder.encode(state, "UTF-8"))));
	}
	
	public static TupleValue locateZip(String zip) throws IOException, Pausable {
		return parseCSV(HTTPUtils.getURL(new URL(
			baseURL + "zip=" + URLEncoder.encode(zip, "UTF-8"))));
	}
}

@@ -116,16 +116,42 @@
 usable;%0A
+import orc.runtime.Kilim;%0A
 import o
@@ -508,16 +508,32 @@
 ing csv)
+ throws Pausable
  %7B%0A%09%09Str
@@ -586,16 +586,38 @@
 th %3C 3) 
+%7B%0A%09%09%09Kilim.exit();%0A%09%09%09
 return n
@@ -621,16 +621,20 @@
 n null;%0A
+%09%09%7D%0A
 %09%09try %7B%0A
@@ -771,16 +771,33 @@
 on e) %7B%0A
+%09%09%09Kilim.exit();%0A
 %09%09%09retur

exit rather than returning null when no results are found.