########################################################################
#                                                                      #
#  main.tcl main script for Swumsuit                                   #
#                                             since 2004.12.3          #
#                                             (c) Motomu Nakashima     #
#                                                                      #
########################################################################

# Setup routine. Open windows, packing, etc...
proc MainSetup {} {

    # Project_folder frame
    global Project_folder
    labelframe .project -text $Project_folder -padx 3 -pady 3
    global Create
    button .project.create -text $Create -anchor w \
                                     -command MainCreateFolder
    global Open
    button .project.open   -text $Open -anchor w \
                                     -command MainOpenFolder
    global Save_as
    button .project.save   -text $Save_as -anchor w \
                                     -command MainSaveFolder
    global Info
    button .project.info   -text $Info -anchor w -command ViewComment

    #global Exit EngineExeFile
    #button .project.exit   -text $Exit -anchor w -command exit
    pack \
       .project.create \
       .project.open \
       .project.save \
       .project.info \
       -fill x

    # Open menus
    menu .openm -tearoff false
    global Choose
    .openm add command -label $Choose \
                      -command MainSelectOpenFolder
    .openm add separator
    AddOpenHistory


    # Input frame
    global Input
    labelframe .input -text $Input -padx 3 -pady 3
    global Edit_Body_Geometry
    global Edit_Joint_Motion
    global Load_Body_Geometry
    global Load_Joint_Motion
    #global EditJointMotionExecute
    #global EditBodyGeometryExecute
    global sourcedir
    button .input.geometry  -text $Edit_Body_Geometry  -anchor w \
                       -command EditBodyGeometryExecute
    button .input.motion    -text $Edit_Joint_Motion    -anchor w \
                       -command EditJointMotionExecute
    button .input.lgeometry -text $Load_Body_Geometry  -anchor w \
                            -command LoadBodyGeometry
    button .input.lmotion   -text $Load_Joint_Motion    -anchor w \
                            -command LoadJointMotion
    pack \
       .input.geometry \
       .input.motion \
       .input.lgeometry \
       .input.lmotion \
     -fill x -anchor n

    # Analysis frame
    global Analysis
    global Start_Analysis
    global Edit_Analysis_Settings
    global Load_Analysis_Settings
    labelframe .analysis -text $Analysis -padx 3 -pady 3
    button .analysis.analysis -text $Start_Analysis   -anchor w \
                                  -command StartAnalysis
    button .analysis.edit_setting -text $Edit_Analysis_Settings \
                                           -anchor w \
                                  -command EditAnalysisSettings
    button .analysis.load_setting -text $Load_Analysis_Settings \
                                           -anchor w \
                                  -command LoadAnalysisSettings
    pack \
       .analysis.analysis \
       .analysis.edit_setting \
       .analysis.load_setting \
       -fill x -anchor n

    # For AnyBody
    global anybody_brep_folder Invoke_AnyBody
    if {$anybody_brep_folder!=""} {
        global anybody_brep_folder Invoke_AnyBody
        button .analysis.invoke_anybody -text $Invoke_AnyBody \
                             -anchor w -command InvokeAnyBody
        pack .analysis.invoke_anybody -fill x -anchor n
    }

    # Analysis menus
    menu .anam -tearoff false
     global Calculation_settings Initial_condition Output_settings \
            Optimization_settings Edit_scripts_for_optimization \
            Penetration_judging_settings
     global Script_to_set_initial_values_of_design_parameters \
            Script_to_set_design_parameters \
            Script_to_set_objective_function

    .anam add command -label $Calculation_settings \
                      -command EditCalcSettings
    .anam add command -label $Initial_condition \
                      -command EditInitialCondition
    .anam add command -label $Output_settings \
                      -command EditOutputSettings
    #if {$anybody_brep_folder!=""} {
    #    global Musculo_skeletal_settings
    #    .anam add command -label $Musculo_skeletal_settings \
    #                  -command EditAnyBodySettings
    #}
    .anam add command -label $Penetration_judging_settings \
                      -command EditPeneJudgeSettings
    .anam add command -label $Optimization_settings \
                      -command EditOptSettings
    .anam add separator
    .anam add cascade -label $Edit_scripts_for_optimization \
                      -menu .anam.opt

    menu .anam.opt -tearoff false
    .anam.opt add command \
        -label $Script_to_set_initial_values_of_design_parameters \
                   -command "EditOptScript opt_initial_values.tcl"
    .anam.opt add command \
        -label $Script_to_set_design_parameters \
                   -command "EditOptScript opt_design_parameters.tcl"
    .anam.opt add command \
        -label $Script_to_set_objective_function \
                   -command "EditOptScript opt_objective_function.tcl"

    global alloreach
    set alloreach all

    # Output frame
    global Output Animation Graph Optimization_log
    labelframe .output -text " $Output " -padx 3 -pady 3
    button .output.animation -text $Animation      -anchor w \
                             -command AnimateStart
    button .output.graph -text $Graph -anchor w \
  -command { DeleteExeFile ; tk_popup .gm [winfo pointerx .] [expr [winfo pointery .]+5]}
    button .output.log -text $Optimization_log -anchor w \
                       -command "OpenOptLogWindow"
    pack \
       .output.animation \
       .output.graph \
       .output.log   \
       -fill x -anchor n

    # Graph menus
    menu .gm -tearoff false
    global Quantity_Per_Cycle Rigid_Body_Motion Force_Moment_Power \
           Joint_Torque
    .gm add cascade -label $Quantity_Per_Cycle  -menu .gm.q
    .gm add cascade -label $Rigid_Body_Motion   -menu .gm.r
    .gm add cascade -label $Force_Moment_Power -menu .gm.f
    .gm add cascade -label $Joint_Torque        -menu .gm.j

    global Swimming_Speed Stroke_Length Direction \
           Power_Efficiency1 Power_Efficiency2 \
           Input_Power_Per_Cycle \
           Output_Power_Per_Cycle1 Output_Power_Per_Cycle2
    menu .gm.q -tearoff false
    .gm.q add command -label $Swimming_Speed \
                      -command "DrawGraph swimming_speed.dat"
    .gm.q add command -label $Stroke_Length \
                      -command "DrawGraph stroke_length.dat"
    .gm.q add command -label $Direction \
                      -command "DrawGraph direction.dat"
    .gm.q add command -label $Power_Efficiency1 \
                      -command "DrawGraph power_efficiency1.dat"
    .gm.q add command -label $Power_Efficiency2 \
                      -command "DrawGraph power_efficiency2.dat"
    .gm.q add command -label $Input_Power_Per_Cycle \
                      -command "DrawGraph input_power.dat"
    .gm.q add command -label $Output_Power_Per_Cycle1 \
                      -command "DrawGraph output_power1.dat"
    .gm.q add command -label $Output_Power_Per_Cycle2 \
                      -command "DrawGraph output_power2.dat"

    menu .gm.r -tearoff false
    global Position_x Position_y Position_z x_y_Locus
    global Velocity_x Velocity_y Velocity_z
    global Angular_Velocity_Axis1 Angular_Velocity_Axis2 \
           Angular_Velocity_Axis3
    global Acceleration_x Acceleration_y Acceleration_z
    global Angular_Acceleration_Axis1 Angular_Acceleration_Axis2 \
           Angular_Acceleration_Axis3
    .gm.r add command -label $Position_x \
                      -command "DrawGraph position_x.dat"
    .gm.r add command -label $Position_y \
                      -command "DrawGraph position_y.dat"
    .gm.r add command -label $Position_z \
                      -command "DrawGraph position_z.dat"
    .gm.r add command -label $x_y_Locus \
                      -command "DrawGraph x-y_locus.dat"
    .gm.r add command -label $Velocity_x \
                      -command "DrawGraph velocity_x.dat"
    .gm.r add command -label $Velocity_y \
                      -command "DrawGraph velocity_y.dat"
    .gm.r add command -label $Velocity_z \
                      -command "DrawGraph velocity_z.dat"
    .gm.r add command -label $Angular_Velocity_Axis1 \
                      -command "DrawGraph angular_velocity_1.dat"
    .gm.r add command -label $Angular_Velocity_Axis2 \
                      -command "DrawGraph angular_velocity_2.dat"
    .gm.r add command -label $Angular_Velocity_Axis3 \
                      -command "DrawGraph angular_velocity_3.dat"
    .gm.r add command -label $Acceleration_x \
                      -command "DrawGraph acceleration_x.dat"
    .gm.r add command -label $Acceleration_y \
                      -command "DrawGraph acceleration_y.dat"
    .gm.r add command -label $Acceleration_z \
                      -command "DrawGraph acceleration_z.dat"
    .gm.r add command -label $Angular_Acceleration_Axis1 \
                      -command "DrawGraph angular_acceleration_1.dat"
    .gm.r add command -label $Angular_Acceleration_Axis2 \
                      -command "DrawGraph angular_acceleration_2.dat"
    .gm.r add command -label $Angular_Acceleration_Axis3 \
                      -command "DrawGraph angular_acceleration_3.dat"

    menu .gm.f -tearoff false
    global Force_x Force_y Force_z \
           Moment_Axis1 Moment_Axis2 Moment_Axis3 \
           Power_x Power_y Power_z
    .gm.f add cascade -label $Force_x      -menu .gm.f.force_x
    .gm.f add cascade -label $Force_y      -menu .gm.f.force_y
    .gm.f add cascade -label $Force_z      -menu .gm.f.force_z
    .gm.f add cascade -label $Moment_Axis1 -menu .gm.f.moment_1
    .gm.f add cascade -label $Moment_Axis2 -menu .gm.f.moment_2
    .gm.f add cascade -label $Moment_Axis3 -menu .gm.f.moment_3
    .gm.f add cascade -label $Power_x      -menu .gm.f.power_x
    .gm.f add cascade -label $Power_y      -menu .gm.f.power_y
    .gm.f add cascade -label $Power_z      -menu .gm.f.power_z

    foreach m {force_x force_y force_z moment_1 moment_2 moment_3 power_x power_y power_z} {
        menu .gm.f.$m -tearoff false
        global Whole_Body Trunk_with_Head Right_Upper_Limb Left_Upper_Limb \
               Right_Lower_Limb Left_Lower_Limb segm_name
        .gm.f.$m add command -label $Whole_Body \
                  -command "DrawGraph ${m}_000whole_body.dat"
        .gm.f.$m add separator
        .gm.f.$m add command -label $Trunk_with_Head \
                  -command "DrawGraph ${m}_001trunk_with_head.dat"
        .gm.f.$m add command -label $Right_Upper_Limb \
                  -command "DrawGraph ${m}_002right_upper_limb.dat"
        .gm.f.$m add command -label $Left_Upper_Limb \
                  -command "DrawGraph ${m}_003left_upper_limb.dat"
        .gm.f.$m add command -label $Right_Lower_Limb \
                  -command "DrawGraph ${m}_004right_lower_limb.dat"
        .gm.f.$m add command -label $Left_Lower_Limb \
                  -command "DrawGraph ${m}_005left_lower_limb.dat"
        .gm.f.$m add separator
        .gm.f.$m add command -label $segm_name(1) \
                  -command "DrawGraph ${m}_01lower_waist.dat"
        .gm.f.$m add command -label $segm_name(2) \
                  -command "DrawGraph ${m}_02upper_waist.dat"
        .gm.f.$m add command -label $segm_name(3) \
                  -command "DrawGraph ${m}_03lower_breast.dat"
        .gm.f.$m add command -label $segm_name(4) \
                  -command "DrawGraph ${m}_04upper_breast.dat"
        .gm.f.$m add command -label $segm_name(5) \
                  -command "DrawGraph ${m}_05shoulder.dat"
        .gm.f.$m add command -label $segm_name(6) \
                  -command "DrawGraph ${m}_06neck.dat"
        .gm.f.$m add command -label $segm_name(7) \
                  -command "DrawGraph ${m}_07head.dat"
        .gm.f.$m add command -label $segm_name(8) \
                  -command "DrawGraph ${m}_08upper_hip.dat"
        .gm.f.$m add command -label $segm_name(9) \
                  -command "DrawGraph ${m}_09lower_hip.dat"
        .gm.f.$m add command -label $segm_name(10) \
                  -command "DrawGraph ${m}_10right_thigh.dat"
        .gm.f.$m add command -label $segm_name(11) \
                  -command "DrawGraph ${m}_11left_thigh.dat"
        .gm.f.$m add command -label $segm_name(12) \
                  -command "DrawGraph ${m}_12right_shank.dat"
        .gm.f.$m add command -label $segm_name(13) \
                  -command "DrawGraph ${m}_13left_shank.dat"
        .gm.f.$m add command -label $segm_name(14) \
                  -command "DrawGraph ${m}_14right_foot.dat"
        .gm.f.$m add command -label $segm_name(15) \
                  -command "DrawGraph ${m}_15left_foot.dat"
        .gm.f.$m add command -label $segm_name(16) \
                  -command "DrawGraph ${m}_16right_upper_arm.dat"
        .gm.f.$m add command -label $segm_name(17) \
                  -command "DrawGraph ${m}_17left_upper_arm.dat"
        .gm.f.$m add command -label $segm_name(18) \
                  -command "DrawGraph ${m}_18right_forearm.dat"
        .gm.f.$m add command -label $segm_name(19) \
                  -command "DrawGraph ${m}_19left_forearm.dat"
        .gm.f.$m add command -label $segm_name(20) \
                  -command "DrawGraph ${m}_20right_hand.dat"
        .gm.f.$m add command -label $segm_name(21) \
                  -command "DrawGraph ${m}_21left_hand.dat"
    }

    menu .gm.j -tearoff false
    .gm.j add cascade -label x  -menu .gm.j.x
    .gm.j add cascade -label y  -menu .gm.j.y
    .gm.j add cascade -label z  -menu .gm.j.z
    .gm.j add separator
    .gm.j add cascade -label xb -menu .gm.j.xb
    .gm.j add cascade -label yb -menu .gm.j.yb
    .gm.j add cascade -label zb -menu .gm.j.zb

    foreach m {x y z xb yb zb} {
        menu .gm.j.$m -tearoff false
        #for {set i 2} {$i<=21} {incr i} {
        #    .gm.j.$m add command -label $segm_name($i)
        #}
        .gm.j.$m add command -label $segm_name(1) \
            -command "DrawGraph joint_torque_${m}_01lower_waist.dat"
        .gm.j.$m add command -label $segm_name(2) \
            -command "DrawGraph joint_torque_${m}_02upper_waist.dat"
        .gm.j.$m add command -label $segm_name(3) \
            -command "DrawGraph joint_torque_${m}_03lower_breast.dat"
        .gm.j.$m add command -label $segm_name(4) \
            -command "DrawGraph joint_torque_${m}_04upper_breast.dat"
        .gm.j.$m add command -label $segm_name(5) \
            -command "DrawGraph joint_torque_${m}_05shoulder.dat"
        .gm.j.$m add command -label $segm_name(6) \
            -command "DrawGraph joint_torque_${m}_06neck.dat"
        .gm.j.$m add command -label $segm_name(7) \
            -command "DrawGraph joint_torque_${m}_07head.dat"
        .gm.j.$m add command -label $segm_name(8) \
            -command "DrawGraph joint_torque_${m}_08upper_hip.dat"
        .gm.j.$m add command -label $segm_name(9) \
            -command "DrawGraph joint_torque_${m}_09lower_hip.dat"
        .gm.j.$m add command -label $segm_name(10) \
            -command "DrawGraph joint_torque_${m}_10right_thigh.dat"
        .gm.j.$m add command -label $segm_name(11) \
            -command "DrawGraph joint_torque_${m}_11left_thigh.dat"
        .gm.j.$m add command -label $segm_name(12) \
            -command "DrawGraph joint_torque_${m}_12right_shank.dat"
        .gm.j.$m add command -label $segm_name(13) \
            -command "DrawGraph joint_torque_${m}_13left_shank.dat"
        .gm.j.$m add command -label $segm_name(14) \
            -command "DrawGraph joint_torque_${m}_14right_foot.dat"
        .gm.j.$m add command -label $segm_name(15) \
            -command "DrawGraph joint_torque_${m}_15left_foot.dat"
        .gm.j.$m add command -label $segm_name(16) \
            -command "DrawGraph joint_torque_${m}_16right_upper_arm.dat"
        .gm.j.$m add command -label $segm_name(17) \
            -command "DrawGraph joint_torque_${m}_17left_upper_arm.dat"
        .gm.j.$m add command -label $segm_name(18) \
            -command "DrawGraph joint_torque_${m}_18right_forearm.dat"
        .gm.j.$m add command -label $segm_name(19) \
            -command "DrawGraph joint_torque_${m}_19left_forearm.dat"
        .gm.j.$m add command -label $segm_name(20) \
            -command "DrawGraph joint_torque_${m}_20right_hand.dat"
        .gm.j.$m add command -label $segm_name(21) \
            -command "DrawGraph joint_torque_${m}_21left_hand.dat"
    }

    # Help frame
    global Help Preferences Manual About Exit
    labelframe .help -text $Help -padx 3 -pady 3
    button .help.option -text $Preferences -anchor w \
                              -command InvokePreferences
    button .help.manual -text $Manual -anchor w -command ManualMessage
    button .help.about  -text $About  -anchor w -command InvokeAbout
    button .help.exit   -text $Exit -anchor w -command exit
    pack \
        .help.option \
        .help.manual \
        .help.about \
        .help.exit \
       -fill x -anchor n

    # Pack all frames
    pack \
        .project \
	.input \
	.analysis \
	.output \
	.help \
        -side left -padx 2 -pady 3 -anchor n

    ChangeIcon .
}


