#------------------------------------------------------------------
#
# ElectroPi EXPLORER
#
# - A way for folks to turn WAV's into control codes.
#
# To use this script, record a ~0.5 second sample of your remote's
# control code at 22050 Hz in your DAW of choice. Then, export the
# recording as a mono, 16-bit WAV file with a 22050 Hz sample rate.
# Then, include the exported file as an argument to this script:
#
# sudo python decode.py recording.wav
#
#------------------------------------------------------------------

# Import modules
from __future__ import division
import sys
import wave, struct
import os
import time

rows, columns = os.popen('stty size', 'r').read().split() # Get console width for pretty output!
os.system("clear") # Clear the terminal

# Check if an input file was specified, die if it was not.
try:
	inFile = sys.argv[1]
except:
	print "You must specify an input file as an argument. (e.g. 'sudo python decode.py infile.wav')"
	sys.exit(0)

# Function for progress bar printing
def drawProgressBar(percent, barLen = 20, num=" ", sep=" ",den=" ",units=" "):
    sys.stdout.write("\r")
    progress = ""
    for i in range(barLen):
        if i < int(barLen * percent):
            progress += "="
        else:
            progress += " "
    sys.stdout.write("[%s] %.2f%% %s%s%s %s" % (progress, percent * 100,num,sep,den,units))
    sys.stdout.flush()

# Function to get the median of a number set
def median(numbers):
    return (sorted(numbers)[int(round((len(numbers) - 1) / 2.0))] + sorted(numbers)[int(round((len(numbers) - 1) // 2.0))]) / 2.0

# Find the lowest and highest number of a set
def lowHigh(numbers):
	lowest = 100000
	highest = 0
	last = 0
	for item in numbers:
		if item > highest:
			highest = item

	for item in numbers:
		if item < lowest:
			lowest = item

	return [lowest,highest]

# Passes data to drawProgressBar()
def printPercent(soFar,total):
	percent = soFar/total
	drawProgressBar(percent,50,soFar,"/",total,"samples")

start_time = time.time() # GO!

print "\n--------------------"
print "ElectroPi RF Decoder"
print "by Connor Nishijima"
print "--------------------\n"

print "Reading WAV file..."
waveFile = wave.open(inFile, 'r') # Open WAV file