import os
import platform
import socket
from MatlabFuncs import *

def loadresultsfromcluster(md,runtimename=False):
	"""
	LOADRESULTSFROMCLUSTER - load results of solution sequence from cluster
 
	    Usage:
	       md=loadresultsfromcluster(md,runtimename);
	"""

	#retrieve cluster, to be able to call its methods
	cluster=md.cluster

	if runtimename:
		md.private.runtimename=runtimename
	end

	#Download outputs from the cluster
	filelist=[md.miscellaneous.name+'.outlog',md.miscellaneous.name+'.errlog']
	if md.qmu.isdakota:
		filelist.append(md.miscellaneous.name+'.qmu.err')
		filelist.append(md.miscellaneous.name+'.qmu.out')
		if 'tabular_graphics_data' in md.qmu.params:
			if md.qmu.params['tabular_graphics_data']:
				filelist.append('dakota_tabular.dat')
		filelist.append(md.miscellaneous.name+'.outbin')
	Download(cluster,md.private.runtimename,filelist)

	#If we are here, no errors in the solution sequence, call loadresultsfromdisk.
	md=loadresultsfromdisk(md,md.miscellaneous.name+'.outbin')

	#erase the log and output files
	if md.qmu.isdakota:
		os.remove(os.path.join('qmu'+str(os.getpid()),md.miscellaneous.name+'.outlog'))
		os.remove(os.path.join('qmu'+str(os.getpid()),md.miscellaneous.name+'.errlog'))
	else:
		os.remove(md.miscellaneous.name+'.outlog')
		os.remove(md.miscellaneous.name+'.errlog')
		os.remove(md.miscellaneous.name+'.outbin')
		if not 'Windows' in platform.system():
			os.remove(md.private.runtimename+'.tar.gz')

	#erase input file if run was carried out on same platform.
	hostname=socket.gethostname().lower().split('.')[0]
	if strcmpi(hostname,cluster.name):
		if md.qmu.isdakota:
			os.remove(os.path.join('qmu'+str(os.getpid()),md.miscellaneous.name+'.bin'))
			os.remove(os.path.join('qmu'+str(os.getpid()),md.miscellaneous.name+'.queue'))
		else:
			os.remove(md.miscellaneous.name+'.bin')
			os.remove(md.miscellaneous.name+'.petsc')
			if not 'Windows' in platform.system():
				os.remove(md.miscellaneous.name+'.queue')
			else:
				os.remove(md.miscellaneous.name+'.bat')

	return md

