#
# 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 sys
import os
import apex_sdk
import clr
import traceback
from time import sleep
import datetime


#.NET references
import System
import System.Windows.Controls as WPFControls
from System.Windows.Automation import AutomationProperties
from Microsoft.Win32 import OpenFileDialog
from Microsoft.Win32 import SaveFileDialog


global utils_path
file_path = os.path.dirname(os.path.realpath(__file__))
utils_path= os.path.dirname(os.path.realpath(file_path)) + "\\res"
xml_file= os.path.join(utils_path, 'UtilityUserSettings.xml')


#from  widgets import createCheckBox
#from  widgets import createEmptyRow

	
#if not utils_path in sys.path:
#	sys.path.insert(0, utils_path)
#	print('inserted ' + utils_path + ' into sys.path')	
	

def read_settings(settings_file, tmp_h=""):
	silent_flag = True
	#
	# settings_file=r'C:\Users\e7390\Documents\Predator\Topics\Scripting\Sample_files\UtilityUserSettings.xml'
	inf = open(settings_file, 'r')
	lines = inf.readlines()
	inf.close()
	keys = []
	SettingsD = {}
	n = 0
	while n < len(lines):
		if lines[n].find('<') > -1 and  lines[n].find('\\') < 0 and lines[n].find('/') < 0:
			# found start tag
			# print lines[n]
			tmp = lines[n].strip().replace('<', '').replace('>', '')
			# print tmp
			endtag = "<\\" + tmp + ">"
			endtag2 = "</" + tmp + ">"
			# print endtag
			n += 1
			SettingsD[tmp] = {}
			while lines[n].find(endtag) < 0 and lines[n].find(endtag2) <0 :
				#while lines[n].find(endtag) < 0 :
				if lines[n].find('=') > 1:
					newkey = lines[n].strip().split('=')[0]
					SettingsD[tmp][newkey] = lines[n].strip().split('=')[1]
					n += 1
				elif lines[n].find('#') == 0:
					continue
				else:
					# not a valid settnigs command
					#print "Not a valid settngs command: " + lines[n]
					n += 1
				#print(lines[n])
		n += 1

	# supress write out of all settings

	if silent_flag != True:
		if tmp_h != -1:
			print("====")
			print("Following setting groups detected:")

		for item in reversed(sorted(SettingsD.keys())):
			if tmp_h != -1:
				print("==== " + item + "   " + " ====")

			for key in list(SettingsD[item].keys()):
				if tmp_h != "" and tmp_h != -1:
					print("%-16s : %-12s" % (key, SettingsD[item][key].strip()))
				elif tmp_h == -1:
					continue
				else:
					print("%-16s : %-12s" % (key, SettingsD[item][key].strip()))
	#
	return SettingsD

def getUIContent():

	my_toolProperty = apex_sdk.ToolPropertyContainer()
	my_toolProperty.ToolPropertyContent = getCustomToolPropertyContent()

	my_toolProperty.TitleText = "Export customized bdf"
	
	file_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
	my_toolProperty.TitleImageUriString = file_path + "\\res\\bdfExportBeta.png"
	
	my_toolProperty.WorkFlowInstructions = """<HTML><BODY><P STYLE=\"font-size:10;\"><SPAN>Export bdf with options. Please note, at this point the only session unit system supported is mm-kg-s-N-K</SPAN></P>
	<P><SPAN> </SPAN></P>
	<P STYLE=\"font-size:10;\"><SPAN>Send questions to stefan.tynelius@hexagon.com - Elvis sightings to larry.pearce@hexagon.com</SPAN></P></BODY></HTML>"""

	#handle apply button (green) click event
	my_toolProperty.AppliedCommand = apex_sdk.ActionCommand(System.Action(HandleApplyButton))
	# handle exit button (red) click event
	my_toolProperty.ExitCommand = apex_sdk.ActionCommand(System.Action(HandleExitButton))
	
	#define pickFiterTools
	#my_toolProperty.ShowPickChoice = True
	#my_toolProperty.IsCustomTool = True
	#my_toolProperty.PickFilterList = setPickFilterTools()
	
	
	
	return my_toolProperty


def getCustomToolPropertyContent():
	global dictionary
	global utils_path
	
	# # get defaults from settings file
	file_path = os.path.dirname(os.path.realpath(__file__))
	#utils_path= os.path.dirname(os.path.realpath(file_path))
	settings_file= os.path.join(utils_path, 'UtilityUserSettings.xml')
	
	global SettingsD
	SettingsD=read_settings(settings_file)
	


	
	my_tabControl = WPFControls.TabControl()

	tabItem1 = WPFControls.TabItem()
	tabItem1.Header = "Export"
	tabItem2 = WPFControls.TabItem()
	tabItem2.Header = "LoadStepControl"
	tabItem3 = WPFControls.TabItem()
	tabItem3.Header = "ContactSettings"
	tabItem4 = WPFControls.TabItem()
	tabItem4.Header = "Misc. Settings"
	
	tabItem1.AddChild(Export())
	tabItem2.AddChild(LoadStepControl())
	tabItem3.AddChild(ContactSettings())
	tabItem4.AddChild(MiscSettings())
	
	my_tabControl.AddChild(tabItem1)
	my_tabControl.AddChild(tabItem2)
	my_tabControl.AddChild(tabItem3)
	my_tabControl.AddChild(tabItem4)
	
	#projectpath = os.path.dirname(os.path.realpath(__file__))
	#main_dir = os.path.join(projectpath, "main_sp.py")
	#apex_sdk.runScriptFunction(main_dir, "getMaterials", callback=getModelMaterials)
	#ret_dict = apex_sdk.getScriptFunctionReturnData()
	return my_tabControl

def MiscSettings():
	global dictionary
	#global miscsettings_grid
	# Create a Grid
	miscsettings_grid = WPFControls.Grid()
	global row,col
	
	nRows = 50
	nCols = 2
	createLayout(miscsettings_grid, nRows, nCols)
	row = col = 0

	########IAI Options############
	createEmptyRow(miscsettings_grid, row)
	row += 1	
	
	zeroLengthBushIndx=0
	try:
		if SettingsD['RBEX_CBUSH']['ZeroLength'].upper().replace("YES","TRUE")=="TRUE":
			zeroLengthBushIndx=1
	except:
		pass
	global zeroLengthBush_Toggle
	zeroLengthBush_Toggle  = createCheckBox(miscsettings_grid, "Create Zero Length Bushes", zeroLengthBushIndx, row, col)
	
	row += 1
	
	patranGroupsIndx=0
	try:
		if SettingsD['System']['CreatePatranGroups'].upper().replace("YES","TRUE")=="TRUE":
			patranGroupsIndx=1
	except:
		pass
	global patranGroups_Toggle
	patranGroups_Toggle  = createCheckBox(miscsettings_grid, "Create Patran Groups", patranGroupsIndx, row, col)
	row += 1	
	
	

	largeDispIndx=0
	try:
		if SettingsD['NASTRAN_JOB_SETUP']['LargeDisp'].upper().replace("YES","TRUE")=="TRUE":
			largeDispIndx=1
	except:
		pass
	global largeDisp_Toggle
	largeDisp_Toggle  = createCheckBox(miscsettings_grid, "Large Displacements", largeDispIndx, row, col)
	row += 1	

	

	
	followerForceIndx=0
	try:
		if SettingsD['NASTRAN_JOB_SETUP']['FollowerForce'].upper().replace("YES","TRUE")=="TRUE":
			followerForceIndx=1
	except:
		pass	
	global followerForce_Toggle
	followerForce_Toggle  = createCheckBox(miscsettings_grid, "Follower Force", followerForceIndx, row, col)
	row += 1
	

	RutmanIndx=0
	try:
		if SettingsD['System']['ProcessRutmanFasteners'].upper().replace("YES","TRUE")=="TRUE":
			RutmanIndx=1
	except:
		pass	
	global processRutman_Toggle
	processRutman_Toggle  = createCheckBox(miscsettings_grid, "Process Rutman Fasteners", RutmanIndx, row, col)
	row += 1

	
	createEmptyRow(miscsettings_grid, row)
	row += 1
	
	# global mergeZeroLengthRigids_Toggle
	# mergeZeroLengthRigidsIndx=0
	# try:
		# if SettingsD['System']['MergeTieRbars'].upper().replace("YES","TRUE")=="TRUE":
			# mergeZeroLengthRigidsIndx=1
	# except:
		# pass			
	# mergeZeroLengthRigids_Toggle  = createCheckBox(miscsettings_grid, "Merge Zero Length Tie RBARs", mergeZeroLengthRigidsIndx, row, col)
	# row += 1
	
	# createEmptyRow(miscsettings_grid, row)
	# row += 1
	
	global autoMsetComboBox, autoMsetTextBlock

	try:
		if SettingsD['NASTRAN_JOB_SETUP']['AUTOMSET'].upper()=="LUSOL":
			autoMsetIndx=2
		elif SettingsD['NASTRAN_JOB_SETUP']['AUTOMSET'].upper()=="YES":
			autoMsetIndx=0
		else:
			autoMsetIndx=1
	except:
		pass
		
	
	autoMsetComboBox, autoMsetTextBlock = createComboBox(miscsettings_grid, "Automset Option:", ["YES","NO","LUSOL"],autoMsetIndx, row, col)
	#autoMsetComboBox.SelectionChanged += autoMsetComboBoxCB
	autoMsetComboBox.SelectedIndex = autoMsetIndx
	row += 1
	
	try:
		AutoSpcEps=SettingsD['NASTRAN_JOB_SETUP']['AUTOSPCEPS']
	except:
		AutoSpcEps="1.0E-6"
	
	
	global AutoSpcEpsTextBox,  AutoSpcEpsTextBlock
	AutoSpcEpsTextBox, AutoSpcEpsTextBlock= createDataBox(miscsettings_grid, "AUTOSPC Stiff. Ratio (EPS)", AutoSpcEps, row, col)

	AutoSpcEpsTextBox.Visibility = System.Windows.Visibility.Visible
	AutoSpcEpsTextBlock.Visibility       = System.Windows.Visibility.Visible
	row += 1
	
	
	#Consolidate Variable Thickness
	if 1==1:
		try:
			convert_node_thick_flag = SettingsD['System']['NodeThicknessToPshells'].upper()
			thick_inc=SettingsD['System']['NodeThicknessToPshellsInc']
			thick_lo_limit=SettingsD['System']['NodeThicknessToPshellsLower_T']
			thick_up_limit=SettingsD['System']['NodeThicknessToPshellsUpper_T']
			
		except:
			convert_node_thick_flag = "FALSE"
			thick_lo_limit="0."
			thick_inc="0.1"
			thick_up_limit="100."
		
		if convert_node_thick_flag == "TRUE":
			SelectConsolidateOption = 0
		else:
			SelectConsolidateOption = 1
		
		global ConsolidateOptionComboBox, ConsolidateOptionTextBlock
		ConsolidateOptionTextBlock = createTextBlock(miscsettings_grid, "Consolidate Variable Thickness:", row, 0)
		ConsolidateOptionComboBox  = createComboBox2(miscsettings_grid, row, 1)
		updateComboBox2(ConsolidateOptionComboBox, ["Yes", "No"])
		ConsolidateOptionComboBox.SelectedIndex = SelectConsolidateOption
		row += 1
		
		ConsolidateOptionComboBox.SelectionChanged += ConsolidateOptionComboBoxCB
		
		ConsolidateOptionComboBox.Visibility = System.Windows.Visibility.Visible
		ConsolidateOptionTextBlock.Visibility = System.Windows.Visibility.Visible
		
		#NodeThicknessToPshells=True
		#NodeThicknessToPshellsLower_T=0.1
		#NodeThicknessToPshellsUpper_T=15.0
		#NodeThicknessToPshellsInc=0.1
		
		global nodeThicknessLoTextBox, nodeThicknessLoTextBlock
		nodeThicknessLoTextBox, nodeThicknessLoTextBlock= createDataBox(miscsettings_grid, "Lower Thickness ", thick_lo_limit, row, col)
		row += 1
		nodeThicknessLoTextBox.Visibility = System.Windows.Visibility.Collapsed
		nodeThicknessLoTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		
		global nodeThicknessUpTextBox, nodeThicknessUpTextBlock
		nodeThicknessUpTextBox, nodeThicknessUpTextBlock= createDataBox(miscsettings_grid, "Upper Thickness", thick_up_limit, row, col)
		row += 1
		nodeThicknessUpTextBox.Visibility = System.Windows.Visibility.Collapsed
		nodeThicknessUpTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		
		global ThicknessRangeIncTextBox, ThicknessRangeIncTextBlock
		ThicknessRangeIncTextBox, ThicknessRangeIncTextBlock  = createDataBox(miscsettings_grid, "Thickness Inc. ", thick_inc, row, col)
		row += 1
		ThicknessRangeIncTextBox.Visibility = System.Windows.Visibility.Collapsed
		ThicknessRangeIncTextBlock.Visibility       = System.Windows.Visibility.Collapsed
	
		

	return miscsettings_grid
	

