#
# Copyright © 2020 MSC.Software Corporation
#  
# Permission to use Scripts
#  
# Permission is granted to MSC.Software customers with valid licenses of the MSC Apex™ software 
# to use script files posted on this page (collectively “Scripts”) solely for customers’ own authorized 
# internal use in conjunction with licensed use of the MSC Apex software.  
# No other use is permitted.  No license to MSC Apex or other software is granted under this Permission.
#  
# SCRIPTS ARE PROVIDED ON AN "AS-IS" BASIS, WITH NO WARRANTIES OF ANY KIND.  USE OF THE SCRIPTS IS AT CUSTOMER'S SOLE RISK.
#  
# IN NO EVENT SHALL MSC.SOFTWARE CORPORATION, ITS AFFILIATES, SUBSIDIARIES, SUPPLIERS, AGENTS, REPRESENTATIVES OR EMPLOYEES BE LIABLE FOR ANY 
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, 
# STRICT LIABILITY, OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION USE OF THE SCRIPTS, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  
#  
# Customer shall indemnify, defend and hold MSC.Software Corporation, its affiliates, subsidiaries, suppliers, agents, 
# employees or representatives (collectively, “Indemnified Parties”) harmless from and against any third-party claims 
# brought against Indemnified Parties rising out of or in connection with Customer’s use of the Scripts.
#
import os
import time
import datetime
import sys
import traceback
import importlib

# This py script is either called from a macro StartIberianLynxFP2Utils, or using the new event Trigger mechanism
# Using the (old) macro method, the exported bdf is digged up from the log file
# Using the new event trigger, the exported bdf is passed as a command line argument sys.argv[1]
from aux_functions_v106b import *
importlib.reload(sys.modules['aux_functions_v106b'])
from aux_functions_v106b import *



