''******************************************************************************
'  File: PMACSstartup.vb                                        
'  Programmer: Ting Chan   Date: August 12, 2004
'  
'  Description:
'  This is the startup form for the PMACS client GUI of the MARS project.
'  This form is the "parent" form which invokes the other child forms of
'  the project.  Note that form PMACSstartup.vb is in effect a "dummy" form
'  only used to invoke the other child forms and in actual usage the operator
'  will never see the  window or controls that appear in the vb design window.
'
'  The Monterey Accelerated Research System (MARS) is a
'  cabled-based observatory system, incorporating a benthic
'  instrument node, AUVs, and various benthic and moored
'  instrumentation. The MARS infrastructure will provide the
'  capability to place and power instruments in areas of scientific
'  interest in various geographical sites.
'
'  This project was developed with Microsoft Visual Basic.NET.
'  Microsoft Development Environment 2003 Version 7.1.3088
'  Microsoft .NET Framework 1.1 Version 1.1.4322.
'
'
' Third Party Software Packages Used:
'
' 1. Shape Control:
'    This project uses the Shape Control from the Vbtrain.net software toolkit
'    by Platte Canyon (see website at http://www.vbtrain.net/trackerinfo.aspx.
'
'    Excerpt from above website:  Visual Studio.NET does not have lines, circles,
'    rectangles, or other shapes available in the Toolbox. Nor does it have a
'    "Tool Palette" for drawing these objects on the form.
'    The Shape control gives you the ability to easily create the shapes you want.
'    Want a circle on your screen? Drag the Shape from the Toolbox. Change its
'    dimensions by resizing its bounding rectangle. Use the Properties window
'    or your code to set its shape type, fill and border effects (linear
'    gradient, path gradient, texture, etc.), colors, "smoothing," and more.
'    Create ellipses, rectangles, lines, arrows, triangles, and other polygons.
'    Change shapes instantaneously. Better yet, do this in either your ASP.NET
'    or Windows applications. In ASP.NET, you can choose to have your shapes
'    stored as external files or streamed right to the browser! And when you
'    use external files, you get lots of options as to when to rewrite the image.
'
'    To use the Shape in VB.NET you add it into your vb.net toolbox by clicking
'    the upper menubar <tools> tab then click <Add/Remove toolbox> and then browse
'    for the Shape tool (you must have previously unzipped the file downloaded from
'    the Platte Canyon website).  After doing this you will find a "Shape" tool
'    in the vb toolbox with the other tools (it may be under "General" instead of the
'    "Windows Components").  It is almost like using the old "Line" control in VB6.
'    You just drag the tool onto your form and the use the mouse to
'    move the endpoints.  You can set the thickness of the line from
'    1 pixel or larger.  You can also click on the line and get the
'    click-event routine to run.
'
' 2. Matrix Operations Library:
'    This project uses the Matrix Operations Library .NET which is a free download
'    by Anas S. A. and can be found at the following website:
'    http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=907&lngWId=1 
'    The project required many matrix operations, that time I really wished that
'    I would find a class or a library with ready functions for matrix manipulations
'    (like addition, inverse, multiplication, etc…) to use in Visual Basic.
'    Unfortunately I could not find such a class, so I decided to write my own
'    class, I called it "cMathLib" . This class gives the user the flexibility
'    to work with matrices and do operations on them. The dimensions of the
'    matrices are neither pre-specified nor limited. The code is highly optimized
'    for fast operation. The code attached contains the class file called with a
'    demonstration on how to use it. Opperations included in the class are :
'    Add, Subtract, Determinant, Inverse, Transpose, Multiply, Print,
'    MultiplyVectors,Magnitude of a Vector, scalar multiply, and scalar divide.
'    I posted a similar code in Visual Basic 6 Zone two days ago and the reaction
'    was too good to imagine, so I decided to post the VB.NET version of the code
'    here. I really hope this class would be of any help to any of you who needs
'    to work with matrix operations.
'
' NOTES:
'
' NOTES ON CREATING A SOAP CLIENT FOR PMACS IN VB.NET
' 1. During the installation of Microsoft Visual Studio.NET from the install
'    CD's you should see a window or titled:
'    "Microsoft Visual Studio .NET Prerequisites, Web Project Requirements"
'    which has instructions for installing Internet Information Service (IIS),
'    Frontpage Server Extensions (FPSE) and Security Updates.
'    I think these components are necessary if you want to create or consume
'    web services like SOAP in your VB.net application
'    If you have already installed Visual Studio.net but have not installed
'    these components the instructions are in a file called WebServer.htm. 
'    On my computer it was in the following directory path
'    C\Program Files\Microsoft Visual Studio .NET 2003\
'    Visual Studio .NET Professional 2003 - English\WebServer.htm
' 2. Start Microsoft Visual Studio .NET 2003.
' 3. In the top menu bar select <File>, <New>, <Project>.
' 4. In the window that pops up, highlight "VB.NET" on the left and highlight
'    "Windows Application" project.  (I think other project types may work
'    just as well like Asp.Net Web application, but a Windows Application is
'    all that is needed for just a SOAP client).  Then click <OK>.
' 5. You should see the Design window containing an empty form titled "PMACSmain".
' 6. On the right side of the screen you should see the Solution Explorer
'    window which has the tree diagram showing the files associated with the project.
' 7. You will now autogenerate the Proxy from Mike Kenneys's WSDL file
'    which is located on his Linux computer.  In Solution Explorer, right click
'    on the bold font project name (like "jbePMACStestWinApp").  Then select
'    "Add Web Reference" (do NOT select the "Add Reference" by mistake!!!). 
'    In the textbox for the URL enter
'    http://pmacs.apl.washington.edu/wsdl/pmacs.wsdl
'    Then left click the <Go> button next to the textbox.
'    In the gray box on the right you should see "1 Service found: pmacs".
'    Then click the <Add Reference> button.
' 8. You should now see in the Solution Explorer tree "Web References"
'    and underneath it "edu.washington.apl.orion".  The proxy file is
'    hidden from view.  To be able to see the proxy file click the
'    icon named "Show All Files" at the top of the Solution Explorer.
'    Expand the tree branches by clicking the "+" next to
'    "edu.washington.apl.orion" and others.  You should also see additional
'    branches labeled "pmacs.WSDL", "Reference.map" and "Reference.vb".
' 9. Reference.vb is the proxy class autogenerated from pmacs.wsdl.
'    If desired, view the vb code by double clicking Reference.vb.
'    Note that later if Mike Kenney should change the pmacs.wsdl file
'    you can right click "edu.washington.apl.orion" and select
'    <Update web reference> to update the corresponding autogenerated code.
'
'*******************************************************************************
'*******************************************************************************
' Notes on Multithread strategy:
'
' We want to call the SOAP method CheckGf() to get the ground fault currents.
' But the CheckGf() method takes 2 seconds to return to the calling program
' during which time we want the program to be doing other things.  So it would
' be desirable to create a "no-wait" version of CheckGf() by using
' multi-threading which is supported very well in VB.NET. 
'
' So instead of calling checkGf() from within a timer event handler every
' 2 seconds as we originally implemented it, we will implement the following
' no-wait version of the code:
'
' 1. There will be a timer control called TimerCheckGfNoWait which will
'    replace the old Timer2 timer corntorl.  The timer TimerCheckGfNoWait
'    will be initialized with an interval of 100 msec.
'
' 2. There will be a routine call CheckGfWorkerThread() that runs in
'    its own thread separately from the thread of the main PMACS client
'    parent thread.  This thread will have a routine that will continuously
'    loop and call the SOAP method checkGf() and then wait for it to return
'    the Ground Fault current to be returned.
'
' 3. There will be several new global variable that will be used to handshake
'    between the parent thread and the worker thread:
'    busStringForGroundFaultMeasure - Global string containing the name of one of the 4 busses
'                                     such as "v400", "v400r", "v48", "v48r", "test".
'                                     Used in call to SOAP method to get the Ground Fault current.
'    gotNewGfMeasurement            - True if independent thread has gotten a
'                                     new Ground Fault current measurement. 
'    mostRecentGFCurrent            - Integer used to transfer Ground Fault current
'                                     value from the worker thread to the main parent thread.
'
' 4. We may later want to add read/write lock support to insure there are no conflict when
'    the parent thread and the worker thread try to access the same variables. 
'    I am not sure if this is necessary since I have observed no conflicts
'    so far but more thorough testing should be done to be certain.
'
' Revision History:
' 08-13-2004 New header block comments added by John Elliott, APL.
' 09-03-2004 Timer1 added allowing client to continously poll data by Ting Chan, UWEE
' 10-25-2004 Converter Initialization done at PMACSextload.vb by Ting Chan, UWEE
' 11-04-2004 Initialization for loads before loading Data from Server addes by Ting Chan, UWEE
' 12-16-2004 Add Try-Catch module in Timer1 event by John Elliott, APL.
' 01-10-2005 Add PMACSstartup_Closing() to let user confirms the closing action by Ting Chan, UWEE
' 03-10-2005 Add default current limits for internal loads and call setLoads() by Ting Chan, UWEE
' 04-28-2005 Commented out Sub TimerCheckGfNoWait_Tick(), Sub Timer1_Tick() by John Elliott, APL.
' 04-29-2005 Remove TimerCheckGfNoWait event and Timer1 event by Ting Chan, UWEE
'            See also TimerGroundFault and TimerLoadData event in PMACSmain.vb
' 05-26-2005 Added initializations for get data flags by Ting Chan, UWEE
' 06-22-2005 Added initializations for first event flags by Ting Chan, UWEE
'*******************************************************************************