#get tool property content
def Export():
	#global eventNameL
	#global scenarioNameL
	global utils_path
	#Create a Grid
	my_Grid = WPFControls.Grid()
	
	createLayout(my_Grid, 15, 2)

	row = 0
	col = 0
	
	# get defaults from settings file
	file_path = os.path.dirname(os.path.realpath(__file__))
	#utils_path= os.path.dirname(os.path.realpath(file_path))
	settings_file= os.path.join(utils_path, 'UtilityUserSettings.xml')
	SettingsD=read_settings(settings_file)
	
	

	
	# Analysis type Option
	global methodTypeComboBox, methodTypeTextBlock
	methodTypeTextBlock = createTextBlock(my_Grid, "Analysis option:", row, 0)
	methodTypeComboBox  = createComboBox2(my_Grid, row, 1)
	updateComboBox2(methodTypeComboBox, ["Nastran SOL101", "Nastran SOL400","Marc Mentat","Nastran SOL106","Abaqus .inp"])
	#updateComboBox2(methodTypeComboBox, ["Nastran SOL101", "Nastran SOL400","Marc Mentat","Abaqus .inp"])
	methodTypeComboBox.SelectedIndex = 1
	row += 1
	
	methodTypeComboBox.SelectionChanged += methodTypeComboBoxCB
	
	# ---- Scenarios----
	
	global scenariosComboBox, scenariosComboTextBlock
	scenariosComboTextBlock = createTextBlock(my_Grid, "Scenario:", row, 0)
	scenariosComboBox       = createComboBox2(my_Grid, row, 1)
	
	row += 1
	
	# Get both scenarios and events write to temp files in __file__ folder

	print("Creating stuff: ",datetime.datetime.now())
	file_path = os.path.dirname(os.path.realpath(__file__))
	script_path_parts= os.path.join(file_path, 'getScenariosAndEvents.py')
	apex_sdk.runScriptFunction(script_path_parts, "main", callback=getNewScenariosCB)
	
	scenariosComboTextBlock.Visibility = System.Windows.Visibility.Visible
	scenariosComboBox.Visibility       = System.Windows.Visibility.Visible
	
	scenariosComboBox.SelectionChanged += scenariosComboBoxCB


	# Session Units Systems
	global sessionUnitsComboBox,sessionUnitsTextBlock
	sessionUnitsTextBlock = createTextBlock(my_Grid, "Apex System Units:", row, 0)
	sessionUnitsComboBox  = createComboBox2(my_Grid, row, 1)
	updateComboBox2(sessionUnitsComboBox, ["mm-kg-s-N-K"])
	sessionUnitsComboBox.SelectedIndex = 0
	row += 1
	sessionUnitsTextBlock.Visibility = System.Windows.Visibility.Collapsed
	sessionUnitsComboBox.Visibility       = System.Windows.Visibility.Collapsed
	
	
	ExportUnitSystem="mm-t-s-N-K"
	supported_systems=["mm-t-s-N-K","m-kg-s-N-K","in-slinch-s-lbf-degF","mm-khyl-s-kgf-K"]
	upper_supported=[item.upper() for item in supported_systems]
	try:
		selected_indx=upper_supported.index(SettingsD['System']['ExportUnitSystem'].upper())
		ExportUnitSystem=supported_systems[selected_indx]
	except:
		selected_indx=0
		pass
	print("ExportUnitSystem:",ExportUnitSystem)
	
	
	
	# Export Units Systems
	global exportUnitsComboBox,exportUnitsTextBlock
	exportUnitsTextBlock = createTextBlock(my_Grid, "Analysis Export Units:", row, 0)
	exportUnitsComboBox  = createComboBox2(my_Grid, row, 1)
	updateComboBox2(exportUnitsComboBox, ["mm-t-s-N-K","m-kg-s-N-K","in-slinch-s-lbf-degF","mm-khyl-s-kgf-K"])
	exportUnitsComboBox.SelectedIndex = selected_indx
	row += 1



	# Solver Option
	global solverOptionComboBox, solverOptionTextBlock
	solverOptionTextBlock = createTextBlock(my_Grid, "Solver option:", row, 0)
	solverOptionComboBox  = createComboBox2(my_Grid, row, 1)
	updateComboBox2(solverOptionComboBox, ["Default (MSC LDL)", "CASI", "Pardiso"])
	solverOptionComboBox.SelectedIndex = 0
	row += 1
	
	solverOptionTextBlock.Visibility = System.Windows.Visibility.Visible
	solverOptionComboBox.Visibility       = System.Windows.Visibility.Visible
	
	

	
	
	# ---- Parts----
	
	global partsComboBox, partsComboTextBlock
	partsComboTextBlock = createTextBlock(my_Grid, "Parts:", row, 0)
	partsComboBox       = createComboBox2(my_Grid, row, 1)
	row += 1

	partsComboTextBlock.Visibility = System.Windows.Visibility.Collapsed
	partsComboBox.Visibility       = System.Windows.Visibility.Collapsed
	
	
	test_list=["TRUE","YES"]
	exportOption=0
	try:
		if SettingsD['NASTRAN_JOB_SETUP']['RunNastran'].upper() in test_list:
			exportOption=2
	except:
		pass
	
	global exportOptionComboBox, exportOptionTextBox
	exportOptionComboBox, exportOptionTextBox = createComboBox(my_Grid, "Export Options:", ["Run-Ready input deck", "Bulk data only", "Run Analysis"], 1, row, col)
	exportOptionComboBox.SelectedIndex = exportOption
	
	exportOptionComboBox.SelectionChanged += exportOptionComboBoxCB
	
	row += 1
	
	global postComboBox, postTextBlock
	postComboBox, postTextBlock = createComboBox(my_Grid, "Post Options: ", ["No Post", "Post using Patran"], 0, row, col)
	row += 1
	
	postTextBlock.Visibility = System.Windows.Visibility.Collapsed
	postComboBox.Visibility       = System.Windows.Visibility.Collapsed
	
	# File Save Text box
	global fileTextBox
	fileTextBox = createDataBox2(my_Grid, "", row, 1)
	
	
	saveBtn = WPFControls.Button()
	saveBtn.Content="Export to..."
	WPFControls.Grid.SetRow(saveBtn, row)
	WPFControls.Grid.SetColumn(saveBtn, col)
	saveBtn.Click+=HandleSaveBtn
	my_Grid.Children.Add(saveBtn)
	
	row += 1
	# UserOtion Text box
	global userOptionsTextBox
	userOptionsTextBox = createDataBox2(my_Grid, xml_file, row, 1)
	#row += 1
	
	userOptionBtn = WPFControls.Button()
	userOptionBtn.Content="User Options..."
	
	WPFControls.Grid.SetRow(userOptionBtn, row)
	WPFControls.Grid.SetColumn(userOptionBtn, col)
	userOptionBtn.Click+=HandleUserOptionBtn
	my_Grid.Children.Add(userOptionBtn)
	
	
	#Return the Grid
		
	return my_Grid


def ContactSettings():
	global dictionary
	#global settings_grid
	# Create a Grid
	settings_grid = WPFControls.Grid()
	global row,col
	
	nRows = 50
	nCols = 2
	createLayout(settings_grid, nRows, nCols)
	row = col = 0

	createEmptyRow(settings_grid, row)
	row += 1
	
	try:
		defaultContactType=SettingsD['NASTRAN_JOB_SETUP']['SOL400DefaultContactType'].upper()
		if defaultContactType != "GLUE":
			defaultContactType="TOUCH"
		else:
			defaultContactType="GLUE"
			
	except:
		defaultContactType="GLUE"
		
	try:
		default_TouchingContactError=float(SettingsD['NASTRAN_JOB_SETUP']['SOL400TouchingContactError'])
	except:
		default_TouchingContactError=0.1
		
	try:
		default_GlueContactError=float(SettingsD['NASTRAN_JOB_SETUP']['SOL400GlueContactError'])
	except:
		default_GlueContactError=0.5	
		
	try:
		default_Friction=float(SettingsD['NASTRAN_JOB_SETUP']['SOL400DefaultFriction'])
	except:
		default_Friction=0.15

	editContactTableatExport=0
	try:
		if SettingsD['NASTRAN_JOB_SETUP']['EditContactTable'].upper().replace("YES","TRUE")=="TRUE":
			editContactTableatExport=1
	except:
		pass
		
	analyticContactIndx=0
	try:
		if SettingsD['NASTRAN_JOB_SETUP']['AnalyticContact'].upper().replace("YES","TRUE")=="TRUE":
			analyticContactIndx=1
	except:
		pass
	
	row += 1
		
		
	
	AllowedCOntactMethods=["SEGTOSEG","NODESURF"]
	try:
		if SettingsD['NASTRAN_JOB_SETUP']['ContactMethod'].upper() in AllowedContactMethods:
			contactMethod=SettingsD['NASTRAN_JOB_SETUP']['ContactMethod']
		else:
			contactMethod="SEGTOSEG"
	except:
		contactMethod="SEGTOSEG"
		
		
	RetainGapOverlapsIndx=0
	try:
		if SettingsD['NASTRAN_JOB_SETUP']['RetainGapOverlaps'].upper().replace("YES","TRUE")=="TRUE":
			RetainGapOverlapsIndx=1
	except:
		pass
		
	InitialStressFreeIndx=0
	try:
		if SettingsD['NASTRAN_JOB_SETUP']['StressFreeInitialContact'].upper().replace("YES","TRUE")=="TRUE":
			InitialStressFreeIndx=1
	except:
		pass	
		
		
	
	global defaultContactTypeTextBox,  defaultContactTypeComboBox
	defaultContactTypeComboBox, defaultContactTypeTextBox = createComboBox(settings_grid, "Default Contact Type:", ["Glue", "Touch"], 1, row, col)
	if defaultContactType=="GLUE":
		defaultContactTypeComboBox.SelectedIndex = 0
	else:
		defaultContactTypeComboBox.SelectedIndex = 1
	defaultContactTypeComboBox.SelectionChanged += defaultContactTypeComboBoxCB
	row += 1
		
	createEmptyRow(settings_grid, row)
	row += 1
	
	
	global stressFreeInitial_Toggle		
	stressFreeInitial_Toggle  = createCheckBox(settings_grid, "Stress Free Inititial Contact", InitialStressFreeIndx, row, col)
	row += 1
	stressFreeInitial_Toggle.Visibility = System.Windows.Visibility.Collapsed


	
	global retainGapsOverlaps_Toggle		
	retainGapsOverlaps_Toggle  = createCheckBox(settings_grid, "Retain Gap Overlaps", RetainGapOverlapsIndx, row, col)
	row += 1
	retainGapsOverlaps_Toggle.Visibility = System.Windows.Visibility.Visible

	global contactMethodComboBox, contactMethodTextBox
	contactMethodComboBox, contactMethodTextBox = createComboBox(settings_grid, "Contact Method:", ["Segment 2 Segment", "Node 2 Segment"], 1, row, col)
	if contactMethod=="SEGTOSEG":
		contactMethodComboBox.SelectedIndex = 0
	else:
		contactMethodComboBox.SelectedIndex = 1	
	#contactMethodComboBox.SelectionChanged += contactMethodComboBoxCB
	
	row += 1
	
	
	global analyticContact_Toggle
	analyticContact_Toggle  = createCheckBox(settings_grid, "Analytic Contact", analyticContactIndx, row, col)			
	row += 1
	analyticContact_Toggle.Visibility = System.Windows.Visibility.Visible
	
	createEmptyRow(settings_grid, row)
	row += 1
	
	global defaultTouchingTolTextBox,  defaultTouchingTolTextBlock
	defaultTouchingTolTextBox, defaultTouchingTolTextBlock= createDataBox(settings_grid, "Default Tocuhing Contact Tol.", str(default_TouchingContactError), row, col)

	defaultTouchingTolTextBox.Visibility = System.Windows.Visibility.Visible
	defaultTouchingTolTextBlock.Visibility       = System.Windows.Visibility.Visible
	row += 1
	
	global defaultGlueTolTextBox,  defaultGlueTolTextBlock
	defaultGlueTolTextBox, defaultGlueTolTextBlock= createDataBox(settings_grid, "Default Glue Contact Tol.", str(default_GlueContactError), row, col)

	defaultGlueTolTextBox.Visibility = System.Windows.Visibility.Visible
	defaultGlueTolTextBlock.Visibility       = System.Windows.Visibility.Visible
	row += 1
	
	global defaultFrictTextBox,  defaultFrictTextBlock
	defaultFrictTextBox, defaultFrictTextBlock= createDataBox(settings_grid, "Default Friction", str(default_Friction), row, col)

	defaultFrictTextBox.Visibility = System.Windows.Visibility.Visible
	defaultFrictTextBlock.Visibility       = System.Windows.Visibility.Visible
	row += 1	
	
	createEmptyRow(settings_grid, row)
	row += 1
	
	global editContactTable_Toggle			
	editContactTable_Toggle  = createCheckBox(settings_grid, "Edit Contact Table at Export", editContactTableatExport, row, col)
	editContactTable_Toggle.Visibility       = System.Windows.Visibility.Collapsed
	
	
		
	return settings_grid