def ProcessSettingsFileOptions(bdf_full_name,SettingsD,exportOptionFlag,OptionsD={}):
	pathDir = os.path.dirname(os.path.realpath(__file__))
	

	print("*** Export Option **** ", exportOptionFlag)

	if( bdf_full_name.replace('.bdf','').strip() == "" ):
		print("Something went wrong with the bdf export, please check the bdf")
		
	else:

		# Rename orig file, if needed
		bdf_path = os.path.dirname(bdf_full_name)
		bdf_name = os.path.basename(bdf_full_name)

		# if there exist an existing orig_file, delete this file
		if os.path.isfile(bdf_path + '/orig_' + bdf_name):
			os.remove(bdf_path + '/orig_' + bdf_name)
			print("*** Information *** Overwrites existing file: " + bdf_path + '/orig_' + bdf_name)
		
		# save copy
		old_bdf = bdf_path + '\\orig_' + bdf_name
		shutil.copyfile(bdf_full_name, old_bdf)
		
	
		#==========================CreatePatranGroups==========================================================
		# create patran groups per part and sub assembly- bdf must be exported with option hierarchy
		try:
			ses_group_flag = SettingsD['System']['CreatePatranGroups']
			#print("SettingsD['System']['CreatePatranGroups']:" + ses_group_flag)
		except:
			ses_group_flag = "False"

		if ses_group_flag.upper() == "YES" or ses_group_flag.upper() == "TRUE":
			print(
				"*** Information *** Generate Patran session file creating groups based on Parts and Assemblies\n")
			AssyD, prefixD, new_tmp_bdf, root_bdf = read_hierarchy(bdf_full_name, SettingsD)
			# AssyD, prefixD, new_tmp_bdf=read_hierarchy(bdf_full_name.replace('/','\\'),SettingsD)
			if AssyD != {}:
				print(" ----- prefixD -----")
				print(prefixD)
				print("--- end prefixD ----")
				print()
				print(" ----- AssyD -----")
				print(AssyD)
				print("--- end AssyD ----")
				groups_ses_file=create_patran_group_ses(bdf_full_name, AssyD, prefixD, SettingsD)

				# rename original file to orig_
				old_bdf = os.path.dirname(bdf_full_name) + '\\orig_' + os.path.basename(bdf_full_name)
				save_orig_file_if_not_new(old_bdf, bdf_full_name)
				# rename tmp_bdf (new flat) remove orig file first
				os.remove(bdf_full_name)
				os.rename(new_tmp_bdf, bdf_full_name)
			else:
				print(
					"*** Warning *** There appears to be no assembly structure, or, bdf was exported without include file structure, skipping...\n")
				print("There appears to be no assembly structure, or, bdf was exported without include file structure, no session file created")
			#print("new_tmp_bdf " + new_tmp_bdf)
			#print("bdf_full_name " + bdf_full_name)
		else:
			print("*** Information *** Creation of patran groups not requested")

		
		#==========================Convert Element Thickness to PSHELL==========================================================	
		
		try:
			
			convert_node_thick_flag = SettingsD['System']['NodeThicknessToPshells']
			thick_inc=float(SettingsD['System']['NodeThicknessToPshellsInc'])
			thick_lo_limit=float(SettingsD['System']['NodeThicknessToPshellsLower_T'])
			thick_up_limit=float(SettingsD['System']['NodeThicknessToPshellsUpper_T'])
			
		except:
			convert_node_thick_flag = "False"
			thick_lo_limit=0
			thick_inc=0.01
			thick_up_limit=100
			
			print("*** Information *** No  conversion of node thickness to PSHELL\n")
			
		if convert_node_thick_flag == "True":
			print("*** Information *** Start conversion of node thickness to PSHELL\n")
			process_nodethickness_to_pshell(bdf_full_name, SettingsD, thick_inc, thick_lo_limit, thick_up_limit)	
		
		#==========================MergeTieRbars==========================================================	
		
		# This is obsolete from v2021 
		merge_tie_flag = "False"
		
		# converts Tie RBARs to  Node2Node (equivalencing)
		# try:
			# merge_tie_flag = SettingsD['System']['MergeTieRbars']
			
		# except:
			# merge_tie_flag == "False"

		#==========================GlueToEqNodes==========================================================		
			
		# converts glue contact to Node2Node (equivalencing) for matching mehses
		try:
			eq_nodes_flag = SettingsD['System']['GlueToEqNodes']
		except:
			eq_nodes_flag = "False"

		#==========================ExportSXNAME==========================================================	
			
		# create SXNAME based on names in bdf file (only triggered if there is a description for the MAT or prop card)
		try:
			ExportSXNAME = SettingsD['System']['ExportSXNAME']	
		except:
			ExportSXNAME = "False"
		if ExportSXNAME.upper() == "TRUE" or ExportSXNAME.upper() == "YES":
			# read name from mat and props and wrtie back to bdf file
			print("*** Information *** Requested creation of SXNAME cards to be wtitten to bdf\n")
			read_descriptions(bdf_full_name)
			
		#==========================RigidLink to Spring==========================================================	
			
		# Convert rigids
		try:
			contype = SettingsD['System']['RigidLink']
			springtype = SettingsD['System']['Spring']
		except:
			print("No connection types detected in settings file")
			springtype = "None"
			if safe_mode:
				print("No conversions done")
				contype = ""
			else:
				print("Job assumes default RBE2-CBAR-RBE2")
				contype = "RBE2_CBAR"

		# Check for rigid links 		
		if contype == "RBEX_CBAR":
			# print "start converting rigid connections of type  RBEX-RBAR  to   RBE2-CBAR"
			print("*** Information *** Start converting rigid connections of type RBEX-RBAR to RBEX-CBAR\n")
			process_rigidlink_2_CbarRbe2(bdf_full_name, SettingsD)
				
		elif contype == "RBEX_CBUSH":
			# print "start converting rigid connections of type  RBEX-RBAR  to   RBE2-CBUSH"
			print("*** Information *** Start converting rigid connections of type RBEX-RBAR  to RBEX-CBUSH\n")
			process_rigidlink_2_CbushRbe2(bdf_full_name, SettingsD)
		else:
			print("*** Information *** No conversion of rigids connections.  RBEX-RBAR is used")

		# check for Springs 		
		if springtype == "RBE2_CBUSH":
			print("*** Information *** Start converting Springs of type  RBEX-CBUSH1D  to   RBE2-CBUSH\n")
			process_spring_2_CbushRbe2(bdf_full_name, SettingsD)
		else:
			print("*** Information *** No conversion of springs.  RBEX-CBUSH1D is used")

		if eq_nodes_flag == "True":
			print("*** Information *** Converting Contacts between coincident nodes to N2N  (equivalenced) mesh")
			process_glue_to_eqnodes(bdf_full_name, SettingsD)

		if merge_tie_flag == "True":
			print("*** Information *** Converting Tie zero length RBARs to N2N  (equivalenced) mesh")
			process_tie_to_eqnodes(bdf_full_name)

			
		#==========================ZeroLength Bushes==========================================================		
		try:
			zlf = SettingsD['RBEX_CBUSH']['ZeroLength']
			if zlf.upper() == "TRUE" or zlf.upper() == "YES" or zlf == "1":
				ZeroLengthFlag = True
			else:
				ZeroLengthFlag = False
		except:
			print("except ZeroLengthFlag")
			ZeroLengthFlag = True

		if ZeroLengthFlag:
			print("*** Information *** Converting CBUSHES in RBEx connections to zero length ")
			process_Cbush_2_ZeroLength(bdf_full_name, SettingsD)

		#==========================MNF Generation==========================================================		
		
		# mnf_ will export and optionally run job to generate an mnf file			
		if exportOptionFlag == "mnf_":
			out_msg = process_bdf_mnf(bdf_full_name, SettingsD)
			print(out_msg)
		
		#==========================GenerateSE==========================================================		
		
		# se reduction  will export and optionally run job to generate an external SE file
		#
		try:
			se_flag = SettingsD['System']['GenerateSE']
		except:
			se_flag = "False"
			print("*** Information *** No Super element generation requested in the settings file\n")

		try:
			vtu_flag = SettingsD['System']['ExportVtu']
			#print("*** Information *** exporting on vtu format initiated\n")
		except:
			vtu_flag = "False"
			print("*** Information *** No VTU export requested in the settings file\n")

		if exportOptionFlag == 'se' and se_flag.upper() == "TRUE" :
			print("*** Information *** Creating external SE ")
			out_msg = process_generate_se(bdf_full_name, SettingsD)
			print(out_msg)
			print(out_msg)

		# if files is vtu_... create vtu file  (Obs this is a demonstrator only)

		#==========================Export VTU==========================================================
		elif exportOptionFlag == "vtu_" and vtu_flag.upper() == "TRUE":
			process_bdf_vtu(bdf_full_name)
			print("vtu file written")
			
		#==========================Export Abaqus inp==========================================================	

		# if files is inp_... create Abaqus input file
		elif exportOptionFlag == "inp_":
			abq_goFlag=True
			try:
				import apex2aba_v12
				importlib.reload(sys.modules['apex2aba_v12'])
				import apex2aba_v12
			except:
				print("Problem loading librariers for Abaqus Export")
				abq_goFlag=False
				
			if 	abq_goFlag==True:
				print("*** Information *** Processing Abaqus file \n")
				
				bolt_pre_load_flag=process_sol400_template(bdf_full_name, SettingsD, OptionsD)
				if SettingsD['NASTRAN_JOB_SETUP']['CreateBoltPreLoad'].upper().replace("YES","TRUE") == "TRUE":
					SettingsD['ABAQUS_EXPORT']['AbaqusBoltExist']="True"
				else:
					SettingsD['ABAQUS_EXPORT']['AbaqusBoltExist']="False"
				out_inp = apex2aba_v12.process_bdf_inp(bdf_full_name,SettingsD)
				print("inp file written")

			
		#==========================RunNastran SOL101==========================================================		
			
		# export and optionally run sol101 job
		elif exportOptionFlag == "sol101":
		
			SettingsD['NASTRAN_JOB_SETUP']['CreateBoltPreLoad']="False"
		
			process_sol101_template(bdf_full_name, SettingsD,OptionsD)
			print("Run Nastran " + SettingsD['NASTRAN_JOB_SETUP']['RunNastran'])
			try:
				RunNastran = SettingsD['NASTRAN_JOB_SETUP']['RunNastran']
			except:
				print("RunNastran Flag could not be found")
				RunNastran = "False"
			if RunNastran.upper() == "TRUE" or RunNastran.upper() == "YES" :
				print("*** Information *** Run Nastran ")
				run_nastran(bdf_full_name, SettingsD)
			else:
				print("*** Information *** Nastran execution is not choosen")
				
				
		#==========================RunNastran SOL106==========================================================		
			
		# export and optionally run sol106 job
		elif exportOptionFlag == "sol106":
			process_sol106_template(bdf_full_name, SettingsD)
			print("Run Nastran " + SettingsD['NASTRAN_JOB_SETUP']['RunNastran'])
			try:
				RunNastran = SettingsD['NASTRAN_JOB_SETUP']['RunNastran']
				print("Nastran executed")
				print("Nastran execution chosen\n")
			except:
				print("RunNastran Flag could not be found")
				RunNastran = "False"
			if RunNastran.upper() == "TRUE" or RunNastran.upper() == "YES" :
				run_nastran(bdf_full_name, SettingsD)
			else:
				print("Nastran execution is not choosen")
		
				

		#==========================RunNastran SOL400==========================================================		

		# export and optionally run sol400 job
		elif exportOptionFlag == "sol400":
			print("*** Information *** Processing  sol400  input file \n")
			#bolt_pre_load_flag=process_sol400_template(bdf_full_name, SettingsD, OptionsD)
			SettingsD=process_sol400_template(bdf_full_name, SettingsD, OptionsD)
			try:
				RunNastran = SettingsD['NASTRAN_JOB_SETUP']['RunNastran']
			except:
				print("RunNastran Flag could not be found")
				RunNastran = "False"
			if RunNastran.upper() == "TRUE" or RunNastran.upper() == "YES" :
				print("*** Information *** Run Nastran ")
				run_nastran(bdf_full_name, SettingsD)
			else:
				print("*** Information *** Nastran execution is not choosen")
				
			try:
				StartPatran = SettingsD['NASTRAN_JOB_SETUP']['SOL400StartPatranPost']
				
				if StartPatran.upper().replace("YES","TRUE") == "TRUE":
					print("*** Information *** Start Patran")
					PatranPath=SettingsD['System']['PatranPath']
				
					if not os.path.isfile(PatranPath):
						StartPatran="False"
						print("***Fail*** Patran executeable could not be found... specify PatranPath under System Tag in Utility User Settings File")
					
					#PatranTemplate= pathDir + "\\" + SettingsD['PatranPost']['Sol400BoltPostProcTemplate']
				
				
					PatranTemplate=resolve_pathname(SettingsD['PatranPost']['Sol400BoltPostProcTemplate'],SettingsD['System']['SettingsFile'])
					if not os.path.isfile(PatranTemplate):
						StartPatran="False"
						print("***Fail*** Patran Template file could not be found")
				else:
					print("*** Information *** Patran execution not chosen")
				
			except:
				traceback.print_exc()
				print("***Fail*** StartPatran Flag could not be found")
				StartPatran = "False"	
				
			if RunNastran.upper() == "TRUE" or RunNastran.upper() == "YES" :
				#run_nastran(bdf_full_name, SettingsD)
				# try read MPC Forces
				if SettingsD['NASTRAN_JOB_SETUP']['CreateBoltPreLoad'].upper().replace("YES","TRUE") == "TRUE":
					print("read MPC Forces from f06 file int0 csv file")
					read_MPCFORCES(bdf_full_name)
				else:
					print("***Information***No bolts in model or CreateBoltPreLoad is set to False")
				
			else:
				pass
				
			if StartPatran.upper() == "TRUE" or StartPatran.upper() == "YES" :
				print("I am in starting patran")
				print("Patran template: " + PatranTemplate)
				
				#hdf5_file=bdf_full_name.replace('.bdf','.h5')
				
				hdf5_file=RemoveBlanksFromFileName(bdf_full_name.replace('.bdf','.h5'))
				
				print(hdf5_file)
				print(PatranPath)
				
				# get number of loadsteps
				sts_h=open(bdf_full_name.replace(".bdf",".sts"),'r')
				lines=sts_h.readlines()
				sts_h.close()
				n=0
				GoStsFlag=False
				while n< len(lines):
					line=lines[n]
					if lines[n].find("Job ends with exit number ") > -1:
						# Job completed
						NoOfLoadSteps=int(lines[n-1][0:9])
						if lines[n].find("Job ends with exit number :       0"):
							#Job completed successfully
							GoStsFlag==True
					n+=1
							
				if GoStsFlag:
					print("Job completed successfully")
					print(("No of loadsteps detected: " +  str(NoOfLoadSteps) ))
				else:
					print("Job stopped before completion")
					print(("No of loadsteps detected: " +  str(NoOfLoadSteps) ))
				
				#try:
				if 1==1:
					groups_flag=SettingsD['System']['CreatePatranGroups']
					if groups_flag.upper()=="TRUE" or groups_flag.upper()=="YES":
						ses_file= os.path.dirname(bdf_full_name) + "\\" + "create_groups_" + os.path.basename(bdf_full_name)[:-4] + '.ses'
						if not os.path.isfile(ses_file):
							ses_file=""
					else:
						ses_file=""	
				#except:
				#	ses_file=""	
				
				print("Session file is " + ses_file)
	#
				start_patran_post(PatranPath,PatranTemplate,bdf_full_name,hdf5_file,NoOfLoadSteps,ses_file)
			else:
				pass

		#==========================Export To Mentat==========================================================

		# export to Mentat
		elif exportOptionFlag=="mentat":
		
			SettingsD['NASTRAN_JOB_SETUP']['CreateBoltPreLoad']="False"
		
			try:
				mentat_exe = SettingsD['System']['MentatPath']
				if not os.path.isfile(mentat_exe):
					AutoStartFlag = False

				AutoStartFlag = SettingsD['MENTAT_EXPORT']['StartMentatAutomatically']
				if AutoStartFlag.upper() == "TRUE" or AutoStartFlag.upper() == "YES":
					print("start mentat")
					print("Auto start Mentat\n")
					AutoStartFlag = True
				else:
					AutoStartFlag = False
			except:
				print("Could not start mentat automatically")
				AutoStartFlag = False
				
			# Check if  Apex Utils is generating Contact table or if built in Mantat translator is used
			# Main benefit of Apex Util is to preserve Part names in contact bodies
			generate_contact_table=False	
			try:
				generate_contact_table=SettingsD['MENTAT_EXPORT']['UseApexUtilsContactTable']
				if generate_contact_table.upper()=="TRUE":
					generate_contact_table=True
			except:
				pass
				
			# get rigid_parts	
			export_rigid_bodies=False
			try:
				export_rigid_bodies=SettingsD['MENTAT_EXPORT']['WriteRigidBodies']
				if export_rigid_bodies.upper()=="TRUE":
					export_rigid_bodies=True
			except:
				pass
			
			rigid_faces = []
			tmp_file = os.environ["TEMP"] + "/tmp_rigid_geometry.txt"
			if export_rigid_bodies == True and os.path.isfile(tmp_file):	
				# read info on rigid contact bodies from tmp file and append to proc file				
				tmp_file_h = open(tmp_file, 'r')
				lines = tmp_file_h.readlines()
				tmp_file_h.close()

				
				for lin in lines:
					rigid_faces.append(lin.split(';'))
					
			# oprate on the sol400 file		
			SettingsD=process_sol400_template(bdf_full_name, SettingsD, OptionsD)
			out_proc_file = write_proc_file(bdf_full_name, rigid_faces,SettingsD,generate_contact_table,OptionsD)
			#out_proc_file = write_proc_file(bdf_full_name.replace('\\', '/'), rigid_faces,SettingsD,generate_contact_table)
			
			# print " I am in starting Mentat"
			# print r"C:\MSC.Software\Marc\2017.0.0\mentat2017\bin\mentat.bat -pr " + out_proc_file
			# os.system(r"C:\MSC.Software\Marc\2017.0.0\mentat2017\bin\mentat.bat -pr " + out_proc_file)
			if AutoStartFlag==True:
				args = []
				#args.append(r"C:\MSC.Software\Marc\2017.0.0\mentat2017\bin\mentat.bat")
				
				args.append(mentat_exe)
				args.append("-pr")
				args.append('"' + out_proc_file + '"' )
				mentat_cwd = os.path.dirname(out_proc_file)
				stdout_h=open(mentat_cwd + "\\stdout.log",'w')
				stderr_h=open(mentat_cwd + "\\stderr.log",'w')
				
				
				print(args)
				# mentat_cwd=r"C:\tmp\Test_mentat5"
			
				#p = subprocess.Popen(args, stdout=stdout_h,stderr=stderr_h,stdin=subprocess.PIPE, cwd=mentat_cwd)

				p = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, cwd=mentat_cwd)					 
									 
				#file_h.close()
		
		#==========================Export To Sesam ==========================================================

		# export to Sesam
		elif exportOptionFlag=="sesam":
			try:
				sesam_exe = SettingsD['System']['SesamPath']
				if os.path.isfile(sesam_exe):
					print("sesam exe: " + sesam_exe)
				else:
					AutoStartFlag = False

				AutoStartFlag = SettingsD['SESAM_EXPORT']['StartSesamAutomatically']
				if AutoStartFlag.upper() == "TRUE" or AutoStartFlag.upper() == "YES":
					
					print("Auto start Sesam\n")
					AutoStartFlag = True
				else:
					AutoStartFlag = False
			except:
				print("Could not start Sesam automatically")
				AutoStartFlag = False

			try:
				template_file = pathDir + "\\" + SettingsD['SESAM_EXPORT']['ExportToSesamTemplate']
				if not os.path.isfile(template_file):
					AutoStartFlag = False
			except:
				print("Could not locate Sesam Template ses  file")
				AutoStartFlag = False


					
			print("AutoStartFlag " + str(AutoStartFlag))
			# print " I am in starting Sesam"
			
			if not os.path.isfile(groups_ses_file):
				groups_ses_file=""
				print("no patran groups created or creation failed")
			else:
				print("groups_ses_file: " + groups_ses_file)

			if AutoStartFlag==True:
				print("start sesam") 
				start_sesam_post(sesam_exe,template_file,bdf_full_name,SettingsD,groups_ses_file)
				
				

		else:
			print("No conversion detected")
			
	return


