# -*- coding: utf-8 -*-
import subprocess
import datetime
import time
import os

header = "test"
oldname = ""
first = True

while True:
	time.sleep(0.1)
	if int(datetime.datetime.now().strftime("%M")) % 5 == 0:
		start_year = str(datetime.datetime.now().strftime("%Y"))[2:]
		start_month = str(datetime.datetime.now().strftime("%m"))[:]
		if start_month < 10:
			start_month = "0" + str(datetime.datetime.now().strftime("%m"))[:]
		start_day = str(datetime.datetime.now().strftime("%d"))[:]
		if start_day < 10:
			start_day = "0" + str(datetime.datetime.now().strftime("%d"))[:]
		start_hour = str(datetime.datetime.now().strftime("%H"))[:]
		if start_hour < 10:
			start_hour = "0" + str(datetime.datetime.now().strftime("%H"))[:]
		start_minute = str(datetime.datetime.now().strftime("%M"))[:]
		if datetime.datetime.now().strftime("%M") < 10:
			start_minute = "0" + str(datetime.datetime.now().strftime("%M"))[:]
		filename = header + str(start_year)[:] + str(start_month)[:] + str(start_day)[:] + str(start_hour)[:] + str(start_minute)[:]
		print filename
		#subprocess.Popen(["rtl_power", "-f", "53.740M:53.760M:50", "-i", "1", "-O", "-e", "120", filename+".csv"])
		#subprocess.Popen(["sh", "rtl_fm", "-M", "usb", "-f", "53.745M", "-s", "48k", "|", "sox", "-r", "44.1k", "-t", "raw", "--encoding", "sign", "-b", "16", "-c", "1", "-", "-n", "rate", "20k", "trim", "0", "300", "spectrogram", "-X", "10", "-o", filename+".png"])
		#subprocess.Popen(['sh -c "cd"'])
		subprocess.Popen(['sh -c "rtl_fm -M usb -f 53.745M -s 48k | sox -r 44.1k -t raw --encoding sign -b 16 -c 1 - -n rate 20k trim 0 300 spectrogram -X 10 -o' +" "+ filename+".png"+'"'],shell=True)
		
		"""sdr = subprocess.Popen(["rtl_fm", "-M", "usb", "-f", "53.745M", "-s", "48k"], 
                        stdout=subprocess.PIPE,
                        )

		sox = subprocess.Popen(["sox", "-r", "44.1k", "-t", "raw", "--encoding", "sign", "-b", "16", "-c", "1", "-", "-n", "rate", "20k", "trim", "0", "300", "spectrogram", "-X", "10", "-o", filename+".png"],
                        stdin=sdr.stdoust,
                        stdout=subprocess.PIPE,
                        )"""
		if first != True:
			pass
			#subprocess.Popen(["python", "./heatmap.py", oldname+".csv", oldname+".png"])
		time.sleep(70)
		first = False
		oldname = filename[:]