def LoadStepControl():
	#global eventNameL
	#global scenarioNameL
	
	# tmp_file =r"C:\Temp\aaa.txt"
	# file_h=open(tmp_file,'w')
	# file_h.write("Items\n")
	# for item in eventNameL:
		# file_h.write(item)
	# file_h.close()
	
	try:
		sol400_epsp=SettingsD['NASTRAN_JOB_SETUP']['SOL400EPSP']
	except:
		sol400_epsp="0.05"
	
	try:
		sol400_epsu=SettingsD['NASTRAN_JOB_SETUP']['SOL400EPSU']
	except:
		sol400_epsu="0.1"
		
	try:
		sol101_epsp=SettingsD['NASTRAN_JOB_SETUP']['SOL400EPSP']
	except:
		sol101_epsp="0.05"
	
	try:
		sol101_epsu=SettingsD['NASTRAN_JOB_SETUP']['SOL400EPSU']
	except:
		sol101_epsu="0.1"	


	try:
		sol106_epsp=SettingsD['NASTRAN_JOB_SETUP']['SOL400EPSP']
	except:
		sol106_epsp="0.05"
	
	try:
		sol106_epsu=SettingsD['NASTRAN_JOB_SETUP']['SOL400EPSU']
	except:
		sol106_epsu="0.1"
		

	try:
		sol400_noOfInc=SettingsD['NASTRAN_JOB_SETUP']['SOL400NoOfIncrements']
	except:
		sol400_noOfInc="10"
		
	try:
		sol101_noOfInc=SettingsD['NASTRAN_JOB_SETUP']['SOL101NoOfIncrements']
	except:
		sol101_noOfInc="10"

	try:
		sol106_noOfInc=SettingsD['NASTRAN_JOB_SETUP']['SOL106NoOfIncrements']
	except:
		sol106_noOfInc="10"		
		

	try:
		preload_noOfInc=SettingsD['BoltPreLoad']['PreloadNoOfInc']
	except:
		preload_noOfInc="2"
		
	try:
		lockstep_noOfInc=SettingsD['BoltPreLoad']['LockNoOfInc']
	except:
		lockstep_noOfInc="1"	


	#global dictionary
	#global loadstepControl_grid
	# Create a Grid
	loadstepControl_grid = WPFControls.Grid()
	global row,col
	
	nRows = 70
	nCols = 2
	createLayout(loadstepControl_grid, nRows, nCols)
	row = col = 0
	
	global eventComboBox,eventComboTextBlock
	
	eventComboTextBlock = createTextBlock(loadstepControl_grid, "Event:", row, 0)
	eventComboBox       = createComboBox2(loadstepControl_grid, row, 1)
	row += 1
	
	eventComboBox.Visibility       = System.Windows.Visibility.Visible
	eventComboTextBlock.Visibility       = System.Windows.Visibility.Visible
	

	########Load Step Control############
	
	

	createEmptyRow(loadstepControl_grid, row)
	row += 1
	
	# Need to hard code events max 8
	# no of steps
		
	row += 1
	
	# ================ Pre Load Event =============================
	global loadStep_PreloadTextBox,  loadStep_PreloadTextBlock
	loadStep_PreloadTextBox, loadStep_PreloadTextBlock= createDataBox(loadstepControl_grid, "Preload Step: No. of Increments", preload_noOfInc, row, col)
	loadStep_PreloadTextBox.Visibility = System.Windows.Visibility.Collapsed
	loadStep_PreloadTextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400epsp_PreloadTextBox,  sol400epsp_PreloadTextBlock
	sol400epsp_PreloadTextBox, sol400epsp_PreloadTextBlock= createDataBox(loadstepControl_grid, "Residual Load Error Tol. (EPSP)", sol400_epsp, row, col)
	sol400epsp_PreloadTextBox.Visibility = System.Windows.Visibility.Collapsed
	sol400epsp_PreloadTextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400epsu_PreloadTextBox,  sol400epsu_PreloadTextBlock
	sol400epsu_PreloadTextBox, sol400epsu_PreloadTextBlock= createDataBox(loadstepControl_grid, "Residual Displacement Error Tol. (EPSU)", sol400_epsu, row, col)
	sol400epsu_PreloadTextBox.Visibility = System.Windows.Visibility.Collapsed
	sol400epsu_PreloadTextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	# ================ LockStep =============================
	global loadStep_LockTextBox,  loadStep_LockTextBlock
	loadStep_LockTextBox, loadStep_LockTextBlock= createDataBox(loadstepControl_grid, "Lock Step: No. of Increments", lockstep_noOfInc, row, col)
	loadStep_LockTextBox.Visibility = System.Windows.Visibility.Collapsed
	loadStep_LockTextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400epsp_LockTextBox,  sol400epsp_LockTextBlock
	sol400epsp_LockTextBox, sol400epsp_LockTextBlock= createDataBox(loadstepControl_grid, "Residual Load Error Tol. (EPSP)", sol400_epsp, row, col)
	sol400epsp_LockTextBox.Visibility = System.Windows.Visibility.Collapsed
	sol400epsp_LockTextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400epsu_LockTextBox,  sol400epsu_LockTextBlock
	sol400epsu_LockTextBox, sol400epsu_LockTextBlock= createDataBox(loadstepControl_grid, "Residual Displacement Error Tol. (EPSU)", sol400_epsu, row, col)
	sol400epsu_LockTextBox.Visibility = System.Windows.Visibility.Collapsed
	sol400epsu_LockTextBlock.Visibility = System.Windows.Visibility.Collapsed
	
	
	
	
	# ================ Step 1 =============================
	global loadStep_1TextBox,  loadStep_1TextBlock
	
	choices = methodTypeComboBox.SelectedValue.ToString().split(":")
	choice = choices[len(choices)-1].lstrip().rstrip()
	if choice=="Nastran SOL101":
		sol400_noOfInc=sol101_noOfInc
		sol400_epsp=sol101_epsp
		sol400_epsu=sol101_epsu
		
	elif choice=="Nastran SOL106":
		sol400_noOfInc=sol106_noOfInc
		sol400_epsp=sol106_epsp
		sol400_epsu=sol106_epsu
	
	
	loadStep_1TextBox, loadStep_1TextBlock= createDataBox(loadstepControl_grid, "Step1: No. of Increments", sol400_noOfInc, row, col)
	loadStep_1TextBox.Visibility = System.Windows.Visibility.Visible
	loadStep_1TextBlock.Visibility       = System.Windows.Visibility.Visible
	row += 1
	
	global sol400epsp_1TextBox,  sol400epsp_1TextBlock
	sol400epsp_1TextBox, sol400epsp_1TextBlock= createDataBox(loadstepControl_grid, "Residual Load Error Tol. (EPSP)", sol400_epsp, row, col)
	sol400epsp_1TextBox.Visibility = System.Windows.Visibility.Visible
	sol400epsp_1TextBlock.Visibility       = System.Windows.Visibility.Visible
	row += 1
	
	global sol400epsu_1TextBox,  sol400epsu_1TextBlock
	sol400epsu_1TextBox, sol400epsu_1TextBlock= createDataBox(loadstepControl_grid, "Residual Displacement Error Tol. (EPSU)", sol400_epsu, row, col)
	sol400epsu_1TextBox.Visibility = System.Windows.Visibility.Visible
	sol400epsu_1TextBlock.Visibility       = System.Windows.Visibility.Visible
	row += 1
	
	global sol400_convcrit_1ComboBox, sol400_convcrit_1TextBox
	sol400_convcrit_1ComboBox, sol400_convcrit_1TextBox = createComboBox(loadstepControl_grid, "Convergence Criteria:", ["PVA", "UP", "P", "U", "UPV"], 1, row, col)
	sol400_convcrit_1ComboBox.SelectedIndex = 0
	sol400_convcrit_1ComboBox.Visibility = System.Windows.Visibility.Visible
	sol400_convcrit_1TextBox.Visibility       = System.Windows.Visibility.Visible
	row += 1
	
	# ================ Step 2 =============================
	global loadStep_2TextBox,  loadStep_2TextBlock
	loadStep_2TextBox, loadStep_2TextBlock= createDataBox(loadstepControl_grid, "Step2: No. of Increments", sol400_noOfInc, row, col)
	loadStep_2TextBox.Visibility = System.Windows.Visibility.Collapsed
	loadStep_2TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400epsp_2TextBox,  sol400epsp_2TextBlock
	sol400epsp_2TextBox, sol400epsp_2TextBlock= createDataBox(loadstepControl_grid, "Residual Load Error Tol. (EPSP)", sol400_epsp, row, col)
	sol400epsp_2TextBox.Visibility = System.Windows.Visibility.Collapsed
	sol400epsp_2TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400epsu_2TextBox,  sol400epsu_2TextBlock
	sol400epsu_2TextBox, sol400epsu_2TextBlock= createDataBox(loadstepControl_grid, "Residual Displacement Error Tol. (EPSU)", sol400_epsu, row, col)
	sol400epsu_2TextBox.Visibility = System.Windows.Visibility.Collapsed
	sol400epsu_2TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400_convcrit_2ComboBox, sol400_convcrit_2TextBox
	sol400_convcrit_2ComboBox, sol400_convcrit_2TextBox = createComboBox(loadstepControl_grid, "Convergence Criteria:", ["PVA", "UP", "P", "U"], 1, row, col)
	sol400_convcrit_2ComboBox.SelectedIndex = 0
	sol400_convcrit_2ComboBox.Visibility = System.Windows.Visibility.Collapsed
	sol400_convcrit_2TextBox.Visibility       = System.Windows.Visibility.Collapsed
	row += 1

	# ================ Step 3 =============================
	global loadStep_3TextBox,  loadStep_3TextBlock
	loadStep_3TextBox, loadStep_3TextBlock= createDataBox(loadstepControl_grid, "Step3: No. of Increments", sol400_noOfInc, row, col)
	loadStep_3TextBox.Visibility = System.Windows.Visibility.Collapsed
	loadStep_3TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400epsp_3TextBox,  sol400epsp_3TextBlock
	sol400epsp_3TextBox, sol400epsp_3TextBlock= createDataBox(loadstepControl_grid, "Residual Load Error Tol. (EPSP)", sol400_epsp, row, col)
	sol400epsp_3TextBox.Visibility = System.Windows.Visibility.Collapsed
	sol400epsp_3TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400epsu_3TextBox,  sol400epsu_3TextBlock
	sol400epsu_3TextBox, sol400epsu_3TextBlock= createDataBox(loadstepControl_grid, "Residual Displacement Error Tol. (EPSU)", sol400_epsu, row, col)
	sol400epsu_3TextBox.Visibility = System.Windows.Visibility.Collapsed
	sol400epsu_3TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400_convcrit_3ComboBox, sol400_convcrit_3TextBox
	sol400_convcrit_3ComboBox, sol400_convcrit_3TextBox = createComboBox(loadstepControl_grid, "Convergence Criteria:", ["PVA", "UP", "P", "U"], 1, row, col)
	sol400_convcrit_3ComboBox.SelectedIndex = 0
	sol400_convcrit_3ComboBox.Visibility = System.Windows.Visibility.Collapsed
	sol400_convcrit_3TextBox.Visibility       = System.Windows.Visibility.Collapsed	
	
	row += 1
	
	# ================ Step 4 =============================
	global loadStep_4TextBox,  loadStep_4TextBlock
	loadStep_4TextBox, loadStep_4TextBlock= createDataBox(loadstepControl_grid, "Step4: No. of Increments", sol400_noOfInc, row, col)
	loadStep_4TextBox.Visibility = System.Windows.Visibility.Collapsed
	loadStep_4TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400epsp_4TextBox,  sol400epsp_4TextBlock
	sol400epsp_4TextBox, sol400epsp_4TextBlock= createDataBox(loadstepControl_grid, "Residual Load Error Tol. (EPSP)", sol400_epsp, row, col)
	sol400epsp_4TextBox.Visibility = System.Windows.Visibility.Collapsed
	sol400epsp_4TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400epsu_4TextBox,  sol400epsu_4TextBlock
	sol400epsu_4TextBox, sol400epsu_4TextBlock= createDataBox(loadstepControl_grid, "Residual Displacement Error Tol. (EPSU)", sol400_epsu, row, col)
	sol400epsu_4TextBox.Visibility = System.Windows.Visibility.Collapsed
	sol400epsu_4TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1	
	
	global sol400_convcrit_4ComboBox, sol400_convcrit_4TextBox
	sol400_convcrit_4ComboBox, sol400_convcrit_4TextBox = createComboBox(loadstepControl_grid, "Convergence Criteria:", ["PVA", "UP", "P", "U"], 1, row, col)
	sol400_convcrit_4ComboBox.Visibility = System.Windows.Visibility.Collapsed
	sol400_convcrit_4TextBox.Visibility  = System.Windows.Visibility.Collapsed
	sol400_convcrit_4ComboBox.SelectedIndex = 0
	row += 1
	# ================ Step 5 =============================
	global loadStep_5TextBox,  loadStep_5TextBlock
	loadStep_5TextBox, loadStep_5TextBlock= createDataBox(loadstepControl_grid, "Step5: No. of Increments", sol400_noOfInc, row, col)
	loadStep_5TextBox.Visibility = System.Windows.Visibility.Collapsed
	loadStep_5TextBlock.Visibility  = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400epsp_5TextBox,  sol400epsp_5TextBlock
	sol400epsp_5TextBox, sol400epsp_5TextBlock= createDataBox(loadstepControl_grid, "Residual Load Error Tol. (EPSP)", sol400_epsp, row, col)
	sol400epsp_5TextBox.Visibility = System.Windows.Visibility.Collapsed
	sol400epsp_5TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400epsu_5TextBox,  sol400epsu_5TextBlock
	sol400epsu_5TextBox, sol400epsu_5TextBlock= createDataBox(loadstepControl_grid, "Residual Displacement Error Tol. (EPSU)", sol400_epsu, row, col)
	sol400epsu_5TextBox.Visibility = System.Windows.Visibility.Collapsed
	sol400epsu_5TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1	


	global sol400_convcrit_5ComboBox, sol400_convcrit_5TextBox
	sol400_convcrit_5ComboBox, sol400_convcrit_5TextBox = createComboBox(loadstepControl_grid, "Convergence Criteria:", ["PVA", "UP", "P", "U"], 1, row, col)
	sol400_convcrit_5ComboBox.SelectedIndex = 0
	sol400_convcrit_5ComboBox.Visibility = System.Windows.Visibility.Collapsed
	sol400_convcrit_5TextBox.Visibility       = System.Windows.Visibility.Collapsed
	
	
	row += 1
	# ================ Step 6 =============================
	global loadStep_6TextBox,  loadStep_6TextBlock
	loadStep_6TextBox, loadStep_6TextBlock= createDataBox(loadstepControl_grid, "Step6: No. of Increments", sol400_noOfInc, row, col)
	loadStep_6TextBox.Visibility = System.Windows.Visibility.Collapsed
	loadStep_6TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400epsp_6TextBox,  sol400epsp_6TextBlock
	sol400epsp_6TextBox, sol400epsp_6TextBlock= createDataBox(loadstepControl_grid, "Residual Load Error Tol. (EPSP)", sol400_epsp, row, col)
	sol400epsp_6TextBox.Visibility = System.Windows.Visibility.Collapsed
	sol400epsp_6TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400epsu_6TextBox,  sol400epsu_6TextBlock
	sol400epsu_6TextBox, sol400epsu_6TextBlock= createDataBox(loadstepControl_grid, "Residual Displacement Error Tol. (EPSU)", sol400_epsu, row, col)
	sol400epsu_6TextBox.Visibility = System.Windows.Visibility.Collapsed
	sol400epsu_6TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400_convcrit_6ComboBox, sol400_convcrit_6TextBox
	sol400_convcrit_6ComboBox, sol400_convcrit_6TextBox = createComboBox(loadstepControl_grid, "Convergence Criteria:", ["PVA", "UP", "P", "U"], 1, row, col)
	sol400_convcrit_6ComboBox.SelectedIndex = 0
	sol400_convcrit_6ComboBox.Visibility = System.Windows.Visibility.Collapsed
	sol400_convcrit_6TextBox.Visibility       = System.Windows.Visibility.Collapsed
	
	row += 1
	# ================ Step 7 =============================
	global loadStep_7TextBox,  loadStep_7TextBlock
	loadStep_7TextBox, loadStep_7TextBlock= createDataBox(loadstepControl_grid, "Step7: No. of Increments", sol400_noOfInc, row, col)
	loadStep_7TextBox.Visibility = System.Windows.Visibility.Collapsed
	loadStep_7TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400epsp_7TextBox,  sol400epsp_7TextBlock
	sol400epsp_7TextBox, sol400epsp_7TextBlock= createDataBox(loadstepControl_grid, "Residual Load Error Tol. (EPSP)", sol400_epsp, row, col)
	sol400epsp_7TextBox.Visibility = System.Windows.Visibility.Collapsed
	sol400epsp_7TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400epsu_7TextBox,  sol400epsu_7TextBlock
	sol400epsu_7TextBox, sol400epsu_7TextBlock= createDataBox(loadstepControl_grid, "Residual Displacement Error Tol. (EPSU)", sol400_epsu, row, col)
	sol400epsu_7TextBox.Visibility = System.Windows.Visibility.Collapsed
	sol400epsu_7TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1

	global sol400_convcrit_7ComboBox, sol400_convcrit_7TextBox
	sol400_convcrit_7ComboBox, sol400_convcrit_7TextBox = createComboBox(loadstepControl_grid, "Convergence Criteria:", ["PVA", "UP", "P", "U"], 1, row, col)
	sol400_convcrit_7ComboBox.SelectedIndex = 0
	sol400_convcrit_7ComboBox.Visibility = System.Windows.Visibility.Collapsed
	sol400_convcrit_7ComboBox.Visibility       = System.Windows.Visibility.Collapsed
	
	row += 1

	# ================ Step 8 =============================
	global loadStep_8TextBox,  loadStep_8TextBlock
	loadStep_8TextBox, loadStep_8TextBlock= createDataBox(loadstepControl_grid, "Step8: No. of Increments", sol400_noOfInc, row, col)
	loadStep_8TextBox.Visibility = System.Windows.Visibility.Collapsed
	loadStep_8TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400epsp_8TextBox,  sol400epsp_8TextBlock
	sol400epsp_8TextBox, sol400epsp_8TextBlock= createDataBox(loadstepControl_grid, "Residual Load Error Tol. (EPSP)", sol400_epsp, row, col)
	sol400epsp_8TextBox.Visibility = System.Windows.Visibility.Collapsed
	sol400epsp_8TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400epsu_8TextBox,  sol400epsu_8TextBlock
	sol400epsu_8TextBox, sol400epsu_8TextBlock= createDataBox(loadstepControl_grid, "Residual Displacement Error Tol. (EPSU)", sol400_epsu, row, col)
	sol400epsu_8TextBox.Visibility = System.Windows.Visibility.Collapsed
	sol400epsu_8TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1

	global sol400_convcrit_8ComboBox, sol400_convcrit_8TextBox
	sol400_convcrit_8ComboBox, sol400_convcrit_8TextBox = createComboBox(loadstepControl_grid, "Convergence Criteria:", ["PVA", "UP", "P", "U"], 1, row, col)
	sol400_convcrit_8ComboBox.SelectedIndex = 0
	sol400_convcrit_8ComboBox.Visibility = System.Windows.Visibility.Collapsed
	sol400_convcrit_8TextBox.Visibility       = System.Windows.Visibility.Collapsed
	
	row += 1

	# ================ Step 9 =============================
	global loadStep_9TextBox,  loadStep_9TextBlock
	loadStep_9TextBox, loadStep_9TextBlock= createDataBox(loadstepControl_grid, "Step9: No. of Increments", sol400_noOfInc, row, col)
	loadStep_9TextBox.Visibility = System.Windows.Visibility.Collapsed
	loadStep_9TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400epsp_9TextBox,  sol400epsp_9TextBlock
	sol400epsp_9TextBox, sol400epsp_9TextBlock= createDataBox(loadstepControl_grid, "Residual Load Error Tol. (EPSP)", sol400_epsp, row, col)
	sol400epsp_9TextBox.Visibility = System.Windows.Visibility.Collapsed
	sol400epsp_9TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400epsu_9TextBox,  sol400epsu_9TextBlock
	sol400epsu_9TextBox, sol400epsu_9TextBlock= createDataBox(loadstepControl_grid, "Residual Displacement Error Tol. (EPSU)", sol400_epsu, row, col)
	sol400epsu_9TextBox.Visibility = System.Windows.Visibility.Collapsed
	sol400epsu_9TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400_convcrit_9ComboBox, sol400_convcrit_9TextBox
	sol400_convcrit_9ComboBox, sol400_convcrit_9TextBox = createComboBox(loadstepControl_grid, "Cunvergence Criteria:", ["PVA", "UP", "P", "U"], 1, row, col)
	sol400_convcrit_9ComboBox.SelectedIndex = 0
	sol400_convcrit_9ComboBox.Visibility = System.Windows.Visibility.Collapsed
	sol400_convcrit_9TextBox.Visibility       = System.Windows.Visibility.Collapsed
	
	
	row += 1

	# ================ Step 10 =============================
	global loadStep_10TextBox,  loadStep_10TextBlock
	loadStep_10TextBox, loadStep_10TextBlock= createDataBox(loadstepControl_grid, "Step10: No. of Increments", sol400_noOfInc, row, col)
	loadStep_10TextBox.Visibility = System.Windows.Visibility.Collapsed
	loadStep_10TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400epsp_10TextBox,  sol400epsp_10TextBlock
	sol400epsp_10TextBox, sol400epsp_10TextBlock= createDataBox(loadstepControl_grid, "Residual Load Error Tol. (EPSP)", sol400_epsp, row, col)
	sol400epsp_10TextBox.Visibility = System.Windows.Visibility.Collapsed
	sol400epsp_10TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400epsu_10TextBox,  sol400epsu_10TextBlock
	sol400epsu_10TextBox, sol400epsu_10TextBlock= createDataBox(loadstepControl_grid, "Residual Displacement Error Tol. (EPSU)", sol400_epsu, row, col)
	sol400epsu_10TextBox.Visibility = System.Windows.Visibility.Collapsed
	sol400epsu_10TextBlock.Visibility       = System.Windows.Visibility.Collapsed
	row += 1
	
	global sol400_convcrit_10ComboBox, sol400_convcrit_10TextBox
	sol400_convcrit_10ComboBox, sol400_convcrit_10TextBox = createComboBox(loadstepControl_grid, "Convergence Criteria:", ["PVA", "UP", "P", "U"], 1, row, col)
	sol400_convcrit_10ComboBox.SelectedIndex = 0
	sol400_convcrit_10ComboBox.Visibility = System.Windows.Visibility.Collapsed
	sol400_convcrit_10TextBox.Visibility       = System.Windows.Visibility.Collapsed
	
	row += 1

	eventComboBox.SelectionChanged += eventComboBoxCB

	return loadstepControl_grid

