#***********************************************************************
#
#       ELMER, A Computational Fluid Dynamics Program.
#
#       Copyright 1st April 1995 - , Center for Scientific Computing,
#                                    Finland.
#
#       All rights reserved. No part of this program may be used,
#       reproduced or transmitted in any form or by any means
#       without the written permission of CSC.
#
#                Address: Center for Scientific Computing
#                         Tietotie 6, P.O. BOX 405
#                         02101 Espoo, Finland
#                         Tel.     +358 0 457 2001
#                         Telefax: +358 0 457 2302
#                         EMail:   Jari.Jarvinen@csc.fi
#***********************************************************************

#***********************************************************************
#Program:   ELMER Front 
#Module:    ecif_tcl_mainScript.tcl
#Language:  Tcl
#Date:      19.10.98
#Version:   1.00
#Author(s): Martti Verho
#Revisions: 
#
#Abstract:  Starting script for the user interface (Tk)
#
#************************************************************************


# Set current version number
# ==========================
#
proc setFrontVersionNumber {} {
  global Info

  # NOTE: Version main-number is meant for major changes in Front input format etc.
  #       It is set in ECIF_CONST.CPP
  #
  # NOTE: Version sub-number is meant for minor changes and bug fixes
  #       It is set HERE!
  #
  # NOTE: Current version sub-number is for main version nbr 9
  #       Reset sub-number (--> .0) whenever the main version changes
  #

  # Set current sub-number
  # ----------------------
  #

  # *******************************
  # This number must match the main
  # version number set in cpp-side.
  # Normally, do NOT change this!!!
  # *******************************
  #
  set main_nbr_txt "9"

  # ***************************************************************************
  # ***************************************************************************
  # Update this for 'minor' changes !!!
  # ***************************************************************************
  # ***************************************************************************
  #
  # Last change: (.0  --> .0a), 12.06.03, MVe
  # Last change: (.0a --> .1a), 21.10.03, MVe
  # Last change: (.1a --> .2a), 10.03.04, MVe
  # Last change: (.2a --> .3a), 02.06.04, MVe; Boundary selection bug fix
  # Last change: (.3a --> .3b), 02.07.04, MVe; ELMER_FRONT_FONT_SIZE env added
  #
  set sub_nbr_txt ".3b" 


  #
  # ----------------------

  if { $Info(FRONT_MAIN_VERSION_NBR) == $main_nbr_txt } {
    set Info(FRONT_SUB_VERSION_NBR) $sub_nbr_txt
  } else {
    set Info(FRONT_SUB_VERSION_NBR) ""
  }

  set Info(FRONT_VERSION_NBR) $Info(FRONT_MAIN_VERSION_NBR)$Info(FRONT_SUB_VERSION_NBR)
}

############################
### Front initialization ###
############################

# Message box proc
# NOTE: This can be called anywhere, no
# loaded source needed!
#
proc my_box { {msg ""} } {
  tk_messageBox -message $msg
}  

# Globals
global Info Model ModelProperty UserSetting


# CAREFULLY, these are for debugging !!!###!!!
# Debug: 0
# Release: 1
#
set Info(SAVE_PANEL_DATA) 1
set Info(DO_CATCH) 1

proc my_catch {block messu} {
  global Info
  upvar $messu msg

  if { $Info(DO_CATCH) } {
    return [catch {$block} msg]
  } else {
    eval $block
    return 0
  }
}

set Info(commandLineArgs) ""
set Info(commandLineInfo) ""

set Info(wrnMsgColor) red
set Info(errMsgColor) red
set Info(remMsgColor) brown
  

##################################
# Main proc to start Elmer Front #
##################################

proc startGUI {} {
  global Info Model ModelProperty

  set Info(userSettingFiles) ""
  set Info(userSettingFilesReadInfo) ""
  set Info(userSettingFilesErrorInfo) ""
  
  set Model(defaultDefinitionFiles) ""
  set Model(defaultDefinitions) ""
  set Model(inDefinitionFile) ""

  #-Init environment variables
  initEnvironment

  # Check possible default setting files
  # ======================================= 
  checkDefaultSettingFiles

  # Check possible default definition files
  # ======================================= 
  checkDefaultDefinitionFiles

  # Check command line arguments
  # ============================
  handleCommandLineArgs 1

  # Read possible setting files (via cpp)
  # ===========================
  if { $Info(userSettingFiles) != "" } {
    cpp_readUserSettingFiles
  }

  # Call start procs
  # ================
  #-Init screen parameters
  initScreen

  #-Load tcl source files
  loadSource
  
  #-Set complete (main+sub) version number
  #
  setFrontVersionNumber

  #-Start (init glob arries, build menus)
  startFront
}


