#______________________________________________________________________
proc startHlpEngine { {hostName localhost} {portNumber 0} } {
    global env tcl_platform SessionID
    global serverPort vPort vHost
    global chmhelp chmhelpfile
    mess "START HELP ENGINE\n"
 
    set vPort 0


	set portNumber [startHlpServer]
	if {$portNumber == -1} {
		mess "Unable to start AI help system.  Please check you help installation.\n" red
		set vPort $portNumber
		set vHost $hostName
		set serverPort 0
		return 
	}   
	if {$portNumber == 0} {
		mess "Unable to start AI help system, PortNumber was not found\n"
		set vPort $portNumber
		set vHost $hostName
		set serverPort 0
		return 
	}
    # ---portNumber is useble (#0), get socket=serverPort
	set vPort $portNumber
	set vHost $hostName
	set serverPort 0
    set serverPort [EchoClient $hostName $portNumber]
	#set serverPort $portNumber
	#set serverPort $portNumber
	#mess "serverPort: $serverPort\n"
}

proc win_htmlhelp {chm_htmlfile} {

	exec start hh.exe $chm_htmlfile
}
proc startNormalHelp {{ihelpset ""}} {
   global env normal_help_launched
   global serverPort
   global chmhelp chmhelpfile

   if {[string match 0 $serverPort]} {
     mess "Unable to connect to the AI help server, no socket available\n"
     mess "This may be due to the incompatibility between some system \
     files and the java executable provided with the software. Try getting \ 
     latest Java binary and point JAVA_BIN variable to that\n"
     return
   }
   set helpset 0

# Then set the Normal Help
    if {$ihelpset == ""} {
      set jhelpsetclass ICM:icemcfd_mainmenu
      set helpset $jhelpsetclass
      set normal_help_launched 1
   } else {
      set jhelpsetclass ICM:$ihelpset
      set helpset $jhelpsetclass
      set normal_help_launched 1
   }   
   catch {hlp_sendcommand $helpset} error_code
}

proc startVaHelp { } {
   global env va_help_launched
   global serverPort
   global chmhelp chmhelpfile

   if {[info exists chmhelp] && !$chmhelp} {set va_help_launched 0}
   if {[string match 0 $serverPort]} {
     mess "Unable to connect to the AI help server, no socket available\n"
     mess "This may be due to the incompatibility between some system \
     files and the java executable provided with the software. Try getting \ 
     latest Java binary and point JAVA_BIN variable to that\n"
     return
   }
   set helpset 0

     set VA_HELP_DIR [file join $env(ICEM_ACN) .. docu VAHelp] 

      if ![file exists $VA_HELP_DIR] {
        mess "Can't find help directory: $VA_HELP_DIR\n" red
        return -1
      }

# Then set the VA Help
   if {[info exists chmhelp] && $chmhelp} {
      set jhelpsetclass [file join $VA_HELP_DIR jhelpset.chm]
      set chmhelpfile $jhelpsetclass
      set helpset "MERGE: $jhelpsetclass"
   } else {
      set jhelpsetclass [file join $VA_HELP_DIR jhelpset.hs]
      set helpset "MERGE: $jhelpsetclass"
      set va_help_launched 1
   }

   catch {hlp_sendcommand $helpset} error_code
}

proc startTutorialHelp { } {
   global env tutorial_help_launched
   global serverPort
   global chmhelp chmhelpfile

   if {[string match 0 $serverPort]} {
     mess "Unable to connect to the AI help server, no socket available\n"
     mess "This may be due to the incompatibility between some system \
     files and the java executable provided with the software. Try getting \ 
     latest Java binary and point JAVA_BIN variable to that\n"
     return
   }
   set helpset 0

# Then set the Tutorial Help
      set jhelpsetclass ICM:icmtut_hexa_2dpipe
      set helpset $jhelpsetclass
      set tutorial_help_launched 1

   catch {hlp_sendcommand $helpset} error_code
}