@apex_sdk.errorhandler
def scenariosComboBoxCB(sender, event):
	global scenariosComboBox
	global eventComboBox
	#global eventNameL
	#global scenarioNameL

	choices = scenariosComboBox.SelectedValue.ToString().split(":")
	_scenario_name = choices[len(choices)-1].lstrip().rstrip()
	
		
	event_file=os.path.dirname(__file__) + '/events.txt'
	try:
		#if 1==1:
		event_file_h=open(event_file,'r')
		event_lines=event_file_h.readlines()
		eventL=[item.strip() for item in event_lines]
		event_file_h.close()
	except:
		print("Failed reading Events: ",datetime.datetime.now())
		traceback.print_exc()
		eventL=[]
	
	scenario_file=os.path.dirname(__file__) + '/scenarios.txt'
	try:
		scenario_file_h=open(scenario_file,'r')
		scenario_lines=scenario_file_h.readlines()
		scenarios=[item.strip() for item in scenario_lines]
		scenario_file_h.close()
	except:
		print("Failed reading Scenes: ",datetime.datetime.now())
		traceback.print_exc()
		scenarios=[]

	
	print("Scenarios")
	print(scenarios)
	print("Events")
	print(eventL)
		
	my_eventNameL=[]
	GoFlag=False
	n=0
	while n < len(scenarios):
		print("n",n)
		if scenarios[n] == _scenario_name:
			my_eventNameL=eventL[n].split('$')
			print("Found matching scenario",_scenario_name )
			GoFlag=True
			break
		n+=1

	if GoFlag:
		print("GoFlag")
		try:
			print("my_eventNameL",my_eventNameL)
			refreshComboBox(eventComboBox, my_eventNameL)
		except:
			print("Failed to updated eventComboBox")
			print("my_eventNameL",my_eventNameL)
			print("==========================")
			traceback.print_exc()
			print("==========================")
	else:
		print("GoFlag=False")