proc setElmerFrontPaths {} {
    global Info env

    set Info(ELMER_FRONT_INSTALL_LIB) "/wrk/jpr/share/elmerfront/lib"
    set Info(ELMER_FRONT_INSTALL_TCL) "/wrk/jpr/share/elmerfront/tcl"

    if { [info exists env(ELMER_HOME)] } {
      set Info(ELMER_FRONT_INSTALL_LIB) "$env(ELMER_HOME)/share/elmerfront/lib"
      set Info(ELMER_FRONT_INSTALL_TCL) "$env(ELMER_HOME)/share/elmerfront/tcl"
    }

    if { [info exists env(ELMER_FRONT_HOME)] } {
      set Info(ELMER_FRONT_INSTALL_LIB) "$env(ELMER_FRONT_HOME)/lib"
      set Info(ELMER_FRONT_INSTALL_TCL) "$env(ELMER_FRONT_HOME)/tcl"
    }


    set Info(ELMER_FRONT_BUILD_LIB) "./lib"
    set Info(ELMER_FRONT_BUILD_TCL) "./tcl"
}


##################### 
# Set platform info #
#####################

proc initEnvironment {} {
  global Info
  global env tcl_platform
  global tcl_version tcl_patchLevel tcl_library
  global tk_version tk_patchLevel tk_library

  #---Program name and version
  set Info(PROJECT) "ELMER"
  set Info(MODULE) "Front"
  set Info(FRONT_NAME) "ELMER Front"
  set Info(VERSION) ""

  #---Machine info info
  set Info(PID) [pid]
  set Info(machine) $tcl_platform(machine)
  set Info(os) $tcl_platform(os)
  set Info(osVersion) $tcl_platform(osVersion)
  set Info(platform) $tcl_platform(platform)

  #---Windows platform and OS names used in Tcl
  set Info(platform,Windows) "windows"
  set Info(os,WindowsNT) "Windows NT"
  set Info(os,Windows95) "Windows 95"
  set Info(os,Windows98) "Windows 98"   ;# This is a guess!
  set Info(os,Windows2K) "Windows NT" 

  #---Tcl version info
  set Info(tclVersion) $tcl_version
  set Info(tclLevel)  $tcl_patchLevel
  set Info(tclLibraryPath) $tcl_library

  set Info(tkVersion) $tk_version
  set Info(tkLevel)  $tk_patchLevel
  set Info(tkLibraryPath) $tk_library

  #---Win32:
  #-Uses dde for "send"
  #-File names not case sensitive
  if { $Info(platform) == "windows" } {
    
    set Info(FNCS) 0

    if { [catch {package require dde 1.0} msg] } {
      tk_messageBox -message $msg
    }

  #---Unix
  #-File names are case sensitive
  } else {
    set Info(FNCS) 1
  }

  # Buttons: press enter <==> pressing space key
  bind Button <KeyPress-Return> "+event generate %W <KeyPress-space>"
  event add <<MenuPick>> <Button-1>


  # Set working directory
  # =====================
  set Info(workingDirectory) [pwd] ;# This is the PWD when it is needed
  set Info(currentDirectory) [pwd] ;# This is for "debugging" (monitoring)

  puts "Setting up paths"
  setElmerFrontPaths

  # Init script-path if not defined
  if { 0 == [info exists Info(frontScriptPath)] } {
    set Info(frontScriptPath) ""
  }

  # Make scriptpath absolute
  if { "relative" == [file pathtype $Info(frontScriptPath)] } {
    set tmp [file split $Info(frontScriptPath)]
    set tmp [lrange $tmp 1 end]
    set Info(frontScriptPath) [file join $Info(workingDirectory) $tmp]
  }

  # All needed images are here
  set Info(imagePath) [file join $Info(frontScriptPath) "images"]


  # ElmerHome
  # =========
  # This is the parent path for /bin etc.

  if { [info exists env(ELMER_HOME)] } {
    set Info(ELMER_HOME) $env(ELMER_HOME)

    if { ![file isdirectory $Info(ELMER_HOME)] } {
      set Info(ELMER_HOME) "."
    }

  } else {
    set Info(ELMER_HOME) "."
  }


  # ElmerUserHome
  # =============
  # This is one of the paths for color tables, matc defs etc.

  if { [info exists env(ELMER_USER_HOME)] } {
    set Info(ELMER_USER_HOME) $env(ELMER_USER_HOME)

    if { ![file isdirectory $Info(ELMER_USER_HOME)] } {
      set Info(ELMER_USER_HOME) ""
    }

  } else {
    set Info(ELMER_USER_HOME) ""
  }


  # Elmer version
  # ==================
  set version_file [file join $Info(ELMER_HOME) lib "version.dat"]
  if { [file exist $version_file] } {
    set msg ""
    if { ![catch {set ch [open $version_file "r"] } msg] } {
      set Info(VERSION) [string trim [gets $ch] ]
    }
  }
   
  # ElmerFrontHome
  # ==============
  if { [info exists env(ELMER_FRONT_HOME)] } {
    set Info(ELMER_FRONT_HOME) $env(ELMER_FRONT_HOME)
  } else {
    set Info(ELMER_FRONT_HOME) "$Info(ELMER_HOME)/Front"
  }

  if { ![file isdirectory $Info(ELMER_FRONT_HOME)] } {
    set Info(ELMER_FRONT_HOME) "."
  }

  # Temporary directory
  # ===========================
  set Info(LOG_DIRECTORY) ""

  # Predefined alternatives in search order!
  #set tmpdir_names { 
  #  ELMER_FRONT_TMP ELMER_FRONT_TEMP
  #  ELMER_TMP ELMER_TEMP
  #  TMPDIR TEMPDIR TMP TEMP
  #}
  set tmpdir_names { 
    ELMER_FRONT_TMP ELMER_FRONT_TEMP
  }

  foreach vn $tmpdir_names {
    if { 1 == [info exists env($vn)] } {
      set Info(LOG_DIRECTORY) $env($vn)
      break
    }
  }

  # User name
  # =========
  set Info(USER) ""

  # Predefined alternatives in search order!
  set user_names {
    ELMER_FRONT_USER ELMER_USER
    USER USERNAME user username
  }

  foreach vn $user_names {
    if {  [info exists env($vn)] } {
      set Info(USER) $env($vn)
      break
    }
  }

  # Computer name
  # =============
  set Info(HOST) ""

  # Predefined alternatives in search order!
  set host_names { 
    ELMER_FRONT_HOST ELMER_HOST
    HOST host COMPUTERNAME
  }

  foreach vn $host_names {
    if {  [info exists env($vn)] } {
      set Info(HOST) $env($vn)
      break
    }
  }

  # Elmer Variable values
  # =====================

  # Names and default values
  set defs {
    { ELMER_MODEL_NAME "" }
    { ELMER_MODEL_DIRECTORY "" }
    { ELMER_INCLUDE_PATH "" }
    { ELMER_RESULTS_DIRECTORY "" }
    { ELMER_FRONT_DEFINITIONS "" }
    { ELMER_FRONT_SETTINGS "" }
    { ELMER_FRONT_FONT_SIZE "" }
  }

  # If environment variable defined, use it
  foreach def $defs {

    set vn [lindex $def 0] ;# variable name
    set vv [lindex $def 1] ;# default value

    if { [info exists env($vn)] } {
      set Info($vn) $env($vn)
    } else {
      set Info($vn) $vv
    }
  }

  # These control "special" features!
  # =============================
  set specials { 
    ELMER_FRONT_THETIS_SUPPORT
    ELMER_FRONT_DEBUG_TCL
    ELMER_FRONT_DEBUG_TCL_PRINT
    ELMER_FRONT_DEBUG_TCL_STACK
  }

  # NOTE: These have 0/1 values!
  foreach special $specials {

    if { [info exists env($special)] && 1 == $env($special) } {
      set Info($special) 1
    } else {
      set Info($special) 0
    }
  }
   
} ;# End initEnvironment


