package org.josast.ModuleSoundModem;

import java.util.Arrays;

/**
 * 
 * 
 * @author christophe
 *
 */
public class kiss {

	public static byte FEND = (byte) 0xC0;

	// TFEND ($DB, $DC)

	public static byte FESC = (byte) 0xDB;
	public static byte TFEND = (byte) 0xDC;

	// FESC, TFESC ($DB, $DD).
	public static byte TFESC = (byte) 0xDD;

	byte[] kissdata = null;

	public kiss(byte[] data) {
		kissdata = data;
	}

	public byte[] toRaw() throws KissException {
		byte[] rawData = null;
		rawData = new byte[kissdata.length];

		if (kissdata[0] != FEND) {
			throw new KissException("FEND (0xC0)  value not find at the beginning of the frame ");
		}
		if (kissdata[kissdata.length - 1] != FEND) {
			throw new KissException("FEND (0xC0)  value not find at the end of the frame ");
		}
		int cptraw = 0;
		int i = 1;
		while (kissdata[i] != FEND) {
			if (kissdata[i] != FESC) {
				rawData[cptraw++] = kissdata[i++];
			} else {
				if (kissdata[i + 1] == TFEND) {
					
					rawData[cptraw++] = FEND;
					i = i + 2;
				} else if (kissdata[i + 1] == TFESC) {
					
					rawData[cptraw++] = FESC;
					i = i +2;
				} else {
					rawData[cptraw++] = kissdata[i++];
				}

			}

		}

		return Arrays.copyOf(rawData, cptraw);

	}

}
