#!/usr/bin/awk -f
###
# Script to decode IR (16-8 format) rise-time data
###
{
	if(!new) {
		startsec = $1;
		startusec = $2;
		new = 1;
	}

	sectime = $1 - startsec;
	usectime = $2 - startusec

	time = sectime * 1000000 + usectime;
	delay = time - lasttime;

        if(delay < 0) {
		error = 1;
		buffer = "";
	}
        else if(delay < 2000) buffer = buffer "0";
        else if(delay < 3000) buffer = buffer "1";
        else if(!error) {
		if(buffer != "") decode(buffer);
		buffer = ""
	}

	lasttime = time;
	error = 0;
	if(delay < 0) error = 1;

}

###
# Decode 32 bit packet into two 8 bit numbers
###
function decode(buf) {
	# check packet length
	if(length(buf) != 32) {
		printf("decode: incorrect packet length\n");
		return;
	}

	# id byte
	id1 = substr(buf, 1, 8);
	id2 = logical_not(substr(buf, 9, 8));

	# command/data byte
	data1 = substr(buf, 17, 8);
	data2 = logical_not(substr(buf, 25, 8));

	# check data integrity
	if((id1 != id2) || (data1 != data2)) {
		printf("decode: packet corrupt\n");
		return;
	}

	printf("%d %d\n", bin2dec(id1), bin2dec(data2));
}

###
# bin-str logical not'er
###
function logical_not(buf) {
	gsub("1", "2", buf);
	gsub("0", "1", buf);
	gsub("2", "0", buf);
	return buf;
}

###
# LSB first bin-str -> dec number converter
###
function bin2dec(buf, i, n) {
	n = 0;
	for(i = 0; i < length(buf); i++) if(substr(buf, i+1, 1) == "1") n += 2**i;
	return n;
}