# Create New Project Folder
proc MainCreateFolder {} {
    global dname
    set d [tk_chooseDirectory -initialdir $dname]
    if { [string length $d]!=0 } {
        # mkdir
        file mkdir $d
        # change directory
        set dname $d
        cd $dname
        wm title . "Swumsuit: [pwd]"

        # convert dname for "space"
        set dname2 $dname
        set starti 0
        while {[string first "\ " $dname2 $starti]!="-1"} {
            set i [string first "\ " $dname2 $starti]
            set newdname [string replace $dname2 $i $i "\\\ "]
            set dname2 $newdname
	    set starti [expr $i+2]
        }

        # Add dname to menu and history file
        .openm insert 2 command -label $dname2 \
                   -command "MainOpenFolderExecute $dname2"
        global env Swumsuit_history
        set history ""
        if {[file exists $env(HOME)/$Swumsuit_history]==1} {
            set f [open $env(HOME)/$Swumsuit_history r]
            set history [read $f]
            close $f
        }
        set f [open $env(HOME)/$Swumsuit_history w]
        puts $f $dname2
        puts $f $history
        close $f
        # read once again only for 10 lines
        set f [open $env(HOME)/$Swumsuit_history r]
        set history ""
        set line [gets $f]
        set history $history\n$line
        set line2 [gets $f]
        if {$line==$line2} {
            .openm delete 2
        } else {
            set history $history\n$line2
        }
        global history_length
        for {set i 3} {$i<=$history_length} {incr i} {
            set line [gets $f]
            set history $history\n$line
        }
        close $f
        set history [string trim $history]
        # write once again
        set f [open $env(HOME)/$Swumsuit_history w]
        puts $f $history
        close $f
    }
}


