#!/bin/bash

function SendByte {
    # Startbit
    echo -n $ZERO >> KC.raw

    # Data bits - LSB first
    mask=1
    for i in {0..7}; do
        if ((($1 & mask) == 0)); then
            echo -n $ZERO >> KC.raw
        else
            echo -n $ONE >> KC.raw
        fi
        mask=$((mask*2))
    done

    # Stopbits
    echo -n $ONE >> KC.raw
    echo -n $ONE >> KC.raw
}


ZERO=$(echo -e "[payload removed: 588 characters]")
ONE=$(echo -e "[payload removed: 588 characters]")

rm -f KC.raw

# 40ms of lead-in to let the circuit stabilize
for i in {1..12}; do
    echo -n $ONE >> KC.raw
done

SendByte 1      #10000000
SendByte 85     #10101010
SendByte 170    #01010101

# 10ms of delay
for i in {1..3}; do
    echo -n $ONE >> KC.raw
done

SendByte 24      #00011000

# 10ms of lead-out
for i in {1..3}; do
    echo -n $ONE >> KC.raw
done

# Convert the raw data to a real .wav file that ltspice can use
sox -t raw -b 8 -e unsigned-integer -r 44100 -c 1 KC.raw KC.wav
rm KC.raw