Option Strict Off
Option Explicit On 
Friend Class PMACSstartup
    Inherits System.Windows.Forms.Form
#Region "Windows Form Designer generated code "
    Public Sub New()
        MyBase.New()
        If m_vb6FormDefInstance Is Nothing Then
            m_vb6FormDefInstance = Me
        End If
        'This call is required by the Windows Form Designer.
        InitializeComponent()
    End Sub
    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal Disposing As Boolean)
        If Disposing Then
            If Not components Is Nothing Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(Disposing)
    End Sub
    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer
    Public ToolTip1 As System.Windows.Forms.ToolTip
    Public MainMenu1 As System.Windows.Forms.MainMenu
    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.
    'Do not modify it using the code editor.
    Friend WithEvents MenuItem1 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuMain As System.Windows.Forms.MenuItem
    Friend WithEvents mnuShore As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem2 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuExtLoad As System.Windows.Forms.MenuItem
    Friend WithEvents mnuEvents As System.Windows.Forms.MenuItem
    Friend WithEvents mnuIntLoad As System.Windows.Forms.MenuItem
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container
        Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(PMACSstartup))
        Me.ToolTip1 = New System.Windows.Forms.ToolTip(Me.components)
        Me.MainMenu1 = New System.Windows.Forms.MainMenu
        Me.MenuItem1 = New System.Windows.Forms.MenuItem
        Me.mnuMain = New System.Windows.Forms.MenuItem
        Me.mnuShore = New System.Windows.Forms.MenuItem
        Me.MenuItem2 = New System.Windows.Forms.MenuItem
        Me.mnuExtLoad = New System.Windows.Forms.MenuItem
        Me.mnuIntLoad = New System.Windows.Forms.MenuItem
        Me.mnuEvents = New System.Windows.Forms.MenuItem
        '
        'MainMenu1
        '
        Me.MainMenu1.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MenuItem1})
        '
        'MenuItem1
        '
        Me.MenuItem1.Index = 0
        Me.MenuItem1.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuMain, Me.mnuShore, Me.MenuItem2, Me.mnuEvents})
        Me.MenuItem1.Text = "Open"
        '
        'mnuMain
        '
        Me.mnuMain.Index = 0
        Me.mnuMain.Text = "PMACS Main Window"
        '
        'mnuShore
        '
        Me.mnuShore.Index = 1
        Me.mnuShore.Text = "PMACS Shore Station"
        '
        'MenuItem2
        '
        Me.MenuItem2.Index = 2
        Me.MenuItem2.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuExtLoad, Me.mnuIntLoad})
        Me.MenuItem2.Text = "PMACS Science Node"
        '
        'mnuExtLoad
        '
        Me.mnuExtLoad.Index = 0
        Me.mnuExtLoad.Text = "PMACS External Load"
        '
        'mnuIntLoad
        '
        Me.mnuIntLoad.Index = 1
        Me.mnuIntLoad.Text = "PMACS Internal Load"
        '
        'mnuEvents
        '
        Me.mnuEvents.Index = 3
        Me.mnuEvents.Text = "PMACS Events Log"
        '
        'PMACSstartup
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.BackColor = System.Drawing.Color.FromArgb(CType(128, Byte), CType(128, Byte), CType(128, Byte))
        Me.ClientSize = New System.Drawing.Size(968, 542)
        Me.Cursor = System.Windows.Forms.Cursors.Default
        Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
        Me.IsMdiContainer = True
        Me.Location = New System.Drawing.Point(11, 49)
        Me.Menu = Me.MainMenu1
        Me.Name = "PMACSstartup"
        Me.RightToLeft = System.Windows.Forms.RightToLeft.No
        Me.Text = "PMACS"
        Me.WindowState = System.Windows.Forms.FormWindowState.Maximized

    End Sub