# Add Open History
proc AddOpenHistory {} {
    global env Swumsuit_history dname
    if {[file exists $env(HOME)/$Swumsuit_history]==1} {
        set f [open $env(HOME)/$Swumsuit_history r]
        while {[gets $f line]!="-1"} {
            regsub -all \; $line \\\; line2
            .openm add command -label $line2 \
              -command "MainOpenFolderExecute $line2"
        }
        close $f
    }
}


# Main Open Folder
proc MainOpenFolder {} {
    tk_popup .openm [expr [winfo pointerx .]-5] [expr [winfo pointery .]-5]
}


# Select Project Folder to be Opened
proc MainSelectOpenFolder {} {
    global dname
    set d [tk_chooseDirectory -initialdir $dname]
    MainOpenFolderExecute $d
}

# Open Project Folder
proc MainOpenFolderExecute { d } {
    global dname

    if { [string length $d]!=0 } {
        set dname $d
        cd $dname

        # convert dname for "space"
	set dname2 $dname
        set starti 0
        while {[string first "\ " $dname2 $starti]!="-1"} {
            set i [string first "\ " $dname2 $starti]
            set newdname [string replace $dname2 $i $i "\\\ "]
            set dname2 $newdname
	    set starti [expr $i+2]
        }

        # Add dname to menu and history file
        .openm insert 2 command -label $dname2 \
                   -command "MainOpenFolderExecute $dname2"
        global env Swumsuit_history
        set history ""
        if {[file exists $env(HOME)/$Swumsuit_history]==1} {
            set f [open $env(HOME)/$Swumsuit_history r]
            set history [read $f]
            close $f
        }
        set f [open $env(HOME)/$Swumsuit_history w]
       
        puts $f $dname2
        puts $f $history
        close $f
        # read once again only for 10 lines
        set f [open $env(HOME)/$Swumsuit_history r]
        set history ""
        set line [gets $f]
        set history $history\n$line
        set line2 [gets $f]
        if {$line==$line2} {
            .openm delete 2
        } else {
            set history $history\n$line2
        }
        global history_length
        for {set i 3} {$i<=$history_length} {incr i} {
            set line [gets $f]
            set history $history\n$line
        }
        close $f
        set history [string trim $history]
        # write once again
        set f [open $env(HOME)/$Swumsuit_history w]
        puts $f $history
        close $f

        # Check if necessary *.dat files exist
        # and warn when no file
        if { [file exists body_geometry.dat]==0 } {
            global No_body_geometry_file
            tk_messageBox -type ok -message $No_body_geometry_file \
                          -icon warning
        }
        if { [file exists joint_motion.dat]==0 } {
            global No_joint_motion_file
            tk_messageBox -type ok -message $No_joint_motion_file \
                          -icon warning
        }
        if { [file exists analysis_settings.dat]==0 } {
            global No_analysis_settings_file
            tk_messageBox -type ok -message $No_analysis_settings_file \
                          -icon warning
        }
        wm title . "Swumsuit: [pwd]"

        # load analysis settings.dat (if exists) for global variables
        #     ("multi" and "num_subprojects")
        if { [file exists analysis_settings.dat]==1 } {
            LoadAutoAnalysisSettings
        }

        # open dialog
        global OK Project_folder Was_opened
        tk_messageBox -type ok -icon info \
                -message "$Project_folder [pwd] $Was_opened"

        # delete exe file (if exists)
        DeleteExeFile
        #global EngineExeFile
        #catch { file delete -force $EngineExeFile }
    }
}