def defaultContactTypeComboBoxCB(sender, event):
	global stressFreeInitial_Toggle
	global retainGapsOverlaps_Toggle
	global defaultContactTypeComboBox

	choices = defaultContactTypeComboBox.SelectedValue.ToString().split(":")
	choice = choices[len(choices)-1].lstrip().rstrip()
	
	if choice == "Glue":
		stressFreeInitial_Toggle.Visibility = System.Windows.Visibility.Collapsed
		retainGapsOverlaps_Toggle.Visibility = System.Windows.Visibility.Visible
	else:
		stressFreeInitial_Toggle.Visibility = System.Windows.Visibility.Visible
		retainGapsOverlaps_Toggle.Visibility = System.Windows.Visibility.Collapsed

def contactMethodComboBoxCB(sender, event):
	global analyticContact_Toggle
	choices = contactMethodComboBox.SelectedValue.ToString().split(":")
	choice = choices[len(choices)-1].lstrip().rstrip()
	
	if choice == "Segment 2 Segment":
		analyticContact_Toggle.Visibility = System.Windows.Visibility.Collapsed
	else:
		analyticContact_Toggle.Visibility = System.Windows.Visibility.Visible



def methodTypeComboBoxCB(sender, event):
	global methodTypeComboBox, methodTypeTextBlock
	global scenariosComboBox, scenariosComboTextBlock
	global exportOptionComboBox, exportOptionTextBox
	#global startIdTextBox, startIdTextBlock
	#global stepIdTextBox, stepIdTextBlock
	global fileTextBox
	global partsComboBox, partsComboTextBlock
	global postComboBox, postTextBlock
	global solverOptionComboBox, solverOptionTextBlock
	#global saveBtn
	
	
	choices = methodTypeComboBox.SelectedValue.ToString().split(":")
	choice = choices[len(choices)-1].lstrip().rstrip()
	
	#["Nastran SOL101", "Nastran SOL400","Marc Mentat","Nastran SOL106","Abaqus .inp"]
	
	
	if choice == "Nastran SOL101":
		methodTypeComboBox.Visibility       = System.Windows.Visibility.Visible
		scenariosComboBox.Visibility       = System.Windows.Visibility.Visible
		scenariosComboTextBlock.Visibility       = System.Windows.Visibility.Visible 
		partsComboBox.Visibility       = System.Windows.Visibility.Collapsed
		partsComboTextBlock.Visibility       = System.Windows.Visibility.Collapsed 
		exportOptionTextBox.Visibility       = System.Windows.Visibility.Visible
		exportOptionComboBox.Visibility       = System.Windows.Visibility.Visible
		postTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		postComboBox.Visibility       = System.Windows.Visibility.Collapsed
		#startIdTextBox.Visibility       = System.Windows.Visibility.Collapsed
		#startIdTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		#stepIdTextBox.Visibility       = System.Windows.Visibility.Collapsed
		#stepIdTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		fileTextBox.Visibility       = System.Windows.Visibility.Visible
		#saveBtn.Visibility           = System.Windows.Visibility.Visible
		
		solverOptionTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		solverOptionComboBox.Visibility       = System.Windows.Visibility.Collapsed
		
	elif choice == "Nastran SOL400":
		methodTypeComboBox.Visibility       = System.Windows.Visibility.Visible
		scenariosComboBox.Visibility       = System.Windows.Visibility.Visible
		scenariosComboTextBlock.Visibility       = System.Windows.Visibility.Visible
		partsComboBox.Visibility       = System.Windows.Visibility.Collapsed
		partsComboTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		exportOptionTextBox.Visibility       = System.Windows.Visibility.Visible
		exportOptionComboBox.Visibility       = System.Windows.Visibility.Visible
		postTextBlock.Visibility       = System.Windows.Visibility.Visible
		postComboBox.Visibility       = System.Windows.Visibility.Visible
		#startIdTextBox.Visibility       = System.Windows.Visibility.Collapsed
		#startIdTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		#stepIdTextBox.Visibility       = System.Windows.Visibility.Collapsed
		#stepIdTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		fileTextBox.Visibility       = System.Windows.Visibility.Visible	
		#saveBtn.Visibility           = System.Windows.Visibility.Visible
		solverOptionTextBlock.Visibility       = System.Windows.Visibility.Visible
		solverOptionComboBox.Visibility       = System.Windows.Visibility.Visible
	
	elif choice == "Marc Mentat":
		methodTypeComboBox.Visibility       = System.Windows.Visibility.Visible
		scenariosComboBox.Visibility       = System.Windows.Visibility.Visible
		scenariosComboTextBlock.Visibility       = System.Windows.Visibility.Visible
		partsComboBox.Visibility       = System.Windows.Visibility.Collapsed
		partsComboTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		exportOptionTextBox.Visibility       = System.Windows.Visibility.Collapsed
		exportOptionComboBox.Visibility       = System.Windows.Visibility.Collapsed
		postTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		postComboBox.Visibility       = System.Windows.Visibility.Collapsed
		#startIdTextBox.Visibility       = System.Windows.Visibility.Collapsed
		#startIdTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		#stepIdTextBox.Visibility       = System.Windows.Visibility.Collapsed
		#stepIdTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		fileTextBox.Visibility       = System.Windows.Visibility.Visible
		#saveBtn.Visibility           = System.Windows.Visibility.Visible
		solverOptionTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		solverOptionComboBox.Visibility       = System.Windows.Visibility.Collapsed
		"Upstream Data Recovery"
		
	elif choice == "Nastran SOL106":
		methodTypeComboBox.Visibility       = System.Windows.Visibility.Visible
		scenariosComboBox.Visibility       = System.Windows.Visibility.Collapsed
		scenariosComboTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		partsComboBox.Visibility       = System.Windows.Visibility.Collapsed
		partsComboTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		exportOptionTextBox.Visibility       = System.Windows.Visibility.Visible
		exportOptionComboBox.Visibility       = System.Windows.Visibility.Visible
		postTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		postComboBox.Visibility       = System.Windows.Visibility.Collapsed
		#startIdTextBox.Visibility       = System.Windows.Visibility.Collapsed
		#startIdTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		#stepIdTextBox.Visibility       = System.Windows.Visibility.Collapsed
		#stepIdTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		fileTextBox.Visibility       = System.Windows.Visibility.Visible	
		#saveBtn.Visibility           = System.Windows.Visibility.Visible
		solverOptionTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		solverOptionComboBox.Visibility       = System.Windows.Visibility.Collapsed
		
		
	elif choice == "Abaqus .inp":
		methodTypeComboBox.Visibility       = System.Windows.Visibility.Visible
		scenariosComboBox.Visibility       = System.Windows.Visibility.Visible
		scenariosComboTextBlock.Visibility       = System.Windows.Visibility.Visible
		partsComboBox.Visibility       = System.Windows.Visibility.Collapsed
		partsComboTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		exportOptionTextBox.Visibility       = System.Windows.Visibility.Collapsed
		exportOptionComboBox.Visibility       = System.Windows.Visibility.Collapsed
		postTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		postComboBox.Visibility       = System.Windows.Visibility.Collapsed
		#startIdTextBox.Visibility       = System.Windows.Visibility.Collapsed
		#startIdTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		#stepIdTextBox.Visibility       = System.Windows.Visibility.Collapsed
		#stepIdTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		fileTextBox.Visibility       = System.Windows.Visibility.Visible	
		#saveBtn.Visibility           = System.Windows.Visibility.Collapsed
		solverOptionTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		solverOptionComboBox.Visibility       = System.Windows.Visibility.Collapsed


def exportOptionComboBoxCB(sender, event):
	# I need to learn and understand sender and event
	#global methodTypeComboBox, methodTypeTextBlock
	#global scenariosComboBox, scenariosComboTextBlock
	global exportOptionComboBox, exportOptionTextBox
	global postComboBox, postTextBlock
	#global solverOptionComboBox, solverOptionTextBlock

	
	["Run-Ready input deck", "Bulk data only", "Run Analysis"]
	choices = exportOptionComboBox.SelectedValue.ToString().split(":")
	choice = choices[len(choices)-1].lstrip().rstrip()
	
	
	
	if choice == "Run-Ready input deck":
		postTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		postComboBox.Visibility       = System.Windows.Visibility.Collapsed

		
	elif choice == "Bulk data only":
		postTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		postComboBox.Visibility       = System.Windows.Visibility.Collapsed

	
	elif choice == "Run Analysis":
		postTextBlock.Visibility       = System.Windows.Visibility.Visible
		postComboBox.Visibility       = System.Windows.Visibility.Visible





def ConsolidateOptionComboBoxCB(sender, event):
	# I need to learn and understand sender and event
	global ConsolidateOptionComboBox, ConsolidateOptionTextBlock
	global scenariosComboBox, scenariosComboTextBlock
	global exportOptionComboBox, exportOptionTextBox
	global nodeThicknessLoTextBox, nodeThicknessLoTextBlock
	global nodeThicknessUpTextBox, nodeThicknessUpTextBlock
	global ThicknessRangeIncTextBox, ThicknessRangeIncTextBlock
	global fileTextBox
	global partsComboBox, partsComboTextBlock
	global postComboBox, postTextBlock
	#global saveBtn


	choices = ConsolidateOptionComboBox.SelectedValue.ToString().split(":")
	choice = choices[len(choices)-1].lstrip().rstrip()

	#["Nastran SOL101", "Nastran SOL400","Marc Mentat","Nastran SOL106","Abaqus .inp"]


	if choice == "Yes":

		#scenariosComboBox.Visibility       = System.Windows.Visibility.Visible
		#scenariosComboTextBlock.Visibility       = System.Windows.Visibility.Visible 
		#partsComboBox.Visibility       = System.Windows.Visibility.Collapsed
		#partsComboTextBlock.Visibility       = System.Windows.Visibility.Collapsed 
		#exportOptionTextBox.Visibility       = System.Windows.Visibility.Visible
		#exportOptionComboBox.Visibility       = System.Windows.Visibility.Visible
		#postTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		#postComboBox.Visibility       = System.Windows.Visibility.Collapsed
		nodeThicknessLoTextBox.Visibility       = System.Windows.Visibility.Visible
		nodeThicknessLoTextBlock.Visibility       = System.Windows.Visibility.Visible
		nodeThicknessUpTextBox.Visibility       = System.Windows.Visibility.Visible
		nodeThicknessUpTextBlock.Visibility       = System.Windows.Visibility.Visible
		ThicknessRangeIncTextBox.Visibility       = System.Windows.Visibility.Visible
		ThicknessRangeIncTextBlock.Visibility       = System.Windows.Visibility.Visible
		#fileTextBox.Visibility       = System.Windows.Visibility.Visible
		#saveBtn.Visibility           = System.Windows.Visibility.Visible
		
	elif choice == "No":

		#scenariosComboBox.Visibility       = System.Windows.Visibility.Visible
		#scenariosComboTextBlock.Visibility       = System.Windows.Visibility.Visible
		#partsComboBox.Visibility       = System.Windows.Visibility.Collapsed
		#partsComboTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		#exportOptionTextBox.Visibility       = System.Windows.Visibility.Collapsed
		#exportOptionComboBox.Visibility       = System.Windows.Visibility.Collapsed
		#postTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		#postComboBox.Visibility       = System.Windows.Visibility.Collapsed
		nodeThicknessLoTextBox.Visibility       = System.Windows.Visibility.Collapsed
		nodeThicknessLoTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		nodeThicknessUpTextBox.Visibility       = System.Windows.Visibility.Collapsed
		nodeThicknessUpTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		ThicknessRangeIncTextBox.Visibility       = System.Windows.Visibility.Collapsed
		ThicknessRangeIncTextBlock.Visibility       = System.Windows.Visibility.Collapsed
		#fileTextBox.Visibility       = System.Windows.Visibility.Visible	
		#saveBtn.Visibility           = System.Windows.Visibility.Visible
	pass