###################################
# Check default UserSetting files #
###################################
#
# Collect possible setting file names:
# elmer/lib/elmerFrontSettings.esf
# from env-var ELMER_FRONT_SETTINGS
# to a list for later loading
#
proc checkDefaultSettingFiles {} {
  global Info Model UserSetting

  set evs {ELMER_FRONT_SETTINGS ELMER_USER_HOME}
  set fn "front.esf"

  if { [info exists Info(ELMER_HOME)] &&
       $Info(ELMER_HOME) != ""
     } {

    set path [file join $Info(ELMER_HOME) lib $fn]

    if { [file exist $path] } {
      lappend Info(userSettingFiles) $path
    }

    # NOTE: This is the default file from now on, for saving etc.!
    set UserSetting(filePath) $path

  }

  foreach ev $evs {
    if { [info exists Info($ev)] && $Info($ev) != "" } {
      set path [file join $Info($ev) $fn]
      if { [file exist $path] } {
        lappend Info(userSettingFiles) $path

        # NOTE: This is the default file from now on, for saving etc.!
        set UserSetting(filePath) $path
      }
    }
  }
}


##################################
# Check default definition files #
##################################
#
# Collect possible definition file names:
# elmer/lib/elmerFrontDefinitions.def
# from env-var ELMER_FRONT_DEFINITIONS
# to a list for later loading
#
proc checkDefaultDefinitionFiles {} {
  global Info Model

  set evs {ELMER_FRONT_DEFINITIONS ELMER_USER_HOME ELMER_FRONT_BUILD_LIB ELMER_FRONT_INSTALL_LIB}
  set fn "front.edf"

  if { [info exists Info(ELMER_HOME)] &&
       $Info(ELMER_HOME) != ""
     } {

    set path [file join $Info(ELMER_HOME) lib $fn]

    if { [file exist $path] } {
      lappend Model(defaultDefinitionFiles) $path
    }
  }

  foreach ev $evs {
    if { [info exists Info($ev)] && $Info($ev) != "" } {
      set path [file join $Info($ev) $fn]
      if { [file exist $path] } {
        lappend Model(defaultDefinitionFiles) $path
      }
    }
  }
}