proc startUserManualHelp { } {
   global env usermanual_help_launched
   global serverPort
   global chmhelp chmhelpfile

   if {[string match 0 $serverPort]} {
     mess "Unable to connect to the AI help server, no socket available\n"
     mess "This may be due to the incompatibility between some system \
     files and the java executable provided with the software. Try getting \ 
     latest Java binary and point JAVA_BIN variable to that\n"
     return
   }
   set helpset ""

# Then set the User Manual Help

      set jhelpsetclass ICM:iuser_intro
      set helpset $jhelpsetclass
      set usermanual_help_launched 1

   catch {hlp_sendcommand $helpset} error_code
}

proc startInstallationManualHelp { } {
   global env installationmanual_help_launched
   global serverPort
   global chmhelp chmhelpfile

   if {[string match 0 $serverPort]} {
     mess "Unable to connect to the AI help server, no socket available\n"
     mess "This may be due to the incompatibility between some system \
     files and the java executable provided with the software. Try getting \ 
     latest Java binary and point JAVA_BIN variable to that\n"
     return
   }
   set helpset ""


# Then set the User Manual Help

      set jhelpsetclass ICM:installlic_set
      set helpset $jhelpsetclass
      set installationmanual_help_launched 1

   catch {hlp_sendcommand $helpset} error_code
}

proc startReleaseNotes { } {
   global env releasenotes_help_launched
   global serverPort
   global chmhelp chmhelpfile

   if {[string match 0 $serverPort]} {
     mess "Unable to connect to the AI help server, no socket available\n"
     mess "This may be due to the incompatibility between some system \
     files and the java executable provided with the software. Try getting \ 
     latest Java binary and point JAVA_BIN variable to that\n"
     return
   }
   set helpset ""


# Then set the User Manual Help

      set jhelpsetclass ICM:icm_new_improve
      set helpset $jhelpsetclass
      set releasenotes_help_launched 1

   catch {hlp_sendcommand $helpset} error_code
}

proc startProgrammersGuide { } {
   global env programmers_guide_launched    
   global serverPort
   global chmhelp chmhelpfile

   if {[string match 0 $serverPort]} {
     mess "Unable to connect to the AI help server, no socket available\n"
     mess "This may be due to the incompatibility between some system \
     files and the java executable provided with the software. Try getting \
     latest Java binary and point JAVA_BIN variable to that\n"
     return
   }
   set helpset 0


# Then set the User Manual Help
      set jhelpsetclass ICM:ipguide_convention
      set helpset $jhelpsetclass
      set programmers_guide_launched 1

                                                                                
   catch {hlp_sendcommand $helpset} error_code
                                                                                
}

proc startInstallGuide { } {
   global env installs_guide_launched    
   global serverPort
   global chmhelp chmhelpfile
                                                                                
   if {[info exists chmhelp] && !$chmhelp} {set install_guide_launched 0}
   if {[string match 0 $serverPort]} {
     mess "Unable to connect to the AI help server, no socket available\n"
     mess "This may be due to the incompatibility between some system \
     files and the java executable provided with the software. Try getting \
     latest Java binary and point JAVA_BIN variable to that\n"
     return
   }
   set helpset 0
      set jhelpsetclass ICM:installlic_set
      set helpset $jhelpsetclass
      set install_guide_launched 1

                                                                                
   catch {hlp_sendcommand $helpset} error_code
                                                                                
}

