#!/usr/bin/perl
use warnings;
use strict;

my @pulses = @ARGV || die "usage: $0 *.pulses";

my $khz = 50; # ir-ctl --features | grep Resolution
# 1 ms = 1000 Hz = 1 kHz

mkdir 'new';
open(my $metadata, '>', 'new/metadata');

print $metadata qq{
[global]
sigrok version=0.5.1

[device 1]
capturefile=logic-1
total probes=8
total analog=0
unitsize=1
samplerate=$khz kHz
probe1=IR
};

=for later
foreach my $ch ( 1 .. scalar($#pulses) ) {
	my $name = $pulses[ $ch - 1 ];
	print $metadata qq{probe$ch=$name\n};
}
=cut

open(my $logic, '>', 'new/logic-1-1');

my $bits_left = 0;
my $state_left = 0;

sub write_logic {
	my ($t,$s) = @_;

	$t = $t / $khz; # convert time to bits

	my $patt = $s ? "\x01" : "\x00";
	print $logic ( $patt x $t );
};


while(<>) {
	if (/^pulse\s(\d+)/ ) {
		write_logic( $1, 1 );
	} elsif ( /^space\s(\d+)/ ) {
		write_logic( $1, 0 );
	} elsif ( /^timeout\s(\d+)/ ) {
		write_logic( $1, 0 );
	} else {
		warn "IGNORE: $_\n";
	}
}

close($metadata);
close($logic);

open(my $version, '>', 'new/version');
print $version '2';
close($version);

system "cd new ; zip ../new.sr *";
