#!/usr/bin/env /usr/bin/python3.7

"""
Filter converting printable input of pulse/space such as generated by
mode2(1) to the binary representation used by the udp driver. Valid
input lines looks like

    pulse 12345
    space 23456

All other type of input is silently ignored. Lengths are in microsecods.
"""

import argparse
import os
import struct
import sys
import config


def irtext2udp(file_, resolution):
    """ Convert pulse/space printable data to udp driver binary format. """

    for line in file_:
        parts = line.split()
        if len(parts) != 2 or not parts[0] in ["pulse", "space"]:
            continue
        try:
            duration = int(parts[1])
        except ValueError:
            continue
        ticks = int(duration / resolution)
        if ticks < (1 << 15):
            payload = ticks
            if parts[0].startswith('pulse'):
                payload += (1 << 15)
            buf = struct.pack('<H', payload)
        else:
            payload = 0
            if parts[0].startswith('pulse'):
                payload += (1 << 15)
            buf = struct.pack('<H', payload)
            buf = struct.pack('<L', ticks)
        os.write(1, buf)


def main():
    """ Indeed: main function. """

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-r", "--resolution", "--clocktick", default=1000000 / 16384,
        type=int, help="Resolution (us per tick ), see irtext2udp(1).")
    parser.add_argument(
        "-v", "--version", action="store_true", help="Print version.")
    parser.add_argument(
        'infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin)
    args = parser.parse_args()

    if args.version:
        print(config.VERSION)
        sys.exit(0)

    irtext2udp(args.infile, args.resolution)


if __name__ == "__main__":
    main()