#End Region
#Region "Upgrade Support "
    Private Shared m_vb6FormDefInstance As PMACSstartup
    Private Shared m_InitializingDefInstance As Boolean
    Public Shared Property DefInstance() As PMACSstartup
        Get
            If m_vb6FormDefInstance Is Nothing OrElse m_vb6FormDefInstance.IsDisposed Then
                m_InitializingDefInstance = True
                m_vb6FormDefInstance = New PMACSstartup
                m_InitializingDefInstance = False
            End If
            DefInstance = m_vb6FormDefInstance
        End Get
        Set(ByVal Value As PMACSstartup)
            m_vb6FormDefInstance = Value
        End Set
    End Property
#End Region

#Region "Load PMACSstartup"
    '*********************************************************************************
    'Load PMACSstartup.vb which is the parent form for all other forms.
    'The main function is to show the main form of the program (PMACSmain) and
    'enable the timer function to start polling data from the server continuously
    'In addition, a number of initializations are done here when loading up the
    'form which keep track of all the controls of other forms.
    '*********************************************************************************
    Private Sub PMACSstartup_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load
        RL = 60             'RL is the cable resistance, here assume cable length is 60km
        activeFlag = False  'initilialize that no control is in active
        Dim r As Integer
        Dim c As String
        Dim X As Integer
        Dim Z As Integer
        Dim Y As Integer
        Dim i As Integer
        Dim response As Integer
        Dim myPrompt As String
        Dim result As String
        Dim myString As String
        Dim IndexString As String
        Dim ws As New edu.washington.apl.pmacs.load_service  'work variable.
        Dim myIntLoadUpdateType As New edu.washington.apl.pmacs.loadUpdateType
        Dim myIntLoadListType As edu.washington.apl.pmacs.loadListType
        Dim myDateTime As String    'store date and time in AM/PM from input seconds
        Dim myMicrosec As Integer    'store input microseconds
        Dim myStringMicrosec As String  'the string to hold microsec
        Dim myDate As String 'store date
        Dim myTime As String 'store time
        Dim mySec As String 'store second, for single digit, it has not 0
        Dim mySecond As String 'store second, for single digit, it has a 0 in front
        Dim myUTCTime As String 'store UTC time
        Dim myFullUTCTime As String 'UTC time with microsecond

        Dim myDatedate As Date      'hold the date in Date format
        Dim myFormatDate As String 'convert date into MMMM dd, yyyy format

        '***********************************************************************************
        ' initialize the total avaliable power
        '***********************************************************************************
        TotalAvailablePower = 10000

        'get current time
        myDateTime = Now
        myDate = DateValue(myDateTime)  'store the current date
        myDatedate = myDate             'store the date info without time
        myFormatDate = Format(myDatedate, "yyyy.MM.dd") 'format the date into the desired format YYYY.MM.DD
        myTime = TimeValue(myDateTime)  'store the current time
        mySec = Second(myTime)          'store the current second
        mySecond = Format(CDbl(mySec), "0#")    'add a zero is the second is in single digit
        myUTCTime = FormatDateTime(myTime, 4)   'convert time into a 24 clock WITHOUT second
        myFullUTCTime = myFormatDate + "   " + myUTCTime + ":" + mySecond   'add the seconds into the date and time

        '**********************************************************
        ' Display the system time on all windows
        '**********************************************************
        PMACSextload.DefInstance.DateTime.Text = myFullUTCTime '+ " (UTC)"
        PMACSintload.DefInstance.DateTime.Text = myFullUTCTime '+ " (UTC)"
        PMACS48Vintload.DefInstance.DateTime.Text = myFullUTCTime '+ " (UTC)"
        PMACS12Vintload.DefInstance.DateTime.Text = myFullUTCTime '+ " (UTC)"
        PMACS5Vintload.DefInstance.DateTime.Text = myFullUTCTime '+ " (UTC)"
        PMACSengsensor.DefInstance.DateTime.Text = myFullUTCTime '+ " (UTC)"
        PMACSmain.DefInstance.DateTime.Text = myFullUTCTime '+ " (UTC)"
        PMACSmvconverter.DefInstance.DateTime.Text = myFullUTCTime '+ " (UTC)"
        PMACSshore.DefInstance.DateTime.Text = myFullUTCTime '+ " (UTC)"
        PMACSgroundfault.DefInstance.DateTime.Text = myFullUTCTime ' + " (UTC)"
        PMACSfaultlocation.DefInstance.DateTime.Text = myFullUTCTime ' + " (UTC)"
        PMACStopology.DefInstance.DateTime.Text = myFullUTCTime ' + " (UTC)"
        PMACSalarm.DefInstance.DateTime.Text = myFullUTCTime

        SystemUTCTime = myFullUTCTime   'store the time as the system time in UTC
        MVConverterUTCTime = SystemUTCTime

        'set a default directory for storing data files
        Dim MyDirExist As String
        Dim MyDirName As String
        Dim MyCurDir As String
        Dim MyDay As Integer
        Dim MyMonth As Integer
        Dim MyMonthName As String
        Dim MyMinute As Integer
        Dim MyYear As Integer

        Dim MyCompleteFileName As String

        BaseDir = CurDir()  'base directory is where the .exe file is
        MyYear = Year(Now)  'get year
        MyMonth = Month(Now)    'get month
        MyMonthName = MonthName(MyMonth, True)  'get current month name
        MyDay = Microsoft.VisualBasic.Day(Now)  'get the day of the month
        MyCurDir = CurDir()
        MyDirName = BaseDir + "\" + CStr(MyYear) + "\" + MyMonthName + CStr(MyDay) 'desired directory with current month and day

        MyDirExist = Dir(MyDirName, vbDirectory)    'check to see if desired directory already exist 
        If MyDirExist = "" Then
            'if the desired directory does not exist
            'create the directory
            MkDir(MyDirName)
        End If
        ChDir(MyDirName)    'change the current directory to the desired one

        'initialze the flags for receiving data from server
        NPCChangeType = 0
        NPCChange = False
        NPCState = 0
        globalNPCStatus = False
        GotExtLoadData = False
        GotIntLoadData = False
        GotBusData = False
        GotSensorData = False
        GotMVData = False
        GotShoreData = False
        GotGFData = True

        'jbe new 04-06-2005: Set lockCriticalCodeCount to zero to indicate there are no
        '  critical sections of code executing presently.  When non-zero 
        '  indicates that one of the threads is executing a critical section of code.  Only one critical 
        '  section of code should be allowed to run at any time.  This was needed for thread synchronization 
        '  to prevent errors such as the big red 'X' in the datagrids and incomplete repaint of controls on 
        '  the forms.
        lockCriticalCodeCount = 0

        'initialize number of messeges to 0
        MessageCount = 0

        'initialize the flags for displaying alert messages
        'the flags are all true so any message will be new
        'and displayed on the customized message box
        FirstEventFlagNPC = True
        FirstEventFlagNPCState = True
        FirstEventFlagExtLoad = True
        FirstEventFlagIntLoad = True
        FirstEventFlagBus = True
        FirstEventFlagSensor = True
        FirstEventFlagMV = True
        FirstEventFlagShore = True
        FirstEventFlagGF400 = True
        FirstEventFlagGF48 = True
        FirstEventFlagGFCom = True
        FirstEventFlagGFUnknown = True
        FirstEventFlagGF = True

        'set the ready flag for ground faults
        'since the NEW ground fault detection requires all 
        '4 busses to have measurements before drawing a conclusion
        'set all flags to false at the beginning
        GF400VReady = False
        GF400VRReady = False
        GF48VReady = False
        GF48VRReady = False

        'start loading data from server
        wantPauseLoadDataThread = False

        'NOT running fault location
        RunFaultLocation = False

        'check the login type of the user and initialize the controls
        If LoginType = 1 Then   'login as the console
            wantPauseGfCheckThread = False
            PMACSmain.DefInstance.Login.Text = "Logged as Console"
        ElseIf LoginType = 2 Then   'login as a remote client
            'remote client does not have ground fault detection or any control over 
            PMACSfaultlocation.DefInstance.FaultLocationStatus.Text = "Fault Location is Disabled for Remote Clients"
            PMACSfaultlocation.DefInstance.FLRun.Enabled = False
            PMACSfaultlocation.DefInstance.FLStop.Enabled = False
            PMACSmain.DefInstance.Login.Text = "Logged as Remote Client"
            'NO ground fault detection
            wantPauseGfCheckThread = True
            'disable controls on external load window
            For i = 0 To 7
                PMACSextload.DefInstance.LabelLoad(i).Enabled = False
                PMACSextload.DefInstance.Load_Renamed(i).Enabled = False
                PMACSextload.DefInstance.Load_400Switch(i).Enabled = False
                PMACSextload.DefInstance.Load_400Deadface(i).Enabled = False
                PMACSextload.DefInstance.Load_48Switch(i).Enabled = False
                PMACSextload.DefInstance.Load_48Deadface(i).Enabled = False
            Next
            'disable controls on internal load windows for 48V and 12V
            For i = 0 To 6
                'disable controls on PMACSintload form for 12V and 48V
                PMACSintload.DefInstance.LabelIntLoad12(i).Enabled = False
                PMACSintload.DefInstance.IntLoad12(i).Enabled = False
                PMACSintload.DefInstance.Switch12(i).Enabled = False
                PMACSintload.DefInstance.LabelIntLoad48(i).Enabled = False
                PMACSintload.DefInstance.IntLoad48(i).Enabled = False
                PMACSintload.DefInstance.Switch48(i).Enabled = False

                'disable controls on PMACS12Vintload form
                PMACS12Vintload.DefInstance.LabelIntLoad12(i).Enabled = False
                PMACS12Vintload.DefInstance.IntLoad12(i).Enabled = False
                PMACS12Vintload.DefInstance.Switch12(i).Enabled = False

                'disable controls on PMACS48Vintload form
                PMACS48Vintload.DefInstance.LabelIntLoad48(i).Enabled = False
                PMACS48Vintload.DefInstance.IntLoad48(i).Enabled = False
                PMACS48Vintload.DefInstance.Switch48(i).Enabled = False
            Next
            'disable controls on internal load windows for 5V
            For i = 0 To 1
                'disable controls on PMACSintload form for 5V
                PMACSintload.DefInstance.LabelIntLoad5(i).Enabled = False
                PMACSintload.DefInstance.IntLoad5(i).Enabled = False
                PMACSintload.DefInstance.Switch5(i).Enabled = False

                'disable controls on PMACS5Vintload form
                PMACS5Vintload.DefInstance.LabelIntLoad5(i).Enabled = False
                PMACS5Vintload.DefInstance.IntLoad5(i).Enabled = False
                PMACS5Vintload.DefInstance.Switch5(i).Enabled = False
            Next
            'disable all ground fault setting controls
            PMACSgroundfault.DefInstance.Set400V.Visible = False
            PMACSgroundfault.DefInstance.Set400V.Enabled = False
            PMACSgroundfault.DefInstance.Set48V.Visible = False
            PMACSgroundfault.DefInstance.Set48V.Enabled = False
            PMACSgroundfault.DefInstance.GFRestart.Visible = False
            PMACSgroundfault.DefInstance.GFRestart.Enabled = False
            PMACSgroundfault.DefInstance.PauseGFDetection.Visible = False
            PMACSgroundfault.DefInstance.PauseGFDetection.Enabled = False
            PMACSgroundfault.DefInstance.GFTesting.Visible = False
            PMACSgroundfault.DefInstance.GFTesting.Enabled = False
            PMACSgroundfault.DefInstance.GFDetect.Text = "Disabled!"
            PMACSgroundfault.DefInstance.GFDetectStatus.Visible = True

            'disbale menu items for remote client
            PMACSmain.DefInstance.mnuDisconnect.Enabled = False
            PMACS5Vintload.DefInstance.mnuDefault.Enabled = False
            PMACS12Vintload.DefInstance.mnuDefault.Enabled = False
            PMACS48Vintload.DefInstance.mnuDefault.Enabled = False
            PMACSintload.DefInstance.mnuDisconnect.Enabled = False
            PMACSextload.DefInstance.mnuDefault.Enabled = False

            'disable shore power supply control 
            PMACSshore.DefInstance.ShoreSupplyManagement.Enabled = False
            PMACSshore.DefInstance.ShoreSupplyManagement.Visible = False
            PMACSshore.DefInstance.Label13.Visible = True
            PMACSshore.DefInstance.Label14.Visible = True
        End If

        counter = 1

        Me.Text = ""

        'initialize the data grid in PMACSmain and PMACSalarm
        'Call InitializeGrid()
        'Call InitializeSEGrid()
        Call InitializeAlarmGrid()

        'initialize state for MV converters and external load
        For i = 0 To 1
            MVConverters(i).ConverterChangeType = 0
            MVConverters(i).ConverterChange = False
            MVConverters(i).ConverterOldOK = 1
            MVConverters(i).ConverterOldS2 = 0
            MVConverters(i).ConverterOldStatus = 0
        Next

        For i = 0 To 7
            Loads(i).Load48OldCurrentLimit = 1
            Loads(i).Load400OldCurrentLimit = 1
            Loads(i).Load400OldState = -1
            Loads(i).Load48OldState = -1
            Loads(i).Change400 = False
            Loads(i).Change48 = False
            Loads(i).ChangeType400 = 0
            Loads(i).ChangeType48 = 0
        Next i

        'Default current limits and load name for 48V internal loads
        IntLoads48(0).DefaultCurrentLimit = 1       'Channel 10 current limit
        IntLoads48(1).DefaultCurrentLimit = 1       'Channel 11
        IntLoads48(2).DefaultCurrentLimit = 1       '48V channel 12 is not assigned, use 0 amp as default
        IntLoads48(3).DefaultCurrentLimit = 0.5     'Channel 13
        IntLoads48(4).DefaultCurrentLimit = 0.5     'Channel 14
        IntLoads48(5).DefaultCurrentLimit = 0.25    'Channel 15
        IntLoads48(6).DefaultCurrentLimit = 0.25    'Channel 16 

        IntLoads48(0).LoadName = "WEST NE OPTICAL SWITCH" '"OTW POW"      'Channel 10 
        IntLoads48(1).LoadName = "WEST EDFA" '"OAW POW"      'Channel 11"
        IntLoads48(2).LoadName = "SPARE"        'Channel 12 
        IntLoads48(3).LoadName = "EAST NE OPTICAL SWITCH" '"OTE POW"      'Channel 13
        IntLoads48(4).LoadName = "EAST EDFA" '"OAE POW"      'Channel 14
        IntLoads48(5).LoadName = "OBC A"    'Channel 15
        IntLoads48(6).LoadName = "OBC B"    'Channel 16 

        'Default current limits and name for 12V internal loads
        IntLoads12(0).DefaultCurrentLimit = 10      'Channel 3
        IntLoads12(1).DefaultCurrentLimit = 10      'Channel 4
        IntLoads12(2).DefaultCurrentLimit = 1       'Channel 5
        IntLoads12(3).DefaultCurrentLimit = 1       'Channel 6
        IntLoads12(4).DefaultCurrentLimit = 1       'Channel 7
        IntLoads12(5).DefaultCurrentLimit = 1       'Channel 8
        IntLoads12(6).DefaultCurrentLimit = 1       'Channel 9

        IntLoads12(0).LoadName = "CISCO MRA01-01" '"L2/L3 SWITCH A"      'Channel 3
        IntLoads12(1).LoadName = "CISCO MRA01-02" '"L2/L3 SWITCH B"      'Channel 4
        IntLoads12(2).LoadName = "OE WEST 75"       'Channel 5"
        IntLoads12(3).LoadName = "CYCLADES"     'Channel 6
        IntLoads12(4).LoadName = "OE EAST 75"       'Channel 7
        IntLoads12(5).LoadName = "OE EAST 98"     'Channel 8
        IntLoads12(6).LoadName = "OE WEST 98"       'Channel 9

        'Default current limits and name for 5V internal loads
        IntLoads5(0).DefaultCurrentLimit = 1       '5V channel 1 is not assigned, use 1 amp as default
        IntLoads5(1).DefaultCurrentLimit = 0.2      'Channel 2

        IntLoads5(0).LoadName = "SPARE"        'Channel 1 
        IntLoads5(1).LoadName = "TIME DIST"      'Channel 2

        'initialize ground fault settings
        'ground fault currents in uA
        Science.GFTestSetpoint = 50
        Science.GF400HighSetpoint = 50
        Science.GF400LowSetpoint = 50
        Science.GF48HighSetpoint = 50
        Science.GF48LowSetpoint = 50
        GFCurrent400V = 10
        GFCurrent400VR = 10
        GFCurrent48V = 10
        GFCurrent48VR = 10
        'initialize the ground fault busses
        'no bus is faulted
        'all GF bus variable set to false
        GF400V = False
        GF400VR = False
        GF48V = False
        GF48VR = False

        'display GF settings on external load screen
        Call GFInitialize(Science)

        'jbe: I am not sure if global boolean wantAbortGfCheckThread works anymore????
        'I originally thought this boolean would be used to tell the Ground Fault child thread to
        'terminate, but it looks like it somehow has been used to pause the Ground Fault child thread 
        'for display updates.  I have commented out it use elsewhere in the code but
        ' we should re-examine its present usage. 4-06-2005.
        wantAbortGfCheckThread = False

        'jbeOld-- gotNewGfMeasurement = False 'jbe new: True if independent thread has gotten a
        '                            new Ground Fault current measurement.  Else false.

        'jbeCommentOut--  busStringForGroundFaultMeasure = "v400" 'jbe new: Global string containing the name of one of the 4 busses
        '                                        such as "v400", "v400r", "v48", "v48r", "test".
        '                                        Used in call to SOAP method to get the Ground Fault current.
        '                                        Intialize arbitrarily to insure Ground Fault worker thread
        '                                        will have something to use when it is first started.


        ''jbeCommentOut--  jbe new: TimerCheckGfNoWait replaces the old Timer2 and workswith a thread so that
        'jbeCommentOut--  '    the program does not get delayed by 2 seconds as it didearlier.
        'jbeCommentOut--  '    The Interval can be very short since timer event handler
        'jbeCommentOut--  '    will not wait for the Ground Fault measurement which is now
        'jbeCommentOut--  '    done in a separate worker thread.
        'jbeCommentOut--  TimerCheckGfNoWait.Interval = 100 'jbe new
        'jbeCommentOut--  TimerCheckGfNoWait.Enabled = True 'jbe new

        'initialize the state of the shore to 1 (ON)
        Shore.ShoreState = 1

        'initialize the state estimation output matrices
        Z = StateEstimation(SSV(SNSize), SSI(SNSize), SNV(SNSize))

        'try to communicate with server and get staus of the NPC
        Try
            NPCState = ws.getNPCState
            NPCOldState = NPCState
            globalNPCStatus = True
            globalNPCOldStatus = globalNPCStatus
        Catch ex As Exception
            'tc: Some error occurred (probably in the Soap request code).
            '    Display a popup message.
            NPCOldState = 0
            globalNPCStatus = False
            globalNPCOldStatus = globalNPCStatus
            Beep()
            myPrompt = "On " + SystemUTCTime + " (UTC)" + vbCrLf
            myPrompt = myPrompt + "Error in getting Node Power Controller status over network in Function LoadDataVersionWithCriticalCodeProtected()." + vbCrLf + vbCrLf
            myPrompt = myPrompt + "Possible reasons include the following:" + vbCrLf
            myPrompt = myPrompt + "1. Server could be offline." + vbCrLf
            myPrompt = myPrompt + "2. Network cable could be disconnected." + vbCrLf + vbCrLf
            myPrompt = myPrompt + "Exact text of exception error information is as follows:" + vbCrLf
            myPrompt = myPrompt + ex.ToString() + vbCrLf

            Call ShowMessage(myPrompt)

            globalLastReqestSoapCount = 9999
        End Try

        'display the initial NPC status on the events log
        Call AddAlarmLineToDataGrid(SystemUTCTime, 0, 0, 0, 8)

        'There are 7 48V internal loads
        'If globalNPCStatus = True And NPCState = 1 And LoginType = 1 Then
        For i = 0 To 6
            '48V internal loads starts from channel 10
            IndexString = CStr(i + 10)
            myString = "/1/internal/" + IndexString

            'Set the parameters to default values
            IntLoads48(i).Change = False
            IntLoads48(i).ChangeType = 0
            IntLoads48(i).LoadOldCurrentLimit = IntLoads48(i).DefaultCurrentLimit
            IntLoads48(i).LoadOldState = 0

            'comment out on 03-15-2005 due to checkGF() conflict
            'Call setLoad() to set the default current limit
            myIntLoadUpdateType.name = IntLoads48(i).LoadName
            'result = ws.setLoad(myString, myIntLoadUpdateType)
        Next

        'There are 7 12V internal loads
        For i = 0 To 6
            '12V internal loads starts from channel 3
            IndexString = CStr(i + 3)
            myString = "/1/internal/" + IndexString

            'Set the parameters to default values
            IntLoads12(i).Change = False
            IntLoads12(i).ChangeType = 0
            IntLoads12(i).LoadOldCurrentLimit = IntLoads12(i).DefaultCurrentLimit
            IntLoads12(i).LoadOldState = 0

            'comment out on 03-15-2005 due to checkGF() conflict
            'Call setLoad() to set the default current limit
            myIntLoadUpdateType.name = IntLoads12(i).LoadName
            'result = ws.setLoad(myString, myIntLoadUpdateType)
        Next

        'There are 2 5V internal loads
        For i = 0 To 1
            '12V internal loads starts from channel 3
            IndexString = CStr(i + 1)
            myString = "/1/internal/" + IndexString

            'Set the parameters to default values
            IntLoads5(i).Change = False
            IntLoads5(i).ChangeType = 0
            IntLoads5(i).LoadOldCurrentLimit = IntLoads5(i).DefaultCurrentLimit
            IntLoads5(i).LoadOldState = 0

            'comment out on 03-15-2005 due to checkGF() conflict
            'Call setLoad() to set the default current limit
            myIntLoadUpdateType.name = IntLoads5(i).LoadName
            'result = ws.setLoad(myString, myIntLoadUpdateType)

            'initialize the maximum number of rows to be 7200
            ShoreMaxRowNumber = 7200
            ScienceMaxRowNumber = 7200
            SEMaxRowNumber = 7200

            'show the main form
            PMACSmain.DefInstance.Show()
        Next
    End Sub