# Save Project Folder
proc MainSaveFolder {} {
    global dname

    # get parent directory
    #set e [string last / $dname]
    #if {$e!="-1"} {
    #    set dname2 [string range $dname 0 [expr $e-1]]
    #} else {
    #    set dname2 $dname
    #}

    set d [tk_chooseDirectory -initialdir $dname]
    if { [string length $d]!=0 } {
    if { $d!=$dname } {
        # mkdir folder (if does not exist)
        if { [file exists $d]==0 } {
            file mkdir $d
        }
	# ask if copy comment file
	if {[file exists comment.dat]==1} {
	    global Copy_comment_file
	    set q [tk_messageBox -type yesno -icon question \
	              -message $Copy_comment_file ]
            if {$q=="yes"} {
                file copy -force $dname/comment.dat $d/comment.dat
	    }
	}
        # copy dat files (if exists)
        if { [file exists body_geometry.dat]==1 } {
            file copy -force $dname/body_geometry.dat \
                               $d/body_geometry.dat
        }
        if { [file exists joint_motion.dat]==1 } {
            file copy -force $dname/joint_motion.dat \
                               $d/joint_motion.dat
        }
        if { [file exists analysis_settings.dat]==1 } {
            file copy -force $dname/analysis_settings.dat \
                               $d/analysis_settings.dat
        }
        if { [file exists comment.dat]==1 } {
            file copy -force $dname/comment.dat \
                               $d/comment.dat
        }
        if { [file exists optimization_log.dat]==1 } {
            file copy -force $dname/optimization_log.dat \
                               $d/optimization_log.dat
        }
        # copy tcl scripts for optimization (if exists)
        if { [file exists opt_design_parameters.tcl]==1 } {
            file copy -force $dname/opt_design_parameters.tcl \
                               $d/opt_design_parameters.tcl
        }
        if { [file exists opt_initial_values.tcl]==1 } {
            file copy -force $dname/opt_initial_values.tcl \
                               $d/opt_initial_values.tcl
        }
        if { [file exists opt_objective_function.tcl]==1 } {
            file copy -force $dname/opt_objective_function.tcl \
                               $d/opt_objective_function.tcl
        }
        # change directory
        set dname $d
        cd $dname
        wm title . "Swumsuit: [pwd]"

        # convert dname for "space"
        set dname2 $dname
        set starti 0
        while {[string first "\ " $dname2 $starti]!="-1"} {
            set i [string first "\ " $dname2 $starti]
            set newdname [string replace $dname2 $i $i "\\\ "]
            set dname2 $newdname
	    set starti [expr $i+2]
        }

        # Add dname to menu and history file
        .openm insert 2 command -label $dname2 \
                   -command "MainOpenFolderExecute $dname2"
        global env Swumsuit_history
        set history ""
        if {[file exists $env(HOME)/$Swumsuit_history]==1} {
            set f [open $env(HOME)/$Swumsuit_history r]
            set history [read $f]
            close $f
        }
        set f [open $env(HOME)/$Swumsuit_history w]
        puts $f $dname2
        puts $f $history
        close $f
        # read once again only for 10 lines
        set f [open $env(HOME)/$Swumsuit_history r]
        set history ""
        set line [gets $f]
        set history $history\n$line
        set line2 [gets $f]
        if {$line==$line2} {
            .openm delete 2
        } else {
            set history $history\n$line2
        }
        global history_length
        for {set i 3} {$i<=$history_length} {incr i} {
            set line [gets $f]
            set history $history\n$line
        }
        close $f
        set history [string trim $history]
        # write once again
        set f [open $env(HOME)/$Swumsuit_history w]
        puts $f $history
        close $f
    }
    }
}


# Load Body Geometry
proc LoadBodyGeometry {} {
    global Confirm_load_body_geometry OK Cancel
    set a [tk_dialog .dialog "Confirm" $Confirm_load_body_geometry \
            "" 1 $OK $Cancel]
    if {$a==1} {return}

    global dname
    set f [tk_getOpenFile -initialdir $dname \
             -filetypes { {"Swumsuit data file" {.dat}} \
                          {"All files" *} } ]
    if { [string length $f]!=0 } {
        file copy -force $f $dname/body_geometry.dat
    }
}


# Load Joint Motion
proc LoadJointMotion {} {
    global Confirm_load_joint_motion OK Cancel
    set a [tk_dialog .dialog "Confirm" $Confirm_load_joint_motion \
            "" 1 $OK $Cancel]
    if {$a==1} {return}

    global dname
    set f [tk_getOpenFile -initialdir $dname \
             -filetypes { {"Swumsuit data file" {.dat}} \
                          {"All files" *} } ]
    if { [string length $f]!=0 } {
        file copy -force $f $dname/joint_motion.dat
    }
}


# Load Analysis Settings
proc LoadAnalysisSettings {} {
    global Confirm_load_analysis_settings OK Cancel
    set a [tk_dialog .dialog "Confirm" $Confirm_load_analysis_settings \
            "" 1 $OK $Cancel]
    if {$a==1} {return}

    global dname
    set f [tk_getOpenFile -initialdir $dname \
             -filetypes { {"Swumsuit data file" {.dat}} \
                          {"All files" *} } ]
    if { [string length $f]!=0 } {
        file copy -force $f $dname/analysis_settings.dat
    }
}