@apex_sdk.errorhandler
def eventComboBoxCB(sender, event):
	global scenariosComboBox
	global eventComboBox
	#global eventNameL
	#global scenarioNameL
	
	# Preload Bolt1$Preload Bolt2$Pos Torque Mech$Relax 1$Neg Torque Mech$Relax 2$Thermal Temp @ 140.$Thermal Temp @ -140.$Thermal Temp @ 20.Event 1$Event 200000000000000000000
	
	# need to know which scenario is selecetd
	choices = scenariosComboBox.SelectedValue.ToString().split(":")
	_scenario_name = choices[len(choices)-1].lstrip().rstrip()
	# # # get list of scenarios and events
	#ret_dict = apex_sdk.getScriptFunctionReturnData()
	#scenarios = ret_dict["ScenarioList"]
	
	event_file=os.path.dirname(__file__) + '/events.txt'
	event_file_h=open(event_file,'r')
	event_lines=event_file_h.readlines()
	eventL=[item.strip() for item in event_lines]
	event_file_h.close()
	
	scenario_file=os.path.dirname(__file__) + '/scenarios.txt'
	scenario_file_h=open(scenario_file,'r')
	scenario_lines=scenario_file_h.readlines()
	scenarios=[item.strip() for item in scenario_lines]
	scenario_file_h.close()

	#scenarios=scenarioNameL
	#eventL = ret_dict["EventL"]
	#eventL=eventNameL
		
	my_eventNameL=[]	
	n=0
	while n < len(scenarios):

		if scenarios[n] == _scenario_name:
			my_eventNameL=eventL[n].split('$')
		n+=1


	try:
		choices = eventComboBox.SelectedValue.ToString().split(":")
		choice = choices[len(choices)-1].lstrip().rstrip()
	except:
		choice=""
	
	# padd upp with zeros to avoid key errors below
	my_eventNameL.extend(["0","0","0","0","0","0""0","0","0","0"])
		

	
	# There can be no ":" in the Event Name


	if choice != my_eventNameL[0]:
		loadStep_1TextBox.Visibility = System.Windows.Visibility.Collapsed
		loadStep_1TextBlock.Visibility       = System.Windows.Visibility.Collapsed		
		sol400epsp_1TextBox.Visibility = System.Windows.Visibility.Collapsed
		sol400epsp_1TextBlock.Visibility       = System.Windows.Visibility.Collapsed
		sol400epsu_1TextBox.Visibility = System.Windows.Visibility.Collapsed
		sol400epsu_1TextBlock.Visibility       = System.Windows.Visibility.Collapsed
		sol400_convcrit_1TextBox.Visibility       = System.Windows.Visibility.Collapsed
		sol400_convcrit_1ComboBox.Visibility       = System.Windows.Visibility.Collapsed
		
	else:
		loadStep_1TextBox.Visibility = System.Windows.Visibility.Visible
		loadStep_1TextBlock.Visibility       = System.Windows.Visibility.Visible		
		sol400epsp_1TextBox.Visibility = System.Windows.Visibility.Visible
		sol400epsp_1TextBlock.Visibility       = System.Windows.Visibility.Visible
		sol400epsu_1TextBox.Visibility = System.Windows.Visibility.Visible
		sol400epsu_1TextBlock.Visibility       = System.Windows.Visibility.Visible
		sol400_convcrit_1TextBox.Visibility       = System.Windows.Visibility.Visible
		sol400_convcrit_1ComboBox.Visibility       = System.Windows.Visibility.Visible		
		
	
	if choice != my_eventNameL[1]:
		loadStep_2TextBox.Visibility = System.Windows.Visibility.Collapsed
		loadStep_2TextBlock.Visibility       = System.Windows.Visibility.Collapsed		
		sol400epsp_2TextBox.Visibility = System.Windows.Visibility.Collapsed
		sol400epsp_2TextBlock.Visibility       = System.Windows.Visibility.Collapsed
		sol400epsu_2TextBox.Visibility = System.Windows.Visibility.Collapsed
		sol400epsu_2TextBlock.Visibility       = System.Windows.Visibility.Collapsed
		sol400_convcrit_2TextBox.Visibility       = System.Windows.Visibility.Collapsed
		sol400_convcrit_2ComboBox.Visibility       = System.Windows.Visibility.Collapsed
		
	else:
		loadStep_2TextBox.Visibility = System.Windows.Visibility.Visible
		loadStep_2TextBlock.Visibility       = System.Windows.Visibility.Visible		
		sol400epsp_2TextBox.Visibility = System.Windows.Visibility.Visible
		sol400epsp_2TextBlock.Visibility       = System.Windows.Visibility.Visible
		sol400epsu_2TextBox.Visibility = System.Windows.Visibility.Visible
		sol400epsu_2TextBlock.Visibility       = System.Windows.Visibility.Visible
		sol400_convcrit_2TextBox.Visibility       = System.Windows.Visibility.Visible
		sol400_convcrit_2ComboBox.Visibility       = System.Windows.Visibility.Visible
		
	
	if choice != my_eventNameL[2]:
		loadStep_3TextBox.Visibility = System.Windows.Visibility.Collapsed
		loadStep_3TextBlock.Visibility       = System.Windows.Visibility.Collapsed		
		sol400epsp_3TextBox.Visibility = System.Windows.Visibility.Collapsed
		sol400epsp_3TextBlock.Visibility       = System.Windows.Visibility.Collapsed
		sol400epsu_3TextBox.Visibility = System.Windows.Visibility.Collapsed
		sol400epsu_3TextBlock.Visibility       = System.Windows.Visibility.Collapsed
		sol400_convcrit_3TextBox.Visibility       = System.Windows.Visibility.Collapsed
		sol400_convcrit_3ComboBox.Visibility       = System.Windows.Visibility.Collapsed
		
	else:
		loadStep_3TextBox.Visibility = System.Windows.Visibility.Visible
		loadStep_3TextBlock.Visibility       = System.Windows.Visibility.Visible		
		sol400epsp_3TextBox.Visibility = System.Windows.Visibility.Visible
		sol400epsp_3TextBlock.Visibility       = System.Windows.Visibility.Visible
		sol400epsu_3TextBox.Visibility = System.Windows.Visibility.Visible
		sol400epsu_3TextBlock.Visibility       = System.Windows.Visibility.Visible
		sol400_convcrit_3TextBox.Visibility       = System.Windows.Visibility.Visible
		sol400_convcrit_3ComboBox.Visibility       = System.Windows.Visibility.Visible

	if choice != my_eventNameL[3]:
		loadStep_4TextBox.Visibility = System.Windows.Visibility.Collapsed
		loadStep_4TextBlock.Visibility       = System.Windows.Visibility.Collapsed		
		sol400epsp_4TextBox.Visibility = System.Windows.Visibility.Collapsed
		sol400epsp_4TextBlock.Visibility       = System.Windows.Visibility.Collapsed
		sol400epsu_4TextBox.Visibility = System.Windows.Visibility.Collapsed
		sol400epsu_4TextBlock.Visibility       = System.Windows.Visibility.Collapsed
		sol400_convcrit_4TextBox.Visibility       = System.Windows.Visibility.Collapsed
		sol400_convcrit_4ComboBox.Visibility       = System.Windows.Visibility.Collapsed
	else:
		loadStep_4TextBox.Visibility = System.Windows.Visibility.Visible
		loadStep_4TextBlock.Visibility       = System.Windows.Visibility.Visible		
		sol400epsp_4TextBox.Visibility = System.Windows.Visibility.Visible
		sol400epsp_4TextBlock.Visibility       = System.Windows.Visibility.Visible
		sol400epsu_4TextBox.Visibility = System.Windows.Visibility.Visible
		sol400epsu_4TextBlock.Visibility       = System.Windows.Visibility.Visible
		sol400_convcrit_4TextBox.Visibility       = System.Windows.Visibility.Visible
		sol400_convcrit_4ComboBox.Visibility       = System.Windows.Visibility.Visible
		
	if choice != my_eventNameL[4]:
		loadStep_5TextBox.Visibility = System.Windows.Visibility.Collapsed
		loadStep_5TextBlock.Visibility       = System.Windows.Visibility.Collapsed		
		sol400epsp_5TextBox.Visibility = System.Windows.Visibility.Collapsed
		sol400epsp_5TextBlock.Visibility       = System.Windows.Visibility.Collapsed
		sol400epsu_5TextBox.Visibility = System.Windows.Visibility.Collapsed
		sol400epsu_5TextBlock.Visibility       = System.Windows.Visibility.Collapsed
		sol400_convcrit_5TextBox.Visibility       = System.Windows.Visibility.Collapsed
		sol400_convcrit_5ComboBox.Visibility       = System.Windows.Visibility.Collapsed
		
	else:	
		loadStep_5TextBox.Visibility = System.Windows.Visibility.Visible
		loadStep_5TextBlock.Visibility       = System.Windows.Visibility.Visible		
		sol400epsp_5TextBox.Visibility = System.Windows.Visibility.Visible
		sol400epsp_5TextBlock.Visibility       = System.Windows.Visibility.Visible
		sol400epsu_5TextBox.Visibility = System.Windows.Visibility.Visible
		sol400epsu_5TextBlock.Visibility       = System.Windows.Visibility.Visible
		sol400_convcrit_5TextBox.Visibility       = System.Windows.Visibility.Visible
		sol400_convcrit_5ComboBox.Visibility       = System.Windows.Visibility.Visible
		
	if choice != my_eventNameL[5]:
		loadStep_6TextBox.Visibility = System.Windows.Visibility.Collapsed
		loadStep_6TextBlock.Visibility       = System.Windows.Visibility.Collapsed		
		sol400epsp_6TextBox.Visibility = System.Windows.Visibility.Collapsed
		sol400epsp_6TextBlock.Visibility       = System.Windows.Visibility.Collapsed
		sol400epsu_6TextBox.Visibility = System.Windows.Visibility.Collapsed
		sol400epsu_6TextBlock.Visibility       = System.Windows.Visibility.Collapsed
		sol400_convcrit_6TextBox.Visibility       = System.Windows.Visibility.Collapsed
		sol400_convcrit_6ComboBox.Visibility       = System.Windows.Visibility.Collapsed
		
	else:
		loadStep_6TextBox.Visibility = System.Windows.Visibility.Visible
		loadStep_6TextBlock.Visibility       = System.Windows.Visibility.Visible		
		sol400epsp_6TextBox.Visibility = System.Windows.Visibility.Visible
		sol400epsp_6TextBlock.Visibility       = System.Windows.Visibility.Visible
		sol400epsu_6TextBox.Visibility = System.Windows.Visibility.Visible
		sol400epsu_6TextBlock.Visibility       = System.Windows.Visibility.Visible
		sol400_convcrit_6TextBox.Visibility       = System.Windows.Visibility.Visible
		sol400_convcrit_6ComboBox.Visibility       = System.Windows.Visibility.Visible


	if choice != my_eventNameL[6]:
		loadStep_7TextBox.Visibility = System.Windows.Visibility.Collapsed
		loadStep_7TextBlock.Visibility       = System.Windows.Visibility.Collapsed		
		sol400epsp_7TextBox.Visibility = System.Windows.Visibility.Collapsed
		sol400epsp_7TextBlock.Visibility       = System.Windows.Visibility.Collapsed
		sol400epsu_7TextBox.Visibility = System.Windows.Visibility.Collapsed
		sol400epsu_7TextBlock.Visibility       = System.Windows.Visibility.Collapsed
		sol400_convcrit_7TextBox.Visibility       = System.Windows.Visibility.Collapsed
		sol400_convcrit_7ComboBox.Visibility       = System.Windows.Visibility.Collapsed
		
	else:
		loadStep_7TextBox.Visibility = System.Windows.Visibility.Visible
		loadStep_7TextBlock.Visibility       = System.Windows.Visibility.Visible		
		sol400epsp_7TextBox.Visibility = System.Windows.Visibility.Visible
		sol400epsp_7TextBlock.Visibility       = System.Windows.Visibility.Visible
		sol400epsu_7TextBox.Visibility = System.Windows.Visibility.Visible
		sol400epsu_7TextBlock.Visibility       = System.Windows.Visibility.Visible
		sol400_convcrit_7TextBox.Visibility       = System.Windows.Visibility.Visible
		sol400_convcrit_7ComboBox.Visibility       = System.Windows.Visibility.Visible
		
		
	if choice != my_eventNameL[7]:
		loadStep_8TextBox.Visibility = System.Windows.Visibility.Collapsed
		loadStep_8TextBlock.Visibility       = System.Windows.Visibility.Collapsed		
		sol400epsp_8TextBox.Visibility = System.Windows.Visibility.Collapsed
		sol400epsp_8TextBlock.Visibility       = System.Windows.Visibility.Collapsed
		sol400epsu_8TextBox.Visibility = System.Windows.Visibility.Collapsed
		sol400epsu_8TextBlock.Visibility       = System.Windows.Visibility.Collapsed
		sol400_convcrit_8TextBox.Visibility       = System.Windows.Visibility.Collapsed
		sol400_convcrit_8ComboBox.Visibility       = System.Windows.Visibility.Collapsed
		
		
	else:
		loadStep_8TextBox.Visibility = System.Windows.Visibility.Visible
		loadStep_8TextBlock.Visibility       = System.Windows.Visibility.Visible		
		sol400epsp_8TextBox.Visibility = System.Windows.Visibility.Visible
		sol400epsp_8TextBlock.Visibility       = System.Windows.Visibility.Visible
		sol400epsu_8TextBox.Visibility = System.Windows.Visibility.Visible
		sol400epsu_8TextBlock.Visibility       = System.Windows.Visibility.Visible
		sol400_convcrit_8TextBox.Visibility       = System.Windows.Visibility.Visible
		sol400_convcrit_8ComboBox.Visibility       = System.Windows.Visibility.Visible
		
		
	if choice != my_eventNameL[8]:
		loadStep_9TextBox.Visibility = System.Windows.Visibility.Collapsed
		loadStep_9TextBlock.Visibility       = System.Windows.Visibility.Collapsed		
		sol400epsp_9TextBox.Visibility = System.Windows.Visibility.Collapsed
		sol400epsp_9TextBlock.Visibility       = System.Windows.Visibility.Collapsed
		sol400epsu_9TextBox.Visibility = System.Windows.Visibility.Collapsed
		sol400epsu_9TextBlock.Visibility       = System.Windows.Visibility.Collapsed
		sol400_convcrit_9TextBox.Visibility       = System.Windows.Visibility.Collapsed
		sol400_convcrit_9ComboBox.Visibility       = System.Windows.Visibility.Collapsed
		
		
	else:
		loadStep_9TextBox.Visibility = System.Windows.Visibility.Visible
		loadStep_9TextBlock.Visibility       = System.Windows.Visibility.Visible		
		sol400epsp_9TextBox.Visibility = System.Windows.Visibility.Visible
		sol400epsp_9TextBlock.Visibility       = System.Windows.Visibility.Visible
		sol400epsu_9TextBox.Visibility = System.Windows.Visibility.Visible
		sol400epsu_9TextBlock.Visibility       = System.Windows.Visibility.Visible
		sol400_convcrit_9TextBox.Visibility       = System.Windows.Visibility.Visible
		sol400_convcrit_9ComboBox.Visibility       = System.Windows.Visibility.Visible

	if choice != my_eventNameL[9]:
		loadStep_10TextBox.Visibility = System.Windows.Visibility.Collapsed
		loadStep_10TextBlock.Visibility       = System.Windows.Visibility.Collapsed		
		sol400epsp_10TextBox.Visibility = System.Windows.Visibility.Collapsed
		sol400epsp_10TextBlock.Visibility       = System.Windows.Visibility.Collapsed
		sol400epsu_10TextBox.Visibility = System.Windows.Visibility.Collapsed
		sol400epsu_10TextBlock.Visibility       = System.Windows.Visibility.Collapsed
		sol400_convcrit_10TextBox.Visibility       = System.Windows.Visibility.Collapsed
		sol400_convcrit_10ComboBox.Visibility       = System.Windows.Visibility.Collapsed
		
		
	else:
		loadStep_10TextBox.Visibility = System.Windows.Visibility.Visible
		loadStep_10TextBlock.Visibility       = System.Windows.Visibility.Visible		
		sol400epsp_10TextBox.Visibility = System.Windows.Visibility.Visible
		sol400epsp_10TextBlock.Visibility       = System.Windows.Visibility.Visible
		sol400epsu_10TextBox.Visibility = System.Windows.Visibility.Visible
		sol400epsu_10TextBlock.Visibility       = System.Windows.Visibility.Visible
		sol400_convcrit_10TextBox.Visibility       = System.Windows.Visibility.Visible
		sol400_convcrit_10ComboBox.Visibility       = System.Windows.Visibility.Visible
		
		