######################
# Create main window #
######################

proc initScreen {} {
  global Info

  # Create main window
  # ==================
  set mainWindow .
  set Info(mainWindow) $mainWindow

  # Main window position from the NW-corner
  wm geometry $mainWindow -20+10

  #---Window killing should send exit also to cpp-side

	# This way ce can catch exit when debugging!!!###!!!
  if { $Info(ELMER_FRONT_DEBUG_TCL) } {
    wm protocol $mainWindow WM_DELETE_WINDOW "MenuExec::cifExit"

	# This always kills Front in user mode!!!###!!!
  } else {
    wm protocol $mainWindow WM_DELETE_WINDOW "cpp_exit"
  }

  #wm protocol $mainWindow WM_TAKE_FOCUS "Util::setMainWindowTitle"

  # Window settings
  # ===============
  # Main window title
  wm title $mainWindow "$Info(PROJECT) $Info(MODULE) - No model name"

  # Just testing, icon for a window does not seem to work in Windows32
  #image create photo FRONT_ICON -file [file join $Info(imagePath) display.gif]
  #image create bitmap FRONT_ICON -file [file join $Info(imagePath) cygnus.ico]
  #wm iconbitmap $mainWindow $FRONT_ICON
  #wm iconbitmap $mainWindow ""
  #wm iconname $mainWindow "Front"

  # Main window max size ( = screen resolution)
  set maxWinSize [wm maxsize $mainWindow]
  set Info(maxWinSizeX) [lindex $maxWinSize 0]
  set Info(maxWinSizeY) [lindex $maxWinSize 1]

} ;# End initScreen

#####################
# Load source files #
#####################