#End Region

#Region "Closing PMACS"
    '**********************************************************************
    ' Closing the PMACSstartup window would terminate PMACS
    '**********************************************************************
    Public Sub PMACSstartup_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        Dim mstrName As Object
        Dim response As Short

        'ask the user to confirm the program termination
        response = MsgBox(" Quit Program?", MsgBoxStyle.Exclamation + MsgBoxStyle.YesNo, "Exiting " & mstrName)
        If response = MsgBoxResult.Yes Then
            wantAbortGfCheckThread = True 'jbe new: If true it tells the GF worker thread to abort itself.
            System.Windows.Forms.Application.DoEvents() 'jbe: Want to make sure GF check worker thread gets some CPU time to terminate.
            End
        Else
            e.Cancel = True
        End If
    End Sub
#End Region
    
#Region "Menu items"
    '***************************************************
    'Menu items for opening child windows
    '***************************************************
    Private Sub mnuMain_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuMain.Click
        PMACSmain.DefInstance.Show()
    End Sub

    Private Sub mnuShore_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuShore.Click
        PMACSshore.DefInstance.Show()
    End Sub

    Private Sub mnuExtLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuExtLoad.Click
        PMACSextload.DefInstance.Show()
    End Sub

    Private Sub mnuIntLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuIntLoad.Click
        PMACSintload.DefInstance.Show()
    End Sub

    Private Sub mnuEvents_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuEvents.Click
        PMACSalarm.DefInstance.Show()
    End Sub
#End Region

End Class
