#!/usr/bin/env python
import argparse
import sys
import subprocess
import os.path

parser = argparse.ArgumentParser(description='Unified interface for running Matlab programs on the command line.')
parser.add_argument('file', type=str, 
                   help='the path to the matlab script or function file to execute')
parser.add_argument('arguments', metavar='A', nargs='*', type=str,
				   help='positional arguments to pass to the function (ignored if the file is a script)')

args = parser.parse_args()

if sys.platform == 'darwin':
    exec_path = '/Applications/Octave.app/Contents/Resources/usr/bin/octave-cli'
    lib_dir = 'osx'
elif sys.platform.startswith('linux'):
    exec_path = 'octave'
    lib_dir = 'linux'
else:
    print 'Not supported.'
    sys.exit(99)

env_dir = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(os.path.realpath(__file__))), lib_dir))
dir_name = os.path.abspath(os.path.dirname(args.file))
file_name = os.path.basename(args.file)
function_name = os.path.splitext(file_name)[0]

def bash_to_matlab(a):
	try:
		return str(int(a))
	except ValueError:
		pass

	try:
		return str(float(a))
	except ValueError:
		pass

	return "'" + a + "'"

arguments = map(bash_to_matlab, args.arguments)

matlab_runner_script = """cd('%s'); addpath('%s'); addpath('%s'); try %s(%s); exit(0); catch, ME = lasterror; fprintf(2, '%%s\\n', ME.message); exit(1); end"""%(dir_name, env_dir, dir_name, function_name,','.join(arguments))

try:
	subprocess.check_call(
		[exec_path, 
            '--eval',
			matlab_runner_script
		], stdout=sys.stdout, stderr=sys.stderr)
	sys.exit(0)
except subprocess.CalledProcessError as e:
	sys.exit(e.returncode)