proc loadSource {} {
  global Info

  set ext tcl

  set sourceScripts {
     ecif_tcl_namespaces
     ecif_tk_aboutBox
     ecif_tk_bodyDisplayPanel
     ecif_tk_bodyInfoPanel
     ecif_tk_bodyPropertiesPanel
     ecif_tk_boundariesPanel
     ecif_tk_boundaryDisplayPanel
     ecif_tk_calculatorPanel
     ecif_tk_constantPanel
     ecif_tk_coordinatePanel
     ecif_tk_datafilePanel
     ecif_tk_equationVariablesPanel
     ecif_tk_initGlobalArries
     ecif_tk_initMenus
     ecif_tk_inputFileInfoPanel
     ecif_tk_labelDisplayPanel
     ecif_tk_matcDefinitionsPanel
     ecif_tk_meshDefinePanel
     ecif_tk_meshSelectPanel
     ecif_tk_modelInfoPanel
     ecif_tk_modelParameterPanel
     ecif_tk_modelPropertiesPanel
     ecif_tk_postFileSelectPanel
     ecif_tk_procedureEntryPanel
     ecif_tk_processorPanel
     ecif_tk_processTablePanel
     ecif_tk_procsDataField
     ecif_tk_procsInterface
     ecif_tk_procsList
     ecif_tk_procsListBox
     ecif_tk_procsMenuExec
     ecif_tk_procsMessage
     ecif_tk_procsObject
     ecif_tk_procsPanel
     ecif_tk_procsPanelCheck
     ecif_tk_procsUserDefined
     ecif_tk_procsUtil
     ecif_tk_procsWidget
     ecif_tk_screenParams
     ecif_tk_simulationParameterPanel
     ecif_tk_solverOrderPanel
     ecif_tk_solverParameterPanel
     ecif_tk_solverControlPanel
     ecif_tk_standardPanelCheck
     ecif_tk_standardPanelCreate
     ecif_tk_standardPanelExec
     ecif_tk_standardPanelInit
     ecif_tk_systemInfoPanel
     ecif_tk_tableEntryPanel
     ecif_tk_timestepPanel
     ecif_tk_userSettingsPanel
     ecif_tk_vertexDisplayPanel
     tkgetdir
  }

  # Load source code
  # ================
  
  #--Front own source code
  if { [catch {
          foreach src_name $sourceScripts {
            set src_file [file join $Info(frontScriptPath) $src_name.$ext]
            lappend Info(sourceScripts) [list $src_name $src_file [file mtime $src_file]]
            source $src_file
          } } msg]
     } {
    #set err_msg "Elmer Front ERROR loading Tcl source file:   $src_file  ($errorInfo)"
    set err_msg "Elmer Front ERROR when loading Tcl source file:   $src_file"
    my_box $err_msg
    cpp_exec_ "cpp_exit"
  }

  #--Possible user source code
  set user_src_file [file join $Info(ELMER_HOME) lib "front_user_src.tcl"]

  if { [file exist $user_src_file] } {
    set msg ""
    if { [catch {source $front_user_src} msg] } {
      set err_msg "Elmer Front ERROR when loading user Tcl source file:   $front_user_src"
      my_box $err_msg
      cpp_exec_ "cpp_exit"
    }
  }
  

  # Post process
  # ============

  if { $Info(platform) == "windows" } {
    rename MenuExec::send_WIN32 send
  }

} ;# End loadSource



###############
# Start Front #
###############

proc startFront {} {
  global Info

  #--Call data init proc (in ecif_tk_initGlobalArries.tcl)
  #
  if { [my_catch FRONT_INIT msg] } {
    #set err_msg "Elmer Front ERROR (FRONT_INIT proc): $errorInfo"
    set err_msg "Elmer Front ERROR (FRONT_INIT proc)"
    my_box "$err_msg \n\n$msg"
    cpp_exec_ "cpp_exit"
  }

  #--Call menu init proc (in ecif_tk_initMenus.tcl)
  #
  if { [my_catch INIT_MENUS msg] } {
    #set err_msg "ELMER FRONT ERROR (INIT_MENUS proc): $errorInfo"
    set err_msg "ELMER FRONT ERROR (INIT_MENUS proc)"
    my_box "$err_msg \n\n$msg"
    return
  }

  #--Call post init proc (in ecif_tk_initGLobArries.tcl)
  #
  if { [my_catch FRONT_POST_INIT msg] } {
    #set err_msg "ELMER FRONT ERROR (FRONT_POST_INIT proc): $errorInfo"
    set err_msg "ELMER FRONT ERROR (FRONT_POST_INIT proc)"
    my_box "$err_msg \n\n$msg"
    return
  }

  #--Read possible fields' help file
  
  # Default fields' help file name
  set filename [file join $Info(ELMER_HOME)/lib "front.ehf"]
  
  if { [file exists $filename] } {
    if { [catch {FRONT_READ_FIELD_HELP_FILE $filename 1} msg] } {
      set err_msg "ELMER FRONT ERROR (FRONT_READ_FIELD_HELP_FILE proc)"
      my_box "$err_msg \n\n$msg"
      #return
    }
  }

  #--Show possible init-messages (cmd-line args stuf etc) (in ecif_tk_initGlobalArries.tcl)
  # NOTE: We show these last because then it is easier for the user to see possible
  # error messages
  #
  if { [my_catch FRONT_SHOW_INIT_MESSAGES msg] } {
    set err_msg "ELMER FRONT ERROR (FRONT_SHOW_INIT_MESSAGES proc)"
    my_box "$err_msg \n\n$msg"
    #return
  }

  #Message::showMessage "$Info(FRONT_NAME) started!" blue 1

} ;# End proc startFront