proc startBSMManualHelp { } {
   global env BSMmanual_help_launched
   global serverPort
   global chmhelp chmhelpfile

   if {[info exists chmhelp] && !$chmhelp} {set BSMmanual_help_launched 0}
   if {[string match 0 $serverPort]} {
     mess "Unable to connect to the AI help server, no socket available\n"
     mess "This may be due to the incompatibility between some system \
     files and the java executable provided with the software. Try getting \ 
     latest Java binary and point JAVA_BIN variable to that\n"
     return
   }
   set helpset 0

   set aihelp [file join $env(ICEM_ACN) .. .. commonfiles help en-us ]

   if {[regexp "fea2.0" $env(AI_ENV_PRODUCT)] && [info exists env(AI_ENV_CFD)]} { 
   set aihelp [file join $env(ICEM_ACN) .. .. commonfiles help en-us ]
   }
   if {[regexp "fea2.0" $env(AI_ENV_PRODUCT)] && (![info exists env(AI_ENV_CFD)])} { 
   set aihelp [file join $env(ICEM_ACN) .. .. commonfiles help en-us ]
   }
   if {[info exists env(AI_ENV_CFD)] && (![info exists env(AI_ENV_CFX)])} { 
   set aihelp [file join $env(ICEM_ACN) .. .. commonfiles help en-us ]
   }
   if {[info exists env(AI_ENV_CFD)] && ([info exists env(AI_ENV_CFX)])} { 
   set aihelp [file join $env(ICEM_ACN) .. .. commonfiles help en-us ]
   }

    if ![file exists $aihelp] {
        mess "Can't find help directory: $aihelp\n" red
        return -1
    }

# Then set the User Manual Help
   if {[info exists chmhelp] && $chmhelp} {
      set jhelpsetclass [file join $aihelp icemcfd_help.chm]
      set chmhelpfile $jhelpsetclass
      set helpset "MERGE: $jhelpsetclass"
   } else {
      set jhelpsetclass [file join $aihelp icemcfd_help.jar]
      set helpset "MERGE: $jhelpsetclass"
      set BSMmanual_help_launched 1
   }

   catch {hlp_sendcommand $helpset} error_code
}

proc startLegalNoticeHelp { } {
   global env legalnotice_help_launched
   global serverPort
   global chmhelp chmhelpfile

   if {[info exists chmhelp] && !$chmhelp} {set legalnotice_help_launched 0}
   if {[string match 0 $serverPort]} {
     mess "Unable to connect to the AI help server, no socket available\n"
     mess "This may be due to the incompatibility between some system \
     files and the java executable provided with the software. Try getting \ 
     latest Java binary and point JAVA_BIN variable to that\n"
     return
   }
   set helpset 0

# Then set the Legal Notice Help
      set jhelpsetclass ICM:installlic_set
      set helpset $jhelpsetclass
      set legalnotice_help_launched 1

   catch {hlp_sendcommand $helpset} error_code
}

proc get_default_server_port { eshost } {
    global tcl_platform 

    set sock_got 0	
    if {$tcl_platform(os) == "HP-UX"} {
# fconfigure is not returning the port number
	for {set i 50000} {$i < 100000} {incr i} {
	    if ![catch {socket -server $eshost $i} sock] {
		set sock_got 1
		break
	    }	
	}
	if  $sock_got {
		close $sock
		return $i
	} else {
	    mess "could not find valid port to connect\n" red
	    return 0
	} 
    }

    if [catch {socket -server $eshost 0} sock] {
	mess "Error: couldn't open server socket\n $sock"
	set esport ""
    } else {
	set sport [fconfigure $sock -sockname]
	set esport [lindex $sport 2]
	close $sock
    }
    return $esport
}
#
proc get_server_client_sock { eshost } {
    if [catch {socket -server $eshost 0} sock] {
	mess "Error: couldn't open server socket\n $sock"
    } else {
	set sport [fconfigure $sock -sockname]
	set esport [lindex $sport 2]
	catch {close $sock}
    }
    puts "esport: $esport"
    return $esport
}
#
proc getPort {pipe} {
	global got_port
	global UsePort
	variable port
	gets $pipe port
	fileevent $pipe readable ""
	puts "Port Number: $port\n"
	set UsePort $port
	set got_port 1
} 

