// $Id: zipcode.java,v 1.6 2004/09/30 21:42:08 mdean Exp $


class zipcode
{
    static com.hp.hpl.mesa.rdf.jena.model.Model zipcode(String zipcode)
	throws Exception
    {
	java.net.URL url = new java.net.URL("http://zip4.usps.com/cgi-bin/zip4/ctystzip2");
	java.net.URLConnection connection = url.openConnection();
	connection.setDoInput(true);
	connection.setDoOutput(true);
	connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	java.io.DataOutputStream outputStream = new java.io.DataOutputStream(connection.getOutputStream());
	String request = "ctystzip=" + java.net.URLEncoder.encode(zipcode);
	outputStream.writeBytes(request);
	outputStream.flush();
	outputStream.close();
	org.daml.html.Tree tree = new org.daml.html.Tree(connection.getInputStream());

	// tree.dump(new java.io.PrintStream(System.out));	// XXX

	com.hp.hpl.mesa.rdf.jena.model.Model model = new com.hp.hpl.mesa.rdf.jena.mem.ModelMem();
	com.hp.hpl.mesa.rdf.jena.model.Resource zipcodeResource = model.createResource("");
	model.add(zipcodeResource,
		  com.hp.hpl.mesa.rdf.jena.vocabulary.RDF.type,
		  zipcode_ont.ZipCode);

	for (int i = 4; ; i++)
	    {
		String line = tree.getString("html/body/center/table/tr/td/pre/p/p/text()[" + i + "]");
		if (line == null)
		    break;
		if (line.trim().length() == 0)
		    break;
		if (line.charAt(0) == ' ') // e.g. USE ANN ARBOR
		    continue;

		String city = line.substring(0, 27).trim();
		String state = line.substring(27, 29);
		String usage = line.substring(36, 62).trim(); // ACCEPTABLE (DEFAULT), ACCEPTABLE, NOT ACCEPTABLE, etc.
		String type = line.substring(62).trim(); // STANDARD, PO BOX ONLY, etc.
		
		com.hp.hpl.mesa.rdf.jena.model.Resource association = model.createResource();
		model.add(association,
			  com.hp.hpl.mesa.rdf.jena.vocabulary.RDF.type,
			  zipcode_ont.Association);
		model.add(zipcodeResource,
			  ((usage.indexOf("(DEFAULT)") == -1)
			   ? zipcode_ont.association
			   : zipcode_ont.defaultAssociation),
			  association);
		model.add(association,
			  zipcode_ont.city,
			  city);
		model.add(association,
			  zipcode_ont.state,
			  state); // XXX - URI?
		model.add(association,
			  zipcode_ont.acceptable,
			  usage.startsWith("ACCEPTABLE") 
			  ? "true" : "false");
		model.add(association,
			  zipcode_ont.type,
			  type); // XXX - enumeration?
	    }

	return model;
    }

    static void usage()
    {
	System.err.println("Usage:  zipcode");
	System.exit(1);
    }

    public static void main(String args[])
	throws Exception
    {
	if (args.length != 1)
	    usage();

	com.hp.hpl.mesa.rdf.jena.model.Model model = zipcode(args[0]);
	java.io.PrintWriter writer = new java.io.PrintWriter(System.out);
	model.write(writer);
	writer.close();
    }
}