#====================================#
#     handleCommandLineArguments     #
#====================================#
#
# Read possible command line arguments for command ElmerFront
# currently available with example values:
#
# --model-directory=/elmer/MODELS
# --model-name=stepflow
# --include-path=/elmer/Materials;/elmer/Conditions
# --results-directory=c:/temp
# --tmp-directory=c:/temp
# --settings-file=/elmer/ElmerFrontSettings.txt
#
# NOTE: settings-file argument value is called back by cpp-side!
# ===> this proc must be called first by cpp-side
#
# NOTE: these value overwrite UserSettings environment case directory values, but 
# they do NOT overwrite model-file case direcrory values !!!
# Case dirs here are: INCLUDE-PATH, RESULTS-DIRECTORY, LOG-DIRECTORY
#
proc handleCommandLineArgs { {do_msg 0} } {
  global Info Model ModelProperty UserSetting

  set Info(MODEL_DIRECTORY) ""  
  set Info(MODEL_NAME) ""  
  set Info(PROBLEM_NAME) ""  

  set arg_line $Info(commandLineArgs)

  if {$arg_line == ""} {
    return
  }

  set Info(commandLineInfo) $arg_line
  lappend Info(commandLineInfo) ""      

  # This will repalce "--" in the 
  # original argument line
  set sep ";"

  regsub -all (--) $arg_line $sep arg_line1

  set arg_list [split [string trimleft $arg_line1 $sep] $sep]

  foreach arg $arg_list {
    
    set data [split $arg "="]

    #-Inproper argument
    if { 2 != [llength $data] } {
 
      if {$do_msg} {
        lappend Info(commandLineInfo) [list $data $Info(errMsgColor)]
        lappend Info(commandLineInfo) [list "INCORRECT command line argument: $data"]
        lappend Info(commandLineInfo) ""
      }
      continue
    }
    
    set cmd  [lindex $data 0]
    set cmdUC [string toupper $cmd]

    set value [lindex $data 1]
    set value [string trim $value]
    
    switch $cmdUC {

      MODEL-DIRECTORY {

        if { [file isdirectory $value] } {
          set UserSetting(DEFAULT_MODEL_DIRECTORY) $value
          set Info(MODEL_DIRECTORY) $value

        } else {
          if {$do_msg} {
            lappend Info(commandLineInfo) [list "--$cmd = $value" $Info(wrnMsgColor)]
            lappend Info(commandLineInfo) [list "CANNOT FIND the model-directory: $value"]
            lappend Info(commandLineInfo) ""
          }
        }
      }

      MODEL-NAME      { 
        set Info(MODEL_NAME) $value
      }

      PROBLEM-NAME      { 
        set Info(PROBLEM_NAME) $value
      }

      INCLUDE-PATH   {
        set UserSetting(DEFAULT_RESULTS_DIRECTORY) $value
      }

      RESULTS-DIRECTORY   {
        set UserSetting(DEFAULT_RESULTS_DIRECTORY) $value
      }

      LOG-DIRECTORY   {
        set UserSetting(DEFAULT_LOG_DIRECTORY) $value
      }

      SETTINGS-FILE   {
        if { [file exists $value] } {
          lappend Info(userSettingFiles) $value

          # NOTE: This is the default file from now on, for saving etc.!
          set UserSetting(filePath) $value

        } else {
          lappend Info(commandLineInfo) [list "--$cmd = $value" $Info(wrnMsgColor)]
          lappend Info(commandLineInfo) [list "CANNOT FIND the settings file: $value"]
          lappend Info(commandLineInfo) ""
        }
      }

      DEFINITION-FILE   {
        if { [file exists $value] } {
          lappend Model(defaultDefinitionFiles) $value
        } else {
          lappend Info(commandLineInfo) [list "--$cmd = $value" $Info(wrnMsgColor)]
          lappend Info(commandLineInfo) [list "CANNOT FIND the definitions file: $value"]
          lappend Info(commandLineInfo) ""
        }
      }

      default {
        if {$do_msg} {
          lappend Info(commandLineInfo) [list "--$cmd" $Info(errMsgColor)]
          lappend Info(commandLineInfo) [list "UNKNOWN command line argument: $cmd"]
          lappend Info(commandLineInfo) ""
        }
      }
    }
  }

} ;# End handleCommandLineArguments