proc startHlpServer {} {
    global env
    global tcl_platform UsePort SessionID
    global chmhelp chmhelpfile

    if { ![info exists UsePort] || ![info exists SessionID] } {
        set SessionID ICEMHelp
    }
    if { $tcl_platform(platform) == "unix" } {
        set monofile [file join "$env(ICEM_ACN)" .. .. Tools mono Linux64 bin mono]
	    set monoExe "\"[file join $env(ICEM_ACN) .. .. Tools mono Linux64 bin mono]\""
	    set aihelp [file join "$env(ICEM_ACN)" .. .. commonfiles help HelpViewer ANSYSHelpViewer.exe ]
	    set helpExe "\"[file join $env(ICEM_ACN) .. commonfiles help HelpViewer ANSYSHelpViewer.exe]\""
	    set helpdir [file join "$env(ICEM_ACN)" .. .. commonfiles help HelpViewer]
	    if ![file exists $monofile] {
		    mess "Can't find mono installation: $monofile\n" red
		    return -1
	    }		
    } else {
	    set aihelp [file join "$env(ICEM_ACN)" .. .. commonfiles help HelpViewer ANSYSHelpViewer.exe ]
	    set helpExe "\"[file join $env(ICEM_ACN) .. .. commonfiles help HelpViewer ANSYSHelpViewer.exe]\""
	    set helpdir [file join "$env(ICEM_ACN)" .. .. commonfiles help HelpViewer]	
    }
	if { (![file exists $aihelp]) || (![file exists $helpdir])} {
		mess "Can't find help directory: $aihelp\n" red
		return -1
	}   
    mess "Help being launched\n"
    if [info exists env(ANSHELP_SESSION_ID)] {
        set SessionID $env(ANSHELP_SESSION_ID)
    }
    # starting the help viewer from the project directory locks the project directory
    # in case that we try to remove the project later and the help viewer is still running 
    set here [pwd]
    cd ~
    if { $tcl_platform(platform) == "windows" } {
        catch {set portNum [ open "|$helpExe --sessionID $SessionID --language en-us"] } helperr
    } else {
        catch {set portNum [ open "|$monoExe $aihelp --sessionID $SessionID --language en-us"] } helperr	
    }
	fileevent $portNum readable [list getPort $portNum]
	fconfigure $portNum -buffering line
	set got_port 0
	vwait got_port
    cd "$here"
    return $UsePort
}

proc EchoClient {host port} {
    global env
    set time [clock seconds]
    while {[catch {socket $host $port} helpSocket]} {
	if { [clock seconds] > [expr $time + 60]} {
	    # the thin server is not yet available after 60 seconds
	    # so bail out.
	    set helpSocket 0
	    mess "Error: connection timed out\n" red
	    mess "Could not connect to help server at host: $host, port: $port\n" red
	    return 0
	}
	after 750
    }
    
    mess "Successfully connected to help server at port: $port\n"
    
    catch {fconfigure $helpSocket -buffering line -blocking 0}
    return $helpSocket
}

proc EchoClient_new { eshost port } {
    if [catch {socket -server $eshost 0} sock] {
	puts "couldn't open server socket"
    } else {
	set sport [fconfigure $sock -sockname]
	set esport [lindex $sport 2]
#	catch {close $sock}
    }
    puts "esport: $esport"
    return $esport
}

proc hlp_sendcommand { args } {
    global env serverPort vPort vHost failure
    global chmhelp chmhelpfile

    if [info exists vPort] {
        if {$vPort == -1} {
            mess "Help could not be started.  Please check you help installation.\n" red
            return
        }
        if {$vPort == 0} {
            if {[string match QUIT $args]} {
            } else {
                mess "Help not available\n"
            }
            return
        }
   
   
        # if vPort is not = 0, check if a socket available---
        if {[string match 0 $serverPort]} {
            set serverPort [EchoClient $vHost $vPort]
        }
        if {[string match 0 $serverPort]} {
            set serverPort [EchoClient $vHost $vPort]
            mess "Unable to connect to the AI help system. Try again later" orange
            return
        }
     
        # This catch will detect that the java process has crashed and attempt
        # to restart. If it fails to restart and connect, it will declare the
        # help system dead
        set res [catch {puts $serverPort $args} error]

        if $res {
            mess "res = $res; error = $error \n" red
            set portNumber [startHlpServer]
	        set vPort $portNumber
	        set vHost localhost 
            set serverPort [EchoClient localhost $portNumber]
	        #set serverPort $portNumber
	        #set serverPort $portNumber
	        mess "serverPort: $serverPort\n"
            set res1 [catch {puts $serverPort $args} error]
        }   
     
        if {[string match QUIT $args]} {
            mess "Quit"
        }
   }
   return
}

proc chmhlp_intialize {} {
   global env
   global tcl_platform options chmhelp chmhelpfile

   if {[info exists chmhelp]} {
      if {$tcl_platform(platform) == "windows"} {
         set chmhelp 1
      }
   } 
 
   if {[info exists options(win_java_help)]} {
      if {$options(win_java_help)} {
         set chmhelp 1
      }
   }

}