# Start analysis
proc StartAnalysis {} {
    global Start_analysis_message
    set a [tk_messageBox -type okcancel -default ok -icon question \
            -message $Start_analysis_message]
    if {$a=="ok"} {

        if { [file exists body_geometry.dat]==0 } {
            global No_body_geometry_file
            tk_messageBox -type ok -message $No_body_geometry_file \
                          -icon error
            return
        }
        if { [file exists joint_motion.dat]==0 } {
            global No_joint_motion_file
            tk_messageBox -type ok -message $No_joint_motion_file \
                          -icon error
            return
        }
        if { [file exists analysis_settings.dat]==0 } {
            global No_analysis_settings_file
            tk_messageBox -type ok -message $No_analysis_settings_file \
                          -icon error
            return
        }
 
        global opt_flag
        if {$opt_flag=="1"} {
            if { [file exists opt_initial_values.tcl]==0 } {
                global No_initial_values_file
                tk_messageBox -type ok -icon error \
                    -message $No_initial_values_file 
                return
            }

            if { [file exists opt_design_parameters.tcl]==0 } {
                global No_design_parameters_file
                tk_messageBox -type ok -icon error \
                    -message $No_design_parameters_file 
                return
            }

            if { [file exists opt_objective_function.tcl]==0 } {
                global No_objective_function_file
                tk_messageBox -type ok -icon error \
                    -message $No_objective_function_file 
                return
            }
        }
 
        # if fluid force coefficients are in old format,
        # correct analysis_setteings.dat
        CorrectAnalysisSettings
        CorrectAnalysisSettings2
        CorrectAnalysisSettings3
        # If AnyBody setting is not found, append value of flagoutm
        CorrectAnalysisSettings4
        # If "numb" setting is not found, append value of numb
        CorrectAnalysisSettings5
        # If "conam" setting is not found, append value of conam
        CorrectAnalysisSettings6
        # If "multi" setting is not found, append value of multi
        CorrectAnalysisSettings7
        # If "pcn" setting is not found, append value of pcn
        CorrectAnalysisSettings8

        # load analysis settings
        LoadAutoAnalysisSettings

        global vgxsolv vgysolv vgzsolv ome1solv ome2solv ome3solv

        if {$vgxsolv=="0"} {
            if { [file exists input_vgx.dat]==0 } {
                global No_input_vgx_file
                tk_messageBox -type ok -message $No_input_vgx_file \
                              -icon error
                return
            }
        }

        if {$vgysolv=="0"} {
            if { [file exists input_vgy.dat]==0 } {
                global No_input_vgy_file
                tk_messageBox -type ok -message $No_input_vgy_file \
                              -icon error
                return
            }
        }

        if {$vgzsolv=="0"} {
            if { [file exists input_vgz.dat]==0 } {
                global No_input_vgz_file
                tk_messageBox -type ok -message $No_input_vgz_file \
                              -icon error
                return
            }
        }

        if {$ome1solv=="0"} {
            if { [file exists input_ome1.dat]==0 } {
                global No_input_ome1_file
                tk_messageBox -type ok -message $No_input_ome1_file \
                              -icon error
                return
            }
        }

        if {$ome2solv=="0"} {
            if { [file exists input_ome2.dat]==0 } {
                global No_input_ome2_file
                tk_messageBox -type ok -message $No_input_ome2_file \
                              -icon error
                return
            }
        }

        if {$ome3solv=="0"} {
            if { [file exists input_ome3.dat]==0 } {
                global No_input_ome3_file
                tk_messageBox -type ok -message $No_input_ome3_file \
                              -icon error
                return
            }
        }

        if {[file exists Output_data]==1} {
            set ls [glob -nocomplain Output_data/*] 
            if {$ls!=""} {
                eval file delete -force $ls
            }
        } else {
            file mkdir Output_data
        }

        # Delete old AnyBody folder, mkdir and copy for AnyBody
        global flagoutm
        if {$flagoutm!="0"} {
            PrepareAnyBody
        }

        # Finally, execute anaylsis engine
        SetEngineExe
        global sourcedir EngineExeFile EngineExeCommand
        file copy -force $sourcedir/Engine/$EngineExeFile [pwd]
        if {$opt_flag=="1"} {
            simplex_init
        } else {
            eval $EngineExeCommand
        }
    }
}


# Correct analysis_settings.dat if fluid force coefficients are
# in old format
proc CorrectAnalysisSettings {} {
    set f [open analysis_settings.dat r+]
    set chars [read $f]

    # if new format, do nothing and return
    if {[string first cn_list $chars]!="-1"} {
        return 
    } 

    # if old format, correct data file

    # first, get each value
    set s [string first "cn=" $chars]
    set cn \
       [string trim [lindex [string range $chars [expr $s+3] end] 0]]
 
    set s [string first "ct=" $chars]
    set ct \
       [string trim [lindex [string range $chars [expr $s+3] end] 0]]
 
    set s [string first "ca=" $chars]
    set ca \
       [string trim [lindex [string range $chars [expr $s+3] end] 0]]
 
    # append list lines
    fconfigure $f -translation lf
    puts $f "cn_list="
    for {set i 1} {$i<=21} {incr i} {
    puts $f " $cn"
    }
    puts $f ""

    puts $f "ct_list="
    for {set i 1} {$i<=21} {incr i} {
    puts $f " $ct"
    }
    puts $f ""

    puts $f "ca_list="
    for {set i 1} {$i<=21} {incr i} {
    puts $f " $ca"
    }
    puts $f ""

    close $f
}


# Correct analysis_settings.dat if motsolv are not found
proc CorrectAnalysisSettings2 {} {
    set f [open analysis_settings.dat r+]
    set chars [read $f]

    # if new format, do nothing and return
    if {[string first motsolv $chars]!="-1"} {
        return 
    } 

    # if old format, correct data file

    # append lines
    fconfigure $f -translation lf
    global comsolv vgxsolv vgysolv vgzsolv ome1solv ome2solv ome3solv
    set comsolv 1
    set vgxsolv 1
    set vgysolv 1
    set vgzsolv 1
    set ome1solv 1
    set ome2solv 1
    set ome3solv 1
    puts $f "motsolv="
    puts $f " $comsolv"
    puts $f " $vgxsolv"
    puts $f " $vgysolv"
    puts $f " $vgzsolv"
    puts $f " $ome1solv"
    puts $f " $ome2solv"
    puts $f " $ome3solv\n"
    close $f
}


# Correct analysis_settings.dat if flagpene are not found
proc CorrectAnalysisSettings3 {} {
    set f [open analysis_settings.dat r+]
    set chars [read $f]

    # if new format, do nothing and return
    if {[string first flagpene $chars]!="-1"} {
        return 
    } 

    # if old format, correct data file

    # append lines
    fconfigure $f -translation lf
    global flagpene
    set flagpene(0) 0
    set flagpene(1) 0
    set flagpene(2) 0
    set flagpene(3) 0
    set flagpene(4) 0
    set flagpene(5) 0
    set flagpene(6) 0
    set flagpene(7) 0
    set flagpene(8) 0
    set flagpene(9) 0
    set flagpene(10) 0
    puts $f "flagpene="
    puts $f " 0"
    puts $f " 0"
    puts $f " 0"
    puts $f " 0"
    puts $f " 0"
    puts $f " 0"
    puts $f " 0"
    puts $f " 0"
    puts $f " 0"
    puts $f " 0"
    puts $f " 0\n"
    close $f
}


# Correct analysis_settings.dat if AnyBody settings are not found
proc CorrectAnalysisSettings4 {} {
    set f [open analysis_settings.dat r+]
    set chars [read $f]

    # if new format, do nothing and return
    if {[string first flagoutm $chars]!="-1"} {
        return 
    } 

    # if old format, append lines
    fconfigure $f -translation lf
    global flagoutm
    set flagoutm "0"
    puts $f "flagoutm="
    puts $f " $flagoutm\n"
    close $f
}

# Correct analysis_settings.dat if "numb" settings are not found
proc CorrectAnalysisSettings5 {} {
    set f [open analysis_settings.dat r+]
    set chars [read $f]

    # if new format, do nothing and return
    if {[string first numb $chars]!="-1"} {
        return 
    } 

    # if old format, append lines
    fconfigure $f -translation lf
    global numb
    set numb "21"
    puts $f "numb="
    puts $f " $numb\n"
    close $f
}

# Correct analysis_settings.dat if "conam" settings are not found
proc CorrectAnalysisSettings6 {} {
    set f [open analysis_settings.dat r+]
    set chars [read $f]

    # if new format, do nothing and return
    if {[string first conam $chars]!="-1"} {
        return 
    } 

    # if old format, append lines
    fconfigure $f -translation lf
    global conam
    set conam "0"
    puts $f "conam="
    puts $f " $conam\n"
    close $f
}

# Correct analysis_settings.dat if "multi" settings are not found
proc CorrectAnalysisSettings7 {} {
    set f [open analysis_settings.dat r+]
    set chars [read $f]

    # if new format, do nothing and return
    if {[string first multi $chars]!="-1"} {
        return 
    } 

    # if old format, append lines
    fconfigure $f -translation lf
    global multi
    set multi "0"
    puts $f "multi="
    puts $f " $multi\n"
    close $f
}

# Correct analysis_settings.dat if "pcn" settings are not found
proc CorrectAnalysisSettings8 {} {
    set f [open analysis_settings.dat r+]
    set chars [read $f]

    # if new format, do nothing and return
    if {[string first pcn $chars]!="-1"} {
        return 
    } 

    # if old format, append lines
    fconfigure $f -translation lf
    global pcn
    set pcn "1.0"
    puts $f "pcn="
    puts $f " $pcn\n"
    close $f
}

proc PrepareAnyBody { } {
    global sourcedir
    # If old folder exists, delete it
    file delete -force AnyBody

    # mkdir
    file mkdir AnyBody
    file mkdir AnyBody/BodyGeometry
    file mkdir AnyBody/JointMotion
    file mkdir AnyBody/BodyMovement
    file mkdir AnyBody/FluidForce

    # copy all files under sourcedir/AnyBody folder into 
    # the project_folder/AnyBody folder
    set a [glob -nocomplain $sourcedir/AnyBody/* ]
    foreach i $a {
        file copy -force $i AnyBody
    }

    # make Main.any file
    set f [open AnyBody/Main.any w]
    global main1_any main2_any main3_any main4_any
    # replace slash into backslash for anybody_brep_folder
    global anybody_brep_folder
    set replaced_brep $anybody_brep_folder
    while {[string first / $replaced_brep ]!="-1"} {
        set i [string first / $replaced_brep ]
        set replaced_brep \
               [string replace $replaced_brep $i $i "\\" ]
    }
    puts $f $main1_any
    puts $f "      //#include \"$replaced_brep\\BodyModels\\FullBodyModel\\BodyModel_NoMuscles.any\"\n"
    puts $f "      //This model uses the simple constant force muscles"
    puts $f "      #include \"$replaced_brep\\BodyModels\\FullBodyModel\\BodyModel.any\"\n"
    puts $f $main2_any
    global anybody_body_geometry
    if {$anybody_body_geometry=="0"} {
        puts $f "      //Do not scale"
        puts $f "      #include \"$replaced_brep\\Scaling\\ScalingStandard.any\""
        puts $f "      //Scale to SWUM"
        puts $f "      //#include \"$replaced_brep\\Scaling\\ScalingLengthMassFat.any\""
        puts $f "      //Scaling=\{"
        puts $f "      //    #include \"SWUMBodyGeometry.any\""
        puts $f "      //\};"
        puts $f "    \};\n"
    } else {
        puts $f "      //Do not scale"
        puts $f "      //#include \"$replaced_brep\\Scaling\\ScalingStandard.any\""
        puts $f "      //Scale to SWUM"
        puts $f "      #include \"$replaced_brep\\Scaling\\ScalingLengthMassFat.any\""
        puts $f "      Scaling=\{"
        puts $f "          #include \"SWUMBodyGeometry.any\""
        puts $f "      \};"
        puts $f "    \};\n"
    }
    puts $f $main3_any
    global cycle anybody_time_step
    puts $f "    tEnd = $cycle;"
    puts $f "    nStep = $anybody_time_step;"
    puts $f $main4_any
    puts $f "  #include \"$replaced_brep\\BodyModels\\FullBodyModel\\CalibrationSequence.any\""
    puts $f "  */"
    puts $f "\}; //Main\n"

    close $f

}


# Set calculation engine execute
proc SetEngineExe {} {
    global OS Engine_OS sourcedir multi
    global EngineExeFile EngineExeCommand EngineExeCommand2
    global WatcherExeFile

    if {$Engine_OS=="Linux"} {
        set EngineExeFile SWUM_ENGINE_LINUX
    } elseif {$Engine_OS=="Darwin"} {
        set EngineExeFile SWUM_ENGINE_MAC
    } else {
        set EngineExeFile SWUM_ENGINE_WINDOWS.EXE
    }

    if {$multi=="0"} {
        if {$OS=="Linux"} {
          set EngineExeCommand "exec xterm -title \"Swumsuit: Analysis\" -e ./$EngineExeFile &"
        } elseif {$OS=="Darwin"} {
          set EngineExeCommand "exec xterm -title \"Swumsuit: Analysis\" -e ./$EngineExeFile &"
        } else {
          set EngineExeCommand  "exec cmd.exe /c $EngineExeFile &"
        }
        set EngineExeCommand2 "exec $EngineExeFile &"

    } else {
      set EngineExeCommand  EngineExeCommandMulti
      set EngineExeCommand2 EngineExeCommandMulti
      if {$OS=="Linux"} {
        set WatcherExeFile SWUM_WATCHER_LINUX
      } elseif {$OS=="Darwin"} {
        set WatcherExeFile SWUM_WATCHER_MAC
      } else {
        set WatcherExeFile SWUM_WATCHER_WINDOWS.EXE
      }
    }
}


# EngineExeCommand for Multi-project mode
proc EngineExeCommandMulti {} {
    global OS EngineExeFile num_subprojects silent_flag sourcedir
    global flagouta
    global WatcherExeFile

    # Overwrite go.dat & go2.dat as "1"
    #  main project
    if {[file exists ./go.dat]==1} {
        catch { file delete -force ./go.dat }
    }
    if {[file exists ./go2.dat]==1} {
        catch { file delete -force ./go2.dat }
    }
    set f [open ./go.dat w]
    puts $f "1 0 0 0"
    close $f
    set f [open ./go2.dat w]
    puts $f "1"
    close $f
    #  sub project(s)
    if {$num_subprojects>=1} {
      for {set i 1} {$i<=$num_subprojects} {incr i} {
        if {[file exists ../sub$i/go.dat]==1} {
            catch { file delete -force ../sub$i/go.dat }
        }
        if {[file exists ../sub$i/go2.dat]==1} {
            catch { file delete -force ../sub$i/go2.dat }
        }
        set f [open ../sub$i/go.dat w]
        puts $f "1 0 0 0"
        close $f
        set f [open ../sub$i/go2.dat w]
        puts $f "1"
        close $f
      }
    }
    update
    after 500

    # Start main project
    if {$silent_flag=="0"} {
        if {$OS=="Linux"} {
            set TmpCommand "exec xterm -title \"Swumsuit: main\" -e ./$EngineExeFile &"
            eval $TmpCommand
        } elseif {$OS=="Darwin"} {
            set TmpCommand "exec xterm -title \"Swumsuit: main\" -e ./$EngineExeFile &"
            eval $TmpCommand
        } else {
            exec cmd.exe /c $EngineExeFile main &
        }
    } else {
        exec ./$EngineExeFile &
    }

    # Start sub project
    if {$num_subprojects>=1} {
        for {set i 1} {$i<=$num_subprojects} {incr i} {
            file copy -force $sourcedir/Engine/$EngineExeFile ../sub$i
            if {$silent_flag=="0"} {
                if {$OS=="Linux"} {
                    set TmpCommand "exec xterm -title \"Swumsuit: sub$i \" -e sh -c \"cd ../sub$i ; ./$EngineExeFile \" & "
                    eval ${TmpCommand}
                } elseif {$OS=="Darwin"} {
                    set TmpCommand "exec xterm -title \"Swumsuit: sub$i \" -e \"cd ../sub$i ; ./$EngineExeFile \" & "
                    eval ${TmpCommand}
                } else {
                    exec cmd.exe /c cd ..\\sub$i & $EngineExeFile sub$i &
                }
            } else {
                exec ../sub$i/$EngineExeFile &
            }
        }
    }
    update

    # Wait for startup of analysis engine(s)
    after 7000

    # Start watching program
    file copy -force $sourcedir/$WatcherExeFile [pwd]
    if {$OS=="Linux"} {
      global WatcherExeCommand
      set WatcherExeCommand "exec xterm -title \"Swumsuit: Watcher\" -e ./$WatcherExeFile"
      after 500 { eval $WatcherExeCommand }
    } elseif {$OS=="Darwin"} {
      global WatcherExeCommand
      set WatcherExeCommand "exec xterm -title \"Swumsuit: Watcher\" -e ./$WatcherExeFile"
      after 500 { eval $WatcherExeCommand }
    } else {
      after 500 { exec cmd.exe /c $WatcherExeFile }
    }
}


# Delete exe file (if exists)
proc DeleteExeFile {} {
    global sourcedir
    set pwd [pwd]
    if {"$pwd"=="$sourcedir/Engine"} { return }
    catch { eval file delete -force [glob SWUM_ENGINE* ] }
}

# Manual message
proc ManualMessage {} {
    global Manual_message
    tk_messageBox -type ok -icon info -message $Manual_message
}


# Invoke "about"
proc InvokeAbout {} {
    global swum_version
    tk_messageBox -type ok -icon info -message "Swumsuit - SWimming hUman Model with Synthetic User Interface Tools\n\nVersion $swum_version"
}


# Joint motion editor
proc EditJointMotionExecute { } {
    global dname sourcedir WISHRUN Locale
    cd $sourcedir
    exec $WISHRUN $sourcedir/edit_joint_motion.tcl $sourcedir $dname $Locale &
    cd $dname
}


# Body geometry editor
proc EditBodyGeometryExecute { } {
    global dname sourcedir WISHRUN Locale
    cd $sourcedir
    exec $WISHRUN $sourcedir/edit_body_geometry.tcl $sourcedir $dname $Locale &
    cd $dname
}


# Animate motion
proc AnimateStart { } {
    DeleteExeFile
    global dname sourcedir WISHRUN Locale multi num_subprojects
    cd $sourcedir
    exec $WISHRUN $sourcedir/animate_motion.tcl $sourcedir $dname $Locale $multi $num_subprojects &
    cd $dname
}



# Change icon
proc ChangeIcon { w } {
    global Platform sourcedir
    if {$Platform=="windows"} {
        update
        wm iconbitmap $w $sourcedir/icon_small.ico
    }
}


# View comment
proc ViewComment { } {
    global dname
    if {[winfo exists .vc ]==0} {
        toplevel .vc
	wm title .vc "Swumsuit: Comment"

        global Project_folder
        labelframe .vc.e -text $Project_folder -padx 3 -pady 3
        #label .vc.e.l -text "${Project_folder}: " 
        entry .vc.e.e -width 80 -state readonly -textvariable dname
        pack  .vc.e.e -fill x

        global Comment
        labelframe .vc.c -text $Comment -padx 3 -pady 3
        text .vc.c.c -width 80 -height 24
        pack .vc.c.c

        frame .vc.p
        global Save Cancel
        button .vc.p.save   -text $Save   -command SaveComment
        button .vc.p.cancel -text $Cancel -command "wm withdraw .vc"
        pack   .vc.p.save .vc.p.cancel -side left -expand 1

        pack .vc.e .vc.c -side top -pady 5
        pack .vc.p -side top -pady 10 -fill x

        ChangeIcon .vc

    } else {
        wm deiconify .vc
    }

    # Load comment
    LoadComment
}


# Load comment
proc LoadComment { } {
    global Locale
    if {[file exists comment.dat]==1} {
        .vc.c.c delete 1.0 end 
        set f [open comment.dat r]
        if {$Locale=="ja_jp"} {
            fconfigure $f -translation crlf -encoding shiftjis
        } else {
            fconfigure $f -translation crlf
        }
        while {[gets $f line]!="-1"} {
            .vc.c.c insert end $line\n
        }
        close $f
        .vc.c.c delete end-1char end
    }
}


# Save comment
proc SaveComment { } {
    global Locale
    set f [open comment.dat w]
    if {$Locale=="ja_jp"} {
        fconfigure $f -translation crlf -encoding shiftjis
    } else {
        fconfigure $f -translation crlf
    }
    puts $f [string trimright [.vc.c.c get 1.0 end]]
    close $f
    wm withdraw .vc
}


# Invoke preferences
proc InvokePreferences { } {
    if {[winfo exists .ip]==0} {
        # open window
        toplevel .ip
        wm title .ip "Swumsuit: Preferences"

        # message
        global You_have_to_restart
        label .ip.m -text $You_have_to_restart

        # Engine_OS
        global Analysis_Engine_OS Auto_Detect
        global Engine_OS_tmp Engine_OS_Detect_tmp
        frame .ip.e -bd 2 -relief groove
        label .ip.e.t -text $Analysis_Engine_OS -anchor w
        checkbutton .ip.e.c -text $Auto_Detect \
                          -variable Engine_OS_Detect_tmp
        bind .ip.e.c <ButtonPress-1> EngineOSDetectToggle
        radiobutton .ip.e.w -text Windows \
                          -variable Engine_OS_tmp -value "Windows NT"
        radiobutton .ip.e.l -text Linux \
                          -variable Engine_OS_tmp -value "Linux"
        radiobutton .ip.e.m -text Mac \
                          -variable Engine_OS_tmp -value "Darwin"
        pack .ip.e.t -side left
        pack .ip.e.m .ip.e.l .ip.e.w .ip.e.c -side right

        # Length of history
        global Number_of_lines_for_project_folders_history
        frame .ip.h -bd 2 -relief groove
        label .ip.h.t -text $Number_of_lines_for_project_folders_history -anchor w
        entry .ip.h.e -width 20 \
                      -textvariable history_length_tmp
        pack  .ip.h.t -side left 
        pack  .ip.h.e -side right -padx 3

        # For AnyBody
        global Musculo_Skeletal_Analysis \
               AnyBody_Execute_File \
               AnyBody_Brep_Folder Choose
        frame  .ip.a -bd 2 -relief groove
        label  .ip.a.t0 -text $Musculo_Skeletal_Analysis -anchor w
        frame  .ip.a.f1 
        frame  .ip.a.f2 
        label  .ip.a.f1.t -text $AnyBody_Execute_File -anchor w
        entry  .ip.a.f1.e -width 34 \
                          -textvariable anybody_exe_file_tmp
        button .ip.a.f1.b -text $Choose -command ChooseAnyBodyExe
        label  .ip.a.f2.t -text $AnyBody_Brep_Folder -anchor w
        entry  .ip.a.f2.e -width 34 \
                          -textvariable anybody_brep_folder_tmp
        button .ip.a.f2.b -text $Choose -command ChooseAnyBodyBrep

        pack  .ip.a.f1.t -side left 
        pack  .ip.a.f1.b -side right -padx 3
        pack  .ip.a.f1.e -side right -padx 3
        pack  .ip.a.f2.t -side left 
        pack  .ip.a.f2.b -side right -padx 3
        pack  .ip.a.f2.e -side right -padx 3
        pack  .ip.a.t0 \
              .ip.a.f1 \
              .ip.a.f2  -side top -anchor w -fill x

        # panel
        frame .ip.p
        global OK Cancel
        button .ip.p.ok     -text $OK \
             -command "SavePreferences ; wm withdraw .ip"
        button .ip.p.cancel -text $Cancel \
             -command "wm withdraw .ip"
        pack   .ip.p.ok     \
               .ip.p.cancel \
                 -side left -padx 5

        # packing
        pack .ip.e -side top -anchor w -fill x
        pack .ip.h -side top -anchor w -fill x
        pack .ip.a -side top -anchor w -fill x
        pack .ip.m -side top -pady 5
        pack .ip.p -side top -pady 5

        ChangeIcon .ip

    } else {
        wm deiconify .ip
    }

    # load preferences
    LoadPreferences
}


# Choose AnyBody exe file
proc ChooseAnyBodyExe { } {
     global anybody_exe_file_tmp
     set anybody_exe_file_tmp_old $anybody_exe_file_tmp
     set anybody_exe_file_tmp \
          [tk_getOpenFile -initialfile $anybody_exe_file_tmp_old \
              -filetypes { {"Execute file" {.exe}} {"All files" *} } ]
     # if the file name is emtpy, recover it
     if {$anybody_exe_file_tmp==""} {
         set anybody_exe_file_tmp $anybody_exe_file_tmp_old
     }
}


# Choose AnyBody Brep folder
proc ChooseAnyBodyBrep { } {
     global anybody_brep_folder_tmp
     set anybody_brep_folder_tmp_old $anybody_brep_folder_tmp
     set anybody_brep_folder_tmp \
          [tk_chooseDirectory -initialdir $anybody_brep_folder_tmp_old ]
     # if the floder name is emtpy, recover it
     if {$anybody_brep_folder_tmp==""} {
         set anybody_brep_folder_tmp $anybody_brep_folder_tmp_old
     }
}


# Load preferences
proc LoadPreferences { } {
    global Engine_OS Engine_OS_tmp
    global Engine_OS_Detect Engine_OS_Detect_tmp
    global anybody_exe_file anybody_exe_file_tmp
    global anybody_brep_folder anybody_brep_folder_tmp
    global history_length history_length_tmp

    set Engine_OS_tmp $Engine_OS
    set Engine_OS_Detect_tmp $Engine_OS_Detect
    set anybody_exe_file_tmp $anybody_exe_file
    set anybody_brep_folder_tmp $anybody_brep_folder
    set history_length_tmp $history_length

    if {$Engine_OS_Detect==1} {
        .ip.e.w configure -state disabled
        .ip.e.l configure -state disabled
        .ip.e.m configure -state disabled
    } else {
        .ip.e.w configure -state normal
        .ip.e.l configure -state normal
        .ip.e.m configure -state normal
    }
}


# Save preferences
proc SavePreferences { } {
    global Engine_OS Engine_OS_tmp
    global Engine_OS_Detect Engine_OS_Detect_tmp
    global anybody_exe_file anybody_exe_file_tmp
    global anybody_brep_folder anybody_brep_folder_tmp
    global history_length history_length_tmp

    # substitute temporary values
    set Engine_OS $Engine_OS_tmp
    set Engine_OS_Detect $Engine_OS_Detect_tmp
    set anybody_exe_file $anybody_exe_file_tmp
    set anybody_brep_folder $anybody_brep_folder_tmp
    set history_length $history_length_tmp
    
    # save to file
    global env Swumsuit_prefs
    set f [open $env(HOME)/$Swumsuit_prefs w]
    puts $f "# Swumsuit preferences \n#\n# This file is created automatically. do not edit!\n"
    if {$Engine_OS_Detect==0} {
        puts $f "set Engine_OS_Detect \"$Engine_OS_Detect\""
        puts $f "set Engine_OS \"$Engine_OS\""
    }
    puts $f "set anybody_exe_file \"$anybody_exe_file\""
    puts $f "set anybody_brep_folder \"$anybody_brep_folder\""
    puts $f "set history_length \"$history_length\""
    close $f
}


proc EngineOSDetectToggle { } {
    global Engine_OS_Detect_tmp
    if {$Engine_OS_Detect_tmp==1} {
        # no auto detect
        .ip.e.w configure -state normal
        .ip.e.l configure -state normal
        .ip.e.m configure -state normal
    } else {
        # auto detect
        global Engine_OS_tmp tcl_platform
        set Engine_OS_tmp $tcl_platform(os)
        .ip.e.w configure -state disabled
        .ip.e.l configure -state disabled
        .ip.e.m configure -state disabled
    }
}


# Replace Input Data for Optimization
proc ReplaceInputData { file line column replace } {
    # load
    set f [open $file r]
    set eoff 0
    set j 1
    while {$eoff!="1"} {
        set fline($j) [gets $f]
        set eoff [eof $f]
        incr j
    }
    close $f
    # replace corresponding column in the corresponding line
    set fline($line) \
     [lreplace $fline($line) [expr $column-1] [expr $column-1] $replace]
    # write all lines 
    set f [open $file w]
    for {set i 1} {$i<=[expr $j-2]} {incr i} {
        puts $f $fline($i)
    }
    close $f
}


# Get Output Data for Optimization
proc GetOutputData { file line column } {
    set f [open Output_data/$file r]
    for {set j 1} {$j<=$line} {incr j} {
        set fline [gets $f]
    }
    close $f
    set y [lindex $fline [expr $column-1] ]
    return $y
}

# Invoke AnyBody
proc InvokeAnyBody { } {
    global anybody_exe_file
    global AnyBody_main_file_does_not_exist
    if {[file exists AnyBody/Main.any]=="1"} {
        exec $anybody_exe_file [pwd]/AnyBody/Main.any &
    } else {
        tk_messageBox -message $AnyBody_main_file_does_not_exist
    }
}

#########################################################
# Start script
#########################################################

# Set source directory
set sourcedir [file dirname [info script]]
cd $sourcedir
set sourcedir [pwd]

# Set locale
set Locale [lindex $argv 0]

# Window title bar
wm title . "Swumsuit: [pwd]"

# Global initializing
set swum_version "5.1.0"
set dname [pwd]

# Set default values for AnyBody
set anybody_exe_file "C:/Program Files/AnyBody Technology/AnyBody.2.0/AnyBody.exe"
set anybody_brep_folder ""

# Set default value for the length of history
set history_length 20

# Set environment
source set_environment.tcl
# Load message catalog according to locale
source load_catalog.tcl
# Set default font
source set_default_font.tcl

# Select wish
if {$tcl_platform(platform)=="unix"} {
    #set WISHRUN "$sourcedir/wish_linux"
    set WISHRUN "wish"
} else {
    set WISHRUN "$sourcedir/wish_windows.exe"
}


# Load joint motion editor
#set EditJointMotionExecute {cd $sourcedir ; exec $sourcedir/$WISHRUN $sourcedir/edit_joint_motion.tcl $sourcedir $pwd $Locale &}

# Load body geometry editor
#set EditBodyGeometryExecute {cd $sourcedir ; exec $sourcedir/$WISHRUN $sourcedir/edit_body_geometry.tcl $sourcedir $pwd $Locale &}

# Load analysis setting editor
source edit_analysis_settings.tcl

# Load animate motion window
#source animate_motion.tcl

# Load draw graph 
source draw_graph.tcl

# Load optimizatin
source opt_simplex.tcl

# Set calculation engine execute file
# SetEngineExe

# Set variables for AnyBody Main.any file
source anybody_main.tcl

# Start setup
MainSetup

# Load local script
catch { source ../local.tcl }

# Set initial values for optimization
set opt_flag 0
set num_dp ""
set size_simplex ""

# Set initial values for penetration judging
set flagpene(0) 0
set flagpene(1) 0
set flagpene(2) 0
set flagpene(3) 0
set flagpene(4) 0
set flagpene(5) 0
set flagpene(6) 0
set flagpene(7) 0
set flagpene(8) 0
set flagpene(9) 0
set flagpene(10) 0

# Set default values of number of subprojects
set num_subprojects 0
