import java.io.*;
import java.lang.*;
import java.util.*;
import javax.comm.*;

public class Term implements SerialPortEventListener {
	private SerialPort port;	/* Serial port device */
	private InputStream input;	/* Input stream from port */
	private OutputStream output;	/* Input stream from port */
	private String portName = "UART";/* System-dependent name of port */
	private int total = 0;

	/** Open a connection to the device */
	public void open(int rate) throws IOException
	{
		try {
			port = getSerialPort(rate);
			input = port.getInputStream();
			output = port.getOutputStream();
			port.addEventListener(this);
			port.notifyOnDataAvailable(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/** Reset and close the connection */
	public void close() throws IOException
	{
		port.close();
	}

	/** Find the serial port to use */
	private SerialPort getSerialPort(int rate) throws
		PortInUseException, UnsupportedCommOperationException
	{
		Enumeration ports = CommPortIdentifier.getPortIdentifiers();
		HashMap names = new HashMap();
		System.out.println("Listing ports:");
		while (ports.hasMoreElements()) 
		{
			CommPortIdentifier id = (CommPortIdentifier)
						ports.nextElement();
			System.out.println("  " + id.getName());
			names.put(id.getName(), id);
		}
			
		if (!names.containsKey(portName))
			throw new NullPointerException(
					"Could not find serial port");

		CommPortIdentifier id = (CommPortIdentifier)names.get(portName);
		System.out.println("Using port: " + id.getName());
		SerialPort port = (SerialPort)id.open("RLE Monitor", 2000);
		port.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
		port.setSerialPortParams(rate, SerialPort.DATABITS_8,
				SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
		return port;
	}

	/** Serial event handler */
	public void serialEvent(SerialPortEvent event)
	{
		if (event.getEventType() != SerialPortEvent.DATA_AVAILABLE)
			return;
		try {
			int count = input.available();
			total += count;
			System.out.println(count + "\t\t" + total);
			input.skip(count);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] argv)
	{
		try {
			Term term = new Term();
			term.open(Integer.valueOf(argv[0]).intValue());
			System.in.read();
			term.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