def createLayout(parent, numRows, numCols):
	for k in range(numRows):
		parent.RowDefinitions.Add(WPFControls.RowDefinition())
	for k in range(numCols):
		parent.ColumnDefinitions.Add(WPFControls.ColumnDefinition())

def createComboBox(parent, title, labels, selected, row, col):
	textBlock = WPFControls.TextBlock()
	textBlock.Text = title
	WPFControls.Grid.SetRow(textBlock, row)
	WPFControls.Grid.SetColumn(textBlock, col)

	parent.Children.Add(textBlock)
	
	comboBox = WPFControls.ComboBox()
	for label in labels:
		item = WPFControls.ComboBoxItem()
		item.Content=label
		comboBox.Items.Add(item)
	
	WPFControls.Grid.SetRow(comboBox, row)
	WPFControls.Grid.SetColumn(comboBox, col+1)
	
	if selected > len(labels): selected = 0
	comboBox.SelectedIndex=str(selected)
	
	parent.Children.Add(comboBox)
	
	return comboBox, textBlock

def createComboBox2(parent, row, col):
	comboBox = WPFControls.ComboBox()
	
	comboBox.Margin = System.Windows.Thickness(5.)
	
	WPFControls.Grid.SetRow(comboBox, row)
	WPFControls.Grid.SetColumn(comboBox, col)
	
	parent.Children.Add(comboBox)
	
	return comboBox

@apex_sdk.errorhandler
def refreshComboBox(comboBox, comboItems):
	print("comboItems",comboItems)
	comboBox.Items.Clear()
	print("there are ",len(comboItems)," items")
	n=0
	for item in comboBox.Items:
		n+=1
	print("===No of items at start ",n,"===")
	
	# this fails with 'NoneType' object has no attribute 'ToString'
	if 1==0:
		if n!=0:
			comboBox.DataSource = None
			#comboBox.Items.Clear()
	try:
		print("I am in here")
		for comboItem in comboItems:
			item = WPFControls.ComboBoxItem()
			item.Content=comboItem
			comboBox.Items.Add(item)
	except:
		print("Error could not add ",comboItem) 
	
	# script will hang with following lines
	if 1==0:
		if n!=0:
		
			goFlag=True
			while goFlag:
				m=-1
				for item in comboBox.Items:
					m+=1
					item_text=item.ToString()
					print(item_text)
					_tmp_text = item_text.split(":")[1].lstrip().rstrip()

					if _tmp_text not in comboItems:
						break
					# if we are not breaking out of loop, means no entries to delete
					goFlag=False
					
				#remove item
				if goFlag:
					try:
						#comboBox.Items.Remove(item)
						comboBox.Items.RemoveAt(m)
					except:
						print("could not remove:",_tmp_text)
				
				
			print("===No of items ",m,"===")
	
	try:
		comboBox.SelectedIndex=0
	except:
		print("Warning-Could not set ComboBox SelectIndex")

def updateComboBox2(comboBox, comboItems):
	comboBox.Items.Clear()
	print("there are ",len(comboItems))
	n=0
	for comboItem in comboItems:
		item = WPFControls.ComboBoxItem()
		item.Content=comboItem
		comboBox.Items.Add(item)
		n+=1
	try:
		comboBox.SelectedIndex=len(comboItems) -1
	except:
		pass
		print("could not set combobox index")


def createTextBlock(parent, text, row, col):
	textBlock = WPFControls.TextBlock()
	textBlock.Text = text
	
	textBlock.Margin = System.Windows.Thickness(5.)
	
	WPFControls.Grid.SetRow(textBlock, row)
	WPFControls.Grid.SetColumn(textBlock, col)
	parent.Children.Add(textBlock)
	
	return textBlock

def updateComboBox(comboBox, comboItems):
	
	for comboItem in comboItems:
		item = WPFControls.ComboBoxItem()
		item.Content=comboItem
		comboBox.Items.Add(item)
	
def createEmptyRow(parent, row):
	textBlock = WPFControls.TextBlock()
	textBlock.Text = ""
	WPFControls.Grid.SetRow(textBlock, row)
	WPFControls.Grid.SetColumn(textBlock, 0)

	parent.Children.Add(textBlock)

	return


	
def createDataBox(parent, title, value, row, col):
	textBlock = WPFControls.TextBlock()
	textBlock.Text = title
	WPFControls.Grid.SetRow(textBlock, row)
	WPFControls.Grid.SetColumn(textBlock, col)

	textBox =WPFControls.TextBox()
	WPFControls.Grid.SetRow(textBox, row)
	WPFControls.Grid.SetColumn(textBox, col+1)
	textBox.Text=value
	
	parent.Children.Add(textBlock)
	parent.Children.Add(textBox)
	
	return textBox,textBlock

def createDataBox2(parent, value, row, col):
	textBox =WPFControls.TextBox()
	WPFControls.Grid.SetRow(textBox, row)
	WPFControls.Grid.SetColumn(textBox, col)
	textBox.Text=value
	
	parent.Children.Add(textBox)
	
	return textBox

def setPickFilterTools():
	pickChoices = System.Collections.Generic.List[System.String]()
	
	#exclusive picking and visibility picking	
	pickChoices.Add(apex_sdk.PickFilterTypes.ExclusivePicking)
	pickChoices.Add(apex_sdk.PickFilterTypes.VisibilityPicking)
	
	#Assembly and part
	#pickChoices.Add(apex_sdk.PickFilterTypes.Assembly)
	pickChoices.Add(apex_sdk.PickFilterTypes.Part)
	
	#Bodies	
	#pickChoices.Add(apex_sdk.PickFilterTypes.SolidMesh)
	#pickChoices.Add(apex_sdk.PickFilterTypes.Solid)
	#pickChoices.Add(apex_sdk.PickFilterTypes.SurfaceMesh)
	#pickChoices.Add(apex_sdk.PickFilterTypes.Surface)
	#pickChoices.Add(apex_sdk.PickFilterTypes.CurveMesh)
	#pickChoices.Add(apex_sdk.PickFilterTypes.Curve)
	#pickChoices.Add(apex_sdk.PickFilterTypes.Point)
	
	#features
	#pickChoices.Add(apex_sdk.PickFilterTypes.CellMesh)
	#pickChoices.Add(apex_sdk.PickFilterTypes.FaceMesh)
	#pickChoices.Add(apex_sdk.PickFilterTypes.EdgeMesh)
	#pickChoices.Add(apex_sdk.PickFilterTypes.Cell)
	#pickChoices.Add(apex_sdk.PickFilterTypes.VertexMesh)
	
	#Lower Dimensional Entities
	#pickChoices.Add(apex_sdk.PickFilterTypes.Element3D)
	#pickChoices.Add(apex_sdk.PickFilterTypes.Element2D)
	#pickChoices.Add(apex_sdk.PickFilterTypes.Face)
	#pickChoices.Add(apex_sdk.PickFilterTypes.MeshSeed)
	#pickChoices.Add(apex_sdk.PickFilterTypes.Element1D)
	#pickChoices.Add(apex_sdk.PickFilterTypes.Edge)
	#pickChoices.Add(apex_sdk.PickFilterTypes.SeedPoint)
	#pickChoices.Add(apex_sdk.PickFilterTypes.Node)
	#pickChoices.Add(apex_sdk.PickFilterTypes.Vertex)
	
	#Sub Lower Dimensional Entities
	#pickChoices.Add(apex_sdk.PickFilterTypes.ElementEdge)
	#pickChoices.Add(apex_sdk.PickFilterTypes.ElementFace)
	
	#Interactions and connections
	#pickChoices.Add(apex_sdk.PickFilterTypes.DiscreteTie)
	#pickChoices.Add(apex_sdk.PickFilterTypes.Connector)
	#pickChoices.Add(apex_sdk.PickFilterTypes.EdgeTie)
	#pickChoices.Add(apex_sdk.PickFilterTypes.Joint)
	#pickChoices.Add(apex_sdk.PickFilterTypes.Glue)
	
	#LBCs
	#pickChoices.Add(apex_sdk.PickFilterTypes.Pressure)
	#pickChoices.Add(apex_sdk.PickFilterTypes.Gravity)
	#pickChoices.Add(apex_sdk.PickFilterTypes.Constraint)
	#pickChoices.Add(apex_sdk.PickFilterTypes.ForceMoment)
	#pickChoices.Add(apex_sdk.PickFilterTypes.EnforcedMotion)
	
	#Attributes and other objects
	#pickChoices.Add(apex_sdk.PickFilterTypes.CompositeZone)
	#pickChoices.Add(apex_sdk.PickFilterTypes.LayeredPanel)
	#pickChoices.Add(apex_sdk.PickFilterTypes.InterfacePoint)
	#pickChoices.Add(apex_sdk.PickFilterTypes.PointMass)
	#pickChoices.Add(apex_sdk.PickFilterTypes.BeamSpan)
	#pickChoices.Add(apex_sdk.PickFilterTypes.Offset)
	
	#Sensors
	#pickChoices.Add(apex_sdk.PickFilterTypes.MotionEnvelopeSensor)
	#pickChoices.Add(apex_sdk.PickFilterTypes.ClearanceSensor)
	#pickChoices.Add(apex_sdk.PickFilterTypes.CrossSectionSensor)
	#pickChoices.Add(apex_sdk.PickFilterTypes.PointSensor)
	
	#Coordinate system
	#pickChoices.Add(apex_sdk.PickFilterTypes.CoordinateSystem)
	
	#Tool Registration
	#Tool Name has to be the same
	#apex_sdk.PickFilterRegistration.RegisterTool("Auto Tie Nodes", pickChoices)
	return pickChoices

