@Override
	public void serialEvent(SerialPortEvent ev)
	{
		if(ev.getEventType() != SerialPortEvent.DATA_AVAILABLE)
			return;
		InputStream in = port.getInputStream();
		int b;
		try
		{
			b = in.read();
			if(b == ProtocolConstants.MARK_RECORD)
			{
				int len = in.read();
				int offset = (in.read() << 8) + in.read();
				int datType = in.read();
				if(datType != 0)
				{
					System.err.println("Data type is not 0 but " + datType);
					return;
				}
				byte[] bytes = new byte[len];
				for(int i = 0; i < len; i++)
					bytes[i] = (byte) in.read();
				byte checkSum = (byte) in.read();
				if(new DataRecord(offset, bytes).getRecordChecksum() != checkSum)
					System.err.println("Calculated checksum does not match the received one");
				System.out.println("Received:\t" + new DataRecord(offset, bytes, checkSum).toHEXString());
				System.out.println("Exiting");
				System.exit(0);
			}
			else
			{
				ByteArrayOutputStream bytes = new ByteArrayOutputStream();
				bytes.write(b);
				bytes.write(in.read());
				bytes.write(in.read());
				String cmd = new String(bytes.toByteArray());
				if(cmd.equalsIgnoreCase(ProtocolConstants.CMD_ACKNOWLEDGE))
				{
					System.out.println("Record aknowledged");
					send();
				}
				else if(cmd.equalsIgnoreCase(ProtocolConstants.CMD_NEXT))
					System.out.println("NEXT record issued. We are not sending it.");
				else if(cmd.equalsIgnoreCase(ProtocolConstants.CMD_RESEND))
				{
					System.err.println("RESEND signal received. Resending");
					sent = false;
					send();
				}
				else
					System.err.println("Unexpected command received: '" + cmd + "'. No response");
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}