################################
# Interface procs Tcl <--> Cpp #
################################

set Info(arguments) ""
set Info(results) ""
set Info(cmdSeparator) @
set Info(argSeparator) ^


# Send commands to Cpp
#
proc cpp_exec_ { cmd {arg ""} } {

  set catch_msg ""
  set code [catch {
    #
    global Info __x__
    set Info(arguments) $arg

    if { [string equal -nocase $cmd "cpp_exit"] } {
      cpp_exit
      set __x__ done

    } else {
      set cmd "cpp_$cmd"
      eval $cmd 
      Util::updateMainWindowTitle 
    }
     
  } catch_msg]

  return $catch_msg
}

# Execute commands from Cpp
#
proc gui_exec {s} {
  global Info __x__
  
  set do_eval 1

  if { [catch { set clist [split $s $Info(cmdSeparator)];
                set cmd [lindex $clist 0];
                set Info(arguments) [lindex $clist 1];
              }
       ] } {
    set do_eval 0
    catch { MSG "Gui: cannot parse and exec script: $" }
  }
     

  if { [string equal -nocase $cmd "gui_exit"] } {
    do_exit
    set __x__ done

  } else {
    if { $do_eval } {
      eval $cmd
    }
  }

  return ""
}



#====================================#
# These are NOT in use currently !!! #
# ===================================#

# ReadFromCpp procs
# -----------------

#---A proc to read commands from clients
proc __readAndExec_cpp {s} {
  global Info __x__
  set clist [split $s $Info(cmdSeparator)]
   set l [lindex $clist 0]
   set Info(arguments) [lindex $clist 1]

  if { [string compare $l "cpp_exit"] == 0} {
    cpp_exit
    set __x__ done
  } else {
#    eval $l 
    after idle $l 
  }
}

#---A proc to read commands from clients
#NOTE This is used when calling function directly
#in dll- and slave-implementations
proc cpp_readAndExec {s} {
  global Info __x__

  set clist [split $s $Info(cmdSeparator)]
  set l [lindex $clist 0]
  set Info(arguments) [lindex $clist 1]

  if { [string compare $l "cpp_exit"] == 0} {
#    interp eval my_slave cpp_exit
    cpp_exit
    set __x__ done
  } else {
    eval $l 
#     after idle interp eval my_slave $l 
  }
}

#---A proc to send an error message to be displayed by Gui.
proc __sendErrorMsg {} {
  global Info
  set sep $Info(cmdSeparator)
  set msg $Info(errorMsg)
  __writeForExec2GUI "Interface::displayErrorMsg$sep$msg"
}

#---A proc to send commands to GUI-server
proc __writeForExec2GUI {msg} {
  set code [catch {  GUI_readAndExec $msg } catch_msg]
}


# WriteToCpp  procs
# ----------------

#---A proc to send commands to the client
proc __writeForExec2cpp {msg} {
  set code [catch {  cpp_readAndExec $msg } catch_msg]
#   cpp_readAndExec $msg
}


#---A proc to execute commands from the clients
proc __readAndExec_GUI {s} {
  global Info __x__
  set clist [split $s $Info(cmdSeparator)]
  set l [lindex $clist 0]
  set Info(arguments) [lindex $clist 1]

  if { [string compare $l "GUI_exit"] == 0} {
    do_exit
    set __x__ done
  } else {
    eval $l
  }
}

#---A proc to execute commands from the clients
proc GUI_readAndExec {s} {
  global Info __x__
  set clist [split $s $Info(cmdSeparator)]
  set l [lindex $clist 0]
  set Info(arguments) [lindex $clist 1]

  if { [string compare $l "GUI_exit"] == 0} {
    do_exit
    set __x__ done
  } else {
    eval $l
  }
}
# End not in use
# ==============


# end ecif_tk_mainScript.tcl
# ********************