def createCheckBox(parent, title, active, row, col):
	myWrapPanel = WPFControls.WrapPanel()
	myWrapPanel.Orientation = WPFControls.Orientation.Vertical

	CheckBox = WPFControls.CheckBox()
	CheckBox.Content = title
	myWrapPanel.Children.Add(CheckBox)

	WPFControls.Grid.SetRow(myWrapPanel, row)
	WPFControls.Grid.SetColumn(myWrapPanel, col)
	CheckBox.IsChecked = System.Nullable[System.Boolean](active)

	parent.Children.Add(myWrapPanel)

	return CheckBox



#Function to handle the Import Button "Click" event
#This function gets called every time the Button is clicked
@apex_sdk.errorhandler
def HandleSaveBtn(sender,args):

	#Create a File open dialog
	#dialog = OpenFileDialog()
	dialog = SaveFileDialog()
	
	#Configure for single file selection
	dialog.Multiselect = False
	
	#Set up the file types you want to support
	dialog.Filter = "All Files  |*.*"
	#dialog.Filter = "MWF Files  |*.mwf* | All Files  |*.*"

	#Display the dialog
	#If it returns anything
	#   get the file name
	#   display it on the text nox 
	if dialog.ShowDialog():
		selectedFile = dialog.FileName
		fileTextBox.Text = selectedFile


#Function to handle the Import Button "Click" event
#This function gets called every time the Button is clicked
@apex_sdk.errorhandler
def HandleUserOptionBtn(sender,args):

	#Create a File open dialog
	#dialog = OpenFileDialog()
	dialog = OpenFileDialog()
	
	#Configure for single file selection
	dialog.Multiselect = False
	
	#Set up the file types you want to support
	#dialog.Filter = "All Files  |*.*"
	#dialog.Filter = "xml Files  |*.xml* | All Files  |*.*"
	dialog.Filter = "All Files  |*.xml"

	#Display the dialog
	#If it returns anything
	#   get the file name
	#   display it on the text nox 
	if dialog.ShowDialog():
		selectedFile = dialog.FileName
		userOptionsTextBox.Text = selectedFile

		
@apex_sdk.errorhandler
def HandleApplyButton():
	file_path = os.path.dirname(os.path.realpath(__file__))
	script_path= os.path.join(file_path, 'bdfExport.py')
	# Create a Dictionary to store the user defined tool data  
	dictionary = {}
	

	
	choices = exportOptionComboBox.SelectedValue.ToString().split(":")
	choice = choices[len(choices)-1].lstrip().rstrip()
	dictionary["RunNastran"] = choice
	
	
	choices = exportOptionComboBox.SelectedValue.ToString().split(":")
	choice = choices[len(choices)-1].lstrip().rstrip()
	dictionary["RunNastran"] = choice
	
	choices = solverOptionComboBox.SelectedValue.ToString().split(":")
	choice = choices[len(choices)-1].lstrip().rstrip()
	dictionary["Solver"] = choice
	

	choices = exportUnitsComboBox.SelectedValue.ToString().split(":")
	choice = choices[len(choices)-1].lstrip().rstrip()
	dictionary["ExportUnitSystem"] = choice


	
	choices = methodTypeComboBox.SelectedValue.ToString().split(":")
	choice = choices[len(choices)-1].lstrip().rstrip()
	dictionary["AnalysisType"] = choice
	
	choices = postComboBox.SelectedValue.ToString().split(":")
	choice = choices[len(choices)-1].lstrip().rstrip()
	dictionary["PostOption"] = choice
	
	choices = scenariosComboBox.SelectedValue.ToString().split(":")
	choice = choices[len(choices)-1].lstrip().rstrip()
	
	dictionary["Scenario"] = choice
	dictionary["bdf_file"]  = fileTextBox.Text
	dictionary["xml_file"]  = userOptionsTextBox.Text
	
	
	# === Contact Settings ====
	choices = defaultContactTypeComboBox.SelectedValue.ToString().split(":")
	choice = choices[len(choices)-1].lstrip().rstrip()
	dictionary["contactType"]=choice
	
	choices = contactMethodComboBox.SelectedValue.ToString().split(":")
	choice = choices[len(choices)-1].lstrip().rstrip()
	dictionary["contactMethod"]=choice.replace("Node 2 Segment","NODESURF").replace("Segment 2 Segment","SEGTOSEG")
	
	dictionary['AnalyticContact']=analyticContact_Toggle.IsChecked
	dictionary['RetainGapOverlaps']=retainGapsOverlaps_Toggle.IsChecked
	dictionary['StressFreeInitial']=stressFreeInitial_Toggle.IsChecked
	
	dictionary['DefaultTouchingTol']=defaultTouchingTolTextBox.Text
	dictionary['DefaultGlueTol']=defaultGlueTolTextBox.Text
	dictionary['DefaultFriction']=defaultFrictTextBox.Text
	
	#  ---Misc Settings-----
	
	dictionary['ZeroLength']	=zeroLengthBush_Toggle.IsChecked
	dictionary['PatranGroups']	=patranGroups_Toggle.IsChecked
	dictionary['LargeDisp']	=largeDisp_Toggle.IsChecked
	dictionary['FollowerForce']	=followerForce_Toggle.IsChecked
	dictionary['ProcessRutman']	=processRutman_Toggle.IsChecked
	
	
	
	try:
		choices = ConsolidateOptionComboBox.SelectedValue.ToString().split(":")
		choice = choices[len(choices)-1].lstrip().rstrip()
		dictionary["ConsolidateThickness"] = choice
	except:
		dictionary["ConsolidateThickness"]="False"


	#dictionary['MergeTieRbars']=mergeZeroLengthRigids_Toggle.IsChecked
	
	choices = autoMsetComboBox.SelectedValue.ToString().split(":")
	choice= choices[len(choices)-1].lstrip().rstrip()
	dictionary['AutoMset']=choice
	
	dictionary['AutoSpcEps']=AutoSpcEpsTextBox.Text


	try:
		dictionary["nodeThicknessLo"]     = nodeThicknessLoTextBox.Text
		dictionary["nodeThicknessUp"]     = nodeThicknessUpTextBox.Text
		dictionary["ThicknessRangeInc"]     = ThicknessRangeIncTextBox.Text
	except:
		pass
		
	# --------------

	
	#dictionary['editContactTable']=editContactTable_Toggle.IsChecked
	
	#choices = sol400ModeComboBox.SelectedValue.ToString().split(":")
	#choice = choices[len(choices)-1].lstrip().rstrip()
	

	eventSteps=""
	eventSteps += loadStep_1TextBox.Text +","
	eventSteps += loadStep_2TextBox.Text +","
	eventSteps += loadStep_3TextBox.Text +","	
	eventSteps += loadStep_4TextBox.Text +","	
	eventSteps += loadStep_5TextBox.Text +","
	eventSteps += loadStep_6TextBox.Text +","
	eventSteps += loadStep_7TextBox.Text +","
	eventSteps += loadStep_8TextBox.Text +","
	eventSteps += loadStep_9TextBox.Text +","
	eventSteps += loadStep_10TextBox.Text
	
	eventEpsp=""
	eventEpsp += sol400epsp_1TextBox.Text +","
	eventEpsp += sol400epsp_2TextBox.Text +","
	eventEpsp += sol400epsp_3TextBox.Text +","	
	eventEpsp += sol400epsp_4TextBox.Text +","	
	eventEpsp += sol400epsp_5TextBox.Text +","
	eventEpsp += sol400epsp_6TextBox.Text +","
	eventEpsp += sol400epsp_7TextBox.Text +","
	eventEpsp += sol400epsp_8TextBox.Text +","
	eventEpsp += sol400epsp_9TextBox.Text +","
	eventEpsp += sol400epsp_10TextBox.Text
	
	eventEpsu=""
	eventEpsu += sol400epsu_1TextBox.Text +","
	eventEpsu += sol400epsu_2TextBox.Text +","
	eventEpsu += sol400epsu_3TextBox.Text +","	
	eventEpsu += sol400epsu_4TextBox.Text +","	
	eventEpsu += sol400epsu_5TextBox.Text +","
	eventEpsu += sol400epsu_6TextBox.Text +","
	eventEpsu += sol400epsu_7TextBox.Text +","
	eventEpsu += sol400epsu_8TextBox.Text +","
	eventEpsu += sol400epsu_9TextBox.Text +","
	eventEpsu += sol400epsu_10TextBox.Text	
	
	
	eventConvCrit=""
	choices = sol400_convcrit_1ComboBox.SelectedValue.ToString().split(":")
	eventConvCrit += choices[len(choices)-1].lstrip().rstrip() + ","
	
	choices = sol400_convcrit_2ComboBox.SelectedValue.ToString().split(":")
	eventConvCrit += choices[len(choices)-1].lstrip().rstrip() + ","
	
	choices = sol400_convcrit_3ComboBox.SelectedValue.ToString().split(":")
	eventConvCrit += choices[len(choices)-1].lstrip().rstrip() + ","
	
	choices = sol400_convcrit_4ComboBox.SelectedValue.ToString().split(":")
	eventConvCrit += choices[len(choices)-1].lstrip().rstrip() + ","	
	
	choices = sol400_convcrit_5ComboBox.SelectedValue.ToString().split(":")
	eventConvCrit += choices[len(choices)-1].lstrip().rstrip() + ","
	
	choices = sol400_convcrit_6ComboBox.SelectedValue.ToString().split(":")
	eventConvCrit += choices[len(choices)-1].lstrip().rstrip() + ","
	
	choices = sol400_convcrit_7ComboBox.SelectedValue.ToString().split(":")
	eventConvCrit += choices[len(choices)-1].lstrip().rstrip() + ","
	
	choices = sol400_convcrit_8ComboBox.SelectedValue.ToString().split(":")
	eventConvCrit += choices[len(choices)-1].lstrip().rstrip() + ","	
	
	choices = sol400_convcrit_9ComboBox.SelectedValue.ToString().split(":")
	eventConvCrit += choices[len(choices)-1].lstrip().rstrip() + ","
	
	choices = sol400_convcrit_10ComboBox.SelectedValue.ToString().split(":")
	eventConvCrit += choices[len(choices)-1].lstrip().rstrip() + ","	
	
	
	dictionary['eventSteps']=eventSteps
	dictionary['eventEpsp']=eventEpsp
	dictionary['eventEpsu']=eventEpsu
	dictionary['eventConvCrit']=eventConvCrit
	
	#aaa_file=r"C:\Users\e7390\Documents\MSC_Apex Workspace\Custom Tools 2021\Apex Utilities\Utilities\Export\ExportUtils\test\Temp\apa.txt"
	#aaa_file_h=open(aaa_file,'w')
	#for key in dictionary.keys():
	#
	#	aaa_file_h.write("dict[" + key + ']=' + str(dictionary[key])+ '\n')
	#aaa_file_h.close()
		
	apex_sdk.runScriptFunction(script_path, "main", dictionary)
		
# exit button (red) from tool header
@apex_sdk.errorhandler
def HandleExitButton():
	print("HandleExitButton")



#This function receives data from the Script API function and updates the Tool UI 
@apex_sdk.errorhandler
def getNewScenariosCB():
	#global scenariosComboBox
	#global eventNameL
	#global scenarioNameL
	#global eventComboBox
	
	ret_dict = apex_sdk.getScriptFunctionReturnData()
	#scenarios=["Entire Model- Default Loadcase"]
	# do not allow default scenario
	scenarios=[]
	scenarioNameL=[]
	# Build Scenario list
	try:
		tmp = ret_dict["ScenarioList"]
	except:
		print("No scenarios found")
		tmp=[]

	for item in tmp:
		scenarios.append(item)

		scenarioNameL=scenarios
	# Get the events Dict

	# Build Event list
	#eventNameL=['Default Loadcase']
	eventNameL=[]
	
	try:
		eventNameL.extend(ret_dict["EventL"])
	except:
		print("No Events Found")


	event_file=os.path.dirname(__file__) + '/events.txt'
	event_file_h=open(event_file,'w')
	for item in eventNameL:
		event_file_h.write(item + "\n")
	event_file_h.close()
	print("EventFiles Created:",datetime.datetime.now())
	
	scenario_file=os.path.dirname(__file__) + '/scenarios.txt'
	scenario_file_h=open(scenario_file,'w')
	
	for item2 in scenarioNameL:
		scenario_file_h.write(item2 + "\n")
	scenario_file_h.close()
	print("ScenarioFiles Created:",datetime.datetime.now())
	
	print("Exported Scenes and events")
	
	
	updateComboBox2(scenariosComboBox,scenarios )
	


	