def RemoveBlanksFromFileName(in_file):
	out_file=os.path.dirname(in_file) + '\\' + os.path.basename(in_file).replace(' ','_')
	if out_file != in_file:
		os.rename(in_file, out_file)
	return out_file


if __name__ == "__main__":
	
	# This part is entered when using this file from Script Trigger

	# Use director specified from system variable, if not set, assume default location
	pathDir=os.environ.get('JAGUAR_UTILS_HOME')

	if pathDir:
		print("***Information***   JAGUAR_UTILS_HOME  env. variable is set to: " +  pathDir + "\n")
		if os.path.isdir(pathDir) and os.path.basename(pathDir)=='JaguarUtils':
			print("***Information*** Script folder located in path:" +  pathDir +  "\n")

		else:
			print("***Information***   JAGUAR_UTILS_HOME  env. variable is  not set, assume default install location is used\n")
			pathDir=os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"] + "\Documents\MSC_Apex Workspace\JaguarUtils"

	else:
		pathDir=os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"] + "\Documents\MSC_Apex Workspace\JaguarUtils"
		if not os.path.isdir(pathDir):
			print("***Error*** Unable to locate the folder : " + os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"] + "\Documents\MSC_Apex Workspace\JaguarUtils\n")
			
	if not pathDir in sys.path:
		sys.path.insert(0, pathDir)
		print('inserted ' + pathDir + ' into sys.path')	


	#from aux_functions_v105 import *
			
	# try:
		# from aux_functions_v105 import *
		# print("Python modules aux_functions_v105 located")
	# except:
		# print("#### Error ####")
		# print("Unable to locate custom modules aux_functions")

	try:
		import apex2aba_v9a
	except:
		print("#### Error ####")
		print("Unable to locate apex2aba_v9a modules")

	Go = True
	StartTime = datetime.datetime.now()



	if "HOMEPATH" in os.environ:

		# print os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"]
		# Use the real log file
		log_file = os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"] + "\Documents\MSC_Apex Workspace\MSC_Apex.log"
		print("Use Apex log file: " + log_file)

		try:
			settings_file = os.path.dirname(__file__) + '\\UtilityUserSettings.xml'
			# settings_file=os.path.dirname(log_file) + '\\JaguarUtils\\UtilityUserSettings.xml'
			print("Use settings file: " + settings_file)
		except:
			print("no settings file detected")
			settings_file=""

		# read settings file
		SettingsD = read_settings(settings_file)

		try:
			exec_mode = SettingsD['System']['ScriptMode']
			if exec_mode != "WaitAndStay":
				exec_mode = "WaitAndStop"
		except:
			exec_mode = "WaitAndStop"
			
			
		# add all info to a tmp_list
		tmp_handle1 = []

		# this part will look for a bdf to be written and take action depending on file prefix
		
		# CHECK PREFIX AND USE EXPORT OPTION FLAG
		# Change Stefan Tynelis 200527
		
		# determine what prefixes to look for to trigger an execution
		try:
			mentat_prefix=SettingsD['MENTAT_EXPORT']['WriteToMentatPrefix']
		except:
			mentat_prefix="mentat"	
			
		try:
			sesam_prefix=SettingsD['SESAM_EXPORT']['ExportToSesamPrefix']
		except:
			sesam_prefix="sesam"

		if len(sys.argv) > 1:
			print("I am in len(sys.argv)") 
			#file name passsed from event trigger script
			bdf_full_name=sys.argv[1]
			print(sys.argv[1])
			# rename file to eliminate blanks in file (not path) name
			#bdf_full_name=RemoveBlanksFromFileName(sys.argv[1])

			bdf_name=os.path.basename(bdf_full_name)
		
			if bdf_name[0:6].upper()  == "SOL101":
				exportOptionFlag="sol101"
			elif bdf_name[0:6].upper()  == "SOL106":
				exportOptionFlag="sol106"
			elif bdf_name[0:6].upper()  == "SOL400":
				exportOptionFlag="sol400"
			elif bdf_name[0:3].upper()  == "MNF":
				exportOptionFlag="mnf_"
			elif bdf_name[0:4].upper() == "INP_":
				exportOptionFlag="inp_"
			elif bdf_name[0:4].upper() == "VTU_":		
				exportOptionFlag="vtu_"
			elif bdf_name.find(	mentat_prefix ) == 0:
				exportOptionFlag="mentat"
			elif bdf_name.find(	sesam_prefix ) == 0:
				exportOptionFlag="sesam"	
			elif bdf_name[0:3].upper() == "SE" and bdf_name[2:3].isdigit():		
				exportOptionFlag="se"
			else:
				exportOptionFlag="None"
		
		
		
		


			ProcessSettingsFileOptions(bdf_full_name,SettingsD,exportOptionFlag)
		
		elif os.path.isfile(log_file) :
			#Standalone Macro method
			
			# create GoFile 
			UtilsGoFile = os.environ.get('TEMP') + '\\UtilsGoFlagFile.txt'
			UtilsGoFile_h = open(UtilsGoFile, 'w')
			UtilsGoFile_h.write('Started: ' + datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y"))
			UtilsGoFile_h.close()
		
			start_line = 0
			n = 0
			last_read_n = -1
			while Go == True:
				# Get Model file
				StartTime = datetime.datetime.now()
				model_file = get_model_file(log_file)

				bdf_full_name, Go, last_read_n = scan_log_file(log_file, StartTime, UtilsGoFile, last_read_n)
				
				# rename file to eliminate blanks in file (not path) name
				#out_file_name=RemoveBlanksFromFileName(bdf_full_name)
				#bdf_full_name=out_file_name
				ProcessSettingsFileOptions(bdf_full_name,SettingsD,exportOptionFlag)
				
				## these lines will manage conversion variuos items
				## Conversion will only happen if there is a settings file

				if os.path.isfile(settings_file) and Go==True:
					print("Settings file located: " + settings_file)

					ProcessSettingsFileOptions(bdf_full_name,SettingsD,exportOptionFlag)
						
					if 	exec_mode == "WaitAndStay":
						Go = True
						print("Script kept running is WaitAndStay")
					else:
						Go = False
						print("Script halted as  ScriptMode is 'WaitAndStop'")
						remove_tmp_file()

				elif Go!=True:
					print("Script stopped")
				else:
					print("No settings file detected, no conversions done")
					print("*** Information *** No settings file deteceted, no conversions done\n")
					Go = False

					n += 1

					tmp_handle1 = []


				UtilsGoFile = os.environ.get('TEMP') + '\\UtilsGoFlagFile.txt'
				if os.path.isfile(UtilsGoFile):
					# print "UtilsGoFlagFile exists"
					Go = True
				else:
					print("UtilsGoFlagFile removed...script will be stopped")
					Go = False

		else:
			#print "Use hardcoded path for debugging" 
			#bdf_full_name=r"C:\tmp\what_is_wrong\sol101_CAD_ASM.bdf"
			#ProcessSettingsFileOptions(bdf_full_name,SettingsD,exportOptionFlag)
			
			print("*** Error  *** Script could not find MSC_Apex.log")
			print("*** Error  *** Script could not find MSC_Apex.log" + '\n')


	else:
		print("HOMEPPATH is not in environment")
	print("done subprocess")

