import os
import socket
import MatlabFuncs as m
from loadresultsfromdisk import loadresultsfromdisk

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

	#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')
	else:
		filelist.append(md.miscellaneous.name+'.outbin')
	cluster.Download(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 m.ispc():
			os.remove(md.private.runtimename+'.tar.gz')

	#erase input file if run was carried out on same platform.
	hostname=socket.gethostname()
	if m.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+'.toolkits')
			if not m.ispc():
				os.remove(md.miscellaneous.name+'.queue')
			else:
				os.remove(md.miscellaneous.name+'.bat')

	return md

