#!/usr/bin/awk -f 
###
# Script to generate delay values for 16-8 space style remotes.
###
BEGIN {
	# Get code defs
	while((getline < "codes") > 0) data[$1] = $2;

	# Show what codes we know
	printf("Known codes: ");
	for(tmp in data) printf("%s ", tmp);
	printf("\n");
}

{
	# Send all commands
	for(i = 1; i <= NF; i++) {
		packet = data[$i];
		if(packet) send(packet);
		else printf("Unknown code %s\n", $i);
	}
}

###
# This function forms and sends the IR Packets
###
function send(data) {
	# IR format definitions (us)
	data_period = 550;
	tailspace = 10000;

	# IR control params
	carrier_period = 20;
	device = "irctrl";

	# irctrl carrier period and compensate values
	printf("%d\n", carrier_period) > device;

	t = data_period;

	# IR data sync header
	printf("%d %d\n", 16*t, 8*t) >> device;

	# IR data packet
	for(i = 1; i <= length(data); i++) {
		bit = substr(data, i, 1);
		if(bit == "1") printf("%d %d\n", t, 3*t) >> device;
		else printf("%d %d\n", t, t) >> device;
	}

	# Stop bit
	printf("%d %d\n", t, tailspace) >> device;
	close(device);
}
