# CMSC 471 - Fall 2008
# Author: Don Miner
# Last updated: 10/23

# This program takes two command line arguments:
#		arg1 : the problem file. This file contains the locations of the cities. Example:
#					5 
#					23.4 109.73 
#					0.4 192.1243 
#					1.1 193.13 
#					10343.13 0.00001 
#					111.3 41.013 
#
#		arg2 : the path file. This file contains the order of cities, by index, to visit.
#				This file may look like:
#					3 2 1 4 0
#
#		Note that the number of cities must equal the length of the path

# You may report bugs to this checking script by emailing the instructor.
# Any bug reports that result in a change to this script will yield a small amount of extra credit.
# Bugs include logic errors, invalid output or causing the program to exit ungracefully (e.g.,
# unhandled exception).

# sample run: python TSP_checker.py tspprob1.txt tspsoln1.txt

import sys



# gets the pieces from the problem file
def get_problem():
	try:
		problem_file = open(sys.argv[1])
	except IndexError:
		print "No problem file given"
		sys.exit(1)
	except IOError:
		print "Problem opening file", sys.argv[1]
		sys.exit(1)

	lines = [ line.strip() for line in problem_file.readlines() if len(line.strip()) > 0 ]

	if len(lines)-1 != int(lines[0]):
		print "Invalid number of cities,", len(lines)-1, "!=", int(lines[0])
		sys.exit(1)
	
	lines = lines[1:]

	try:
		lines = [ [ float(c) for c in line.strip().split()] for line in lines ]
	except ValueError:
		print "failed to convert something to a float"
		sys.exit(1)

	for line in lines:
		if len(line) != 2:
			print "invalid line", line
			sys.exit(1)
			
	return lines

# gets the path from the path file
def get_input():

	try:
		move_file = open(sys.argv[2])
	except IndexError:
		print "No path file given"
		sys.exit(1)
	except IOError:
		print "Problem opening file", sys.argv[2]
		sys.exit(1)
	
	lines = [ line for line in move_file.readlines() if len(line.strip()) > 0 ]

	if len(lines) != 1:
		print "invalid number of lines in path file (there should only be one)"
		sys.exit(1)
	
	try:
		lines = [ int(c) for c in lines[0].strip().split() ]
	except ValueError:
		print "failed to convert something to a int"
		sys.exit(1)
	
	
	sorted_lines = lines[:]
	sorted_lines.sort()
	
	if sorted_lines != range(len(lines)):
		print "invalid path, is there some city missing?"
		sys.exit(1)

	return lines

def distance(p1, p2):
	x1, y1 = p1
	x2, y2 = p2

	return ((y2 - y1)**2 + (x2 - x1)**2)**.5


problem = get_problem()
inp = get_input()

if len(inp) != len(problem):
	print "the number of cities does not match the length of the path"
	sys.exit(1)

# wrap around the path
run_sum = distance(problem[inp[0]], problem[inp[-1]]) 

# calculate the rest of the path
for i in range(len(inp) - 1):
	run_sum += distance(problem[inp[i]], problem[inp[i+1]])
	
	
print "The path length is:", run_sum