import sys
import shutil
import os, errno
from os import listdir
from os.path import isfile, join


"""
This program is a helper script to sort images generated by Basler's free Pylon software into four directories
It can be altered to work with different files or naming conventions.

Prior to running sort.py (this file), 
1) load 'arduino_SSHTS_sample_script.ino' to your arduino Uno board, 
2) set the camera to 'trigger' mode (if using a Basler camera, do this through their free pylon software) and
3) collect data by cycling to mode 5 (see comments in 'arduino_SSHTS_sample_script.ino')
This will generate a single directory with sequentially saved images

This python script moves these images into four new directories (as there are four LEDS used in the ssHTS system).
The only parameter is the source directory with your recently saved images.

Usage:
1. Open up cmd prompt
2. cd to desktop i.e.      cd desktop
3. run the command i.e.	   python Sort.py "C:\Users\Admin\Documents\Test Run\TEST20"

"""

mypath = ""

if len(sys.argv) > 1:
	mypath = (sys.argv[1])
	print (mypath)
else:
	print ("Use the directory name as the argument.")
	sys.exit()

onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

folder1 = mypath + "\\1\\"
folder2 = mypath + "\\2\\"
folder3 = mypath + "\\3\\"
folder4 = mypath + "\\4\\"
folder5 = mypath + "\\5\\"
def create_folder(directory):
	try:
	    os.makedirs(directory)
	except OSError as e:
	    if e.errno != errno.EEXIST:
	        raise

def sort(files):
	for f in files:
		print (f)
		if(f.startswith( 'Basler' )):
			a = f.split("_")[3]
			b = a.split(".")[0]
			c = b.lstrip("0")
			mod4 = (int(c)) % 4
			oldpath = mypath + "\\" + f
			if (mod4 == 0):
				shutil.move(oldpath,  folder4 + f)
			elif (mod4 == 3):
				shutil.move(oldpath,  folder3 + f)
			elif (mod4 == 2):
				shutil.move(oldpath,  folder2 + f)
			elif (mod4 == 1):
				shutil.move(oldpath,  folder1 + f)
			elif (mod4 == 4):
				shutil.move(oldpath,  folder5 + f)
			print (c)

def initialize():
	create_folder(folder1)
	create_folder(folder2)
	create_folder(folder3)
	create_folder(folder4)
	sort(onlyfiles)

initialize()


