import java.text.NumberFormat;

import java.net.*;
import java.io.*;

public class freeRice
{
	public static int time = 0;
	public static int donated = 0;
	public static int selected = 1;
	public static String info = "";
	public static String info2 = "";
	public static String info3 = "";

	public static void main(String args[])
	{
		NumberFormat usFormat = NumberFormat.getIntegerInstance();
		
		if (args.length > 0)
			time = Integer.parseInt(args[0]);

		newRice();
		
		while(true)
		{				
			try
			{
				if(selected > 4)
				{
					newRice();
					selected = 1;
				}

				Thread.sleep(time);
				// Construct data
				String data = URLEncoder.encode("SELECTED", "UTF-8") + "=" + URLEncoder.encode(" "+selected+" ", "UTF-8");
				data += "&" + URLEncoder.encode("PAST", "UTF-8") + "=" + URLEncoder.encode("", "UTF-8");
				data += "&" + URLEncoder.encode("INFO", "UTF-8") + "=" + URLEncoder.encode(info, "UTF-8");    
				data += "&" + URLEncoder.encode("INFO2", "UTF-8") + "=" + URLEncoder.encode(info2, "UTF-8");
				data += "&" + URLEncoder.encode("INFO3", "UTF-8") + "=" + URLEncoder.encode(info3, "UTF-8");
 
				// Send data
				URL url = new URL("http://www.freerice.com/");
				URLConnection conn = url.openConnection();
				conn.setDoOutput(true);
				OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
				wr.write(data);
				wr.flush();
   
				// Get the response
				BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				String line;
				while ((line = rd.readLine()) != null)
				{				
					int lio = 0;
					if((lio = line.indexOf("correctDef")) > 0)
					{
						donated += 20;
						System.out.println(line.substring(lio+13, line.length()-10) + "\nYou have donated "+usFormat.format(donated)+" grains of rice");
						selected = 1;
						newRice();
					}
					if((lio = line.indexOf("incorrect")) > 0)
					{
						System.out.print(".");
						selected = selected + 1;
					}
				}
				wr.close();
				rd.close();
			} catch (Exception e) {}
		}
	}
	
	public static void newRice()
	{
		try
		{	
			// Setup connection
			URL url = new URL("http://www.freerice.com/");
			URLConnection conn = url.openConnection();
			
			// Get INFO and INFO2
			BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = rd.readLine()) != null)
			{
				int lio = 0;
				if((lio = line.indexOf("name=\"INFO\" value=")) > 0)
					info = line.substring(lio+18, line.indexOf("/")-1);
				else if((lio = line.indexOf("name=\"INFO2\" value=")) > 0)
					info2 = line.substring(lio+19, line.indexOf("/")-1);
				else if((lio = line.indexOf("name=\"INFO3\" value=")) > 0)
					info3 = line.substring(lio+19, line.indexOf("/")-1);
			}
			rd.close();
		} catch (Exception e) {}
	}
}
