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

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

	if(ARGC >= 2) {
		cmds = ARGC;
		for(i = 1; i < cmds; i++) {
			packet = data[ARGV[i]];
			if(packet) send(packet);
			else printf("Unknown command %s\n", ARGV[i]);
		}
		exit 0;
	}
}

{
	# 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)
	bit_t = 600;
	one_t = 7000;
	zero_t = 4400;
	sync_t = 3200;
	tailspace = 100;

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

	# x bit toggle per press
	press = (press++)%2

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

	t = data_period;

	# IR data sync header
	printf("%d %d\n", bit_t, sync_t) >> device;
	printf("%d %d\n", bit_t, sync_t) >> device;

	# IR data packet
	for(i = 1; i <= length(data); i++) {
		bit = substr(data, i, 1);
		if(bit == "x") bit = press;
		if(bit == "1") printf("%d %d\n", bit_t, one_t) >> device;
		else printf("%d %d\n", bit_t, zero_t) >> device;
	}

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