'#Uses "..\include\Const.inc"
'#Uses "..\include\Global.inc"
'#Uses "..\include\Format.inc"
'#Uses "..\include\Port.inc"
'#Uses "..\classes\FunctionClass.cls
'#Uses "..\classes\ParameterClass.cls
'#Uses "..\classes\Port.cls
'#Uses "..\classes\PortPin.cls
'#Uses "Include.inc"
Option Explicit

'*****************************************************************************
' Module:
'        IO
'-----------------------------------------------------------------------------
' Description:
'        This file contains functions which are create controls for this
'        module.
'        Furthermore it contains functions for the event handling of
'        these controls.
'
'-----------------------------------------------------------------------------
' History:
'                 
'        Rev. Author         Date        Description
'        ---------------------------------------------------------------------
'        1.0  ste            02.02.00    final version for TC10GP
'             ste            23.02.00    many changes for TC1775
'             
'        ---------------------------------------------------------------------
'        3.0  ahe            02.02.00    final version for C161PI
'                                        - added register PDCR
'                                        - changes 'As PortPin' to 'As Object'
'
'        ---------------------------------------------------------------------
'        4.0  ahe            23.05.01    final version for Pegasus
'                                         - changes the notes of each port
'                                         - changes ALTESL set's
'
'*****************************************************************************

'*****************************************************************************
' @bfunc   Public | StartGenerateCode | Boolean|
'
'-----------------------------------------------------------------------------
'          This functions initiates the code generation for the IO module.
'
'-----------------------------------------------------------------------------
' @rdesc   one of the following values
' @flag    True | all functions called successfull and code is generated
' @flag    False| else
'
'-----------------------------------------------------------------------------
' @bparm   | r | ProjectData | set of the registers
' @bparm   | vIndex | Variant | parameter for the codegenerator
'
'*****************************************************************************
Function StartGenerateCode(r As ProjectData, vIndex As Variant) As Boolean
    On Error GoTo StartGenerateCodeError
    StartGenerateCode = False

    ' write files IO.h
    If (r.v("IO_USE_Init")) Then
      If (Not IOGenerateH(r)) Then Exit Function
	 	   If (Not r.AddFile(r.s("IO_HFILE"), "H")) Then Exit Function
    End if

    ' write file IO.c
    If (r.v("IO_USE_Init")) Then
      If (Not IOGenerateC(r)) Then Exit Function
	 	   If (Not r.AddFile(r.s("IO_CFILE"), "C")) Then Exit Function
    End if

        
    StartGenerateCode = True
    Exit Function
    
StartGenerateCodeError:
    Errorbox("Code generation for IO failed", Error$)
    Exit Function
End Function


'*****************************************************************************
' @bfunc   Public | IOGenerateC | Boolean |
'
'-----------------------------------------------------------------------------
'          Generates the code for the IO.c file.
'
'-----------------------------------------------------------------------------
' @rdesc   one of the following values
' @flag    True | generation was successfull
' @flag    False| else
'
'-----------------------------------------------------------------------------
' @bparm   | r | ProjectData | set of the registers
'
'*****************************************************************************
Function IOGenerateC(r As ProjectData) As Boolean
    On Error GoTo IOGenerateCError
    
    Dim vIndex As Variant
    Dim sIndex As String
    Dim i As Integer
    Dim f As Variant
    Dim v As Variant
    Dim d As String
    Dim sName As String
    Dim dc As DAvECollection
    Dim uc As UserCode
    Dim func As FunctionClass
    Dim cPort As DAvECollection
    Dim Port As Port
    Dim cPins As Object
    Dim sPin As String
    Dim iPin As Integer
    Dim iByte As Integer
    Dim iNible As Integer
    Dim sPort As String
    Dim vPort As Variant
    Dim l As Long
    Dim sAlternateName As String

    Dim lDIRx As Long
    Dim lODx As Long
    Dim lALTSEL0x As Long
    Dim lALTSEL1x As Long
    Dim lPUDSELx As Long
    Dim lPUDENx As Long
    Dim lOUTx As Long
    Dim lPICONx As Long
    Dim lPOCONx As Long
    Dim bIsGeneralInput As Boolean
    Dim bIsGeneralOutput As Boolean
    Dim bIsAlternateInput As Boolean
    Dim bIsAlternateOutput As Boolean
    Dim lUnusedPins As Long

    Dim sDirectionReg As String
    Dim sOpenDrainReg As String
    Dim sOutputReg As String
    Dim sPullupPulldownEnableReg As String
    Dim sPullupPulldownSelectReg As String
    Dim sOutputDriverEnableReg As String
    Dim sAlternateSelect0Reg As String
    Dim sAlternateSelect1Reg As String
    Dim sInputConfigurationReg As String
    Dim sOutputEdgeCharcReg As String
    Dim sOutputDriverCharcReg As String

    IOGenerateC = False

    Set dc = ObjectCollection("MODULENAMES")
    Set uc = New UserCode
    Set func = New  FunctionClass
    Set cPort = ObjectCollection("PORTS")
    Set cPins = ObjectCollection("PORTPINS")

    sIndex = "IO" ' & vIndex

    'refresh the decriptions of the functions and macros  
    RefreshFunctionDescriptions(vIndex, func, r)

    'read usercode
    uc.ReadFile((StripFilenameAndExtension(r.LoadedFile)) & "\" & r.v("IO_CFILE"))

    'open IO.c
    f = FreeFile
    Open CStr(StripFilenameAndExtension(r.LoadedFile)) & "\" & r.v("IO_CFILE") For Output As f
    
    '------------------------------------------------------------------------------------------------
    ' module header
    '------------------------------------------------------------------------------------------------
    d = FormatModuleDescription(GetModuleHeaderC(sIndex))
    Print #f, Rtf.GenerateModuleHeader(DefGetValue("ProductVersion"), StripPath(r.LoadedFile), dc(sIndex).ModuleDescription, r.v(sIndex & "_CFILE"), r.v("MAIN_CPU_TYPE"), r.v("MAIN_COMPILER"), d)

            Print #f, uc.GetUserCode("(IO_General,1)",0)    'USER CODE for application specific descriptions'
            Print #f, ""

          ' do for each port in the system
          For Each Port In cPort
              If Not(r.v("IO_P" & Port.PortNumber & "_Notes")= "") Then
                  Print #f, Rtf.GenerateNote("Notes for Port P" & Port.PortNumber & ":" & vbcrlf & r.v("IO_P" & Port.PortNumber & "_Notes"))
              End If
          Next Port
            Print #f, Rtf.GenerateNote((r.v("IO_Notes")))
            Print #f, ""
            Print #f, SECTION_PROJECT_INCLUDES
            Print #f, ""  'DAvE includes'
            Print #f, "#include """ & r.v("MAIN_HFile") & """"
            Print #f, ""
            Print #f, uc.GetUserCode("(IO_General,2)",0)
            Print #f, ""
            Print #f, ""
            Print #f, SECTION_MACROS
            Print #f, ""  'DAvE local macro definitions'
            Print #f, uc.GetUserCode("(IO_General,3)",0)
            Print #f, ""
            Print #f, ""
            Print #f, SECTION_DEFINES
            Print #f, ""  'DAvE local #define definitions'
            Print #f, uc.GetUserCode("(IO_General,4)",0)
            Print #f, ""
            Print #f, ""
            Print #f, SECTION_TYPEDEFS
            Print #f, ""  'DAvE type defintions'
            Print #f, uc.GetUserCode("(IO_General,5)",0)
            Print #f, ""
            Print #f, ""
            Print #f, SECTION_IMPORTED_GLOBAL_VARIABLES
            Print #f, ""  'DAvE external declarations of imported global variables'
            Print #f, uc.GetUserCode("(IO_General,6)",0)
            Print #f, ""
            Print #f, ""
            Print #f, SECTION_GLOBAL_VARIABLES
            Print #f, ""  'DAvE definitions of global variables'
            Print #f, uc.GetUserCode("(IO_General,7)",0)
            Print #f, ""
            Print #f, ""
            Print #f, SECTION_EXTERNAL_PROTOTYPES
            Print #f, ""  'DAvE external declarations of imported functions'
            Print #f, uc.GetUserCode("(IO_General,8)",0)
            Print #f, ""
            Print #f, ""
            Print #f, SECTION_LOCAL_PROTOTYPES
            Print #f, ""  'DAvE declarations of internal local functions'
            Print #f, uc.GetUserCode("(IO_General,9)",0)
            Print #f, ""
            Print #f, ""
    '------------------------------------------------------------------------------------------------
    ' IO_vInit function
    '------------------------------------------------------------------------------------------------
    sName = "Init"
    If (r.v("IO_USE_" & sName) = 1) Then
    Print #f, FormatFunctionHeader(r, func, "IO_NAME_" & sName)        
            Print #f, uc.GetUserCode("(IO_Function,1)",0)      'USER CODE for application specific descriptions'
            Print #f, ""
                      '<--                     max. 78 characters                                -->'
            Print #f, FormatFunctionDeclaration(r, func, "IO_NAME_" & sName)
            Print #f, "{"
            Print #f, uc.GetUserCode("(IO_Function,2)",2) 
            Print #f, ""

    '------------------------------------------------------------------------------------------------
    ' Temperature Compensation:
    '------------------------------------------------------------------------------------------------
    d = "PTCR"
    If (r.Regs.SfrFind(d) = True) Then
      Print #f, FormatSectionHeader(2, 1, "Temperature Compensation:")
      If (r.v("PTCR_TCS") = 0) Then
        d = "port logic is controlled by the temperature compensation sensor"
        Print #f, FormatCommentsForSource(2, 1, d)    
      Else
        d = "port logic is controlled by software via bitfield TCC"
        Print #f, FormatCommentsForSource(2, 1, d)    
        d = "compensation mode: "
        Select Case r.v("PTCR_TCC")
          Case 0
            d = d & "low (-40C to 0C)"
          Case 1
            d = d & "normal (0C to 60C)"
          Case 2
            d = d & "high (60C to 125C)"
          Case 3
            d = d & "very high (125C to 150C)"
        End Select
        Print #f, FormatCommentsForSource(2, 1, d)    
      End If
      Print #f, ""

      d = "PTCR"
      Print #f, FormatCodeStatemente(2, d, "=", FormatTextOutput(r.sfr(d), "H4"), "load port temperature control register")
      Print #f, ""
    End If

    '------------------------------------------------------------------------------------------------
    ' Temperature Compensation:
    '------------------------------------------------------------------------------------------------
    d = "PDCR"
    If (r.Regs.SfrFind(d) = True) Then
      Print #f, FormatSectionHeader(2, 1, "Port Driver Control for Ports P0, P1, P4 and Pins P6.4-0, #RD, #WR, ALE, CLKOUT, #BHE/#WRH and #READY (emulation mode only):")
      If (r.v("PDCR_BIPEC") = 0) Then
        d = "Fast edge mode, rise/fall times depend on the drivers dimensioning"
        Print #f, FormatCommentsForInit(1, d)    
      Else
        d = "Reduced edge mode"
        Print #f, FormatCommentsForInit(1, d)    
      End If
      Print #f, ""

      Print #f, FormatSectionHeader(2, 1, "Port Driver Control for Ports P2, P3 and pins P6.7-5 and #RSTOUT:")
      If (r.v("PDCR_NBPEC") = 0) Then
        d = "Fast edge mode, rise/fall times depend on the drivers dimensioning"
        Print #f, FormatCommentsForInit(1, d)    
      Else
        d = "Reduced edge mode"
        Print #f, FormatCommentsForInit(1, d)    
      End If
      Print #f, ""

      d = "PDCR"
      Print #f, FormatCodeStatemente(2, d, "=", FormatTextOutput(r.sfr(d), "H4"), "load port driver control register")
      Print #f, ""
    End If

    '------------------------------------------------------------------------------------------------
    ' General Port Settings:
    '------------------------------------------------------------------------------------------------
    Print #f, FormatSectionHeader(2, 1, "General Port Settings:")

    '-----------------------------------------------------------------
    ' Code statements for the InputConfiguration register for all ports together
    '-----------------------------------------------------------------
      d = "PICON"
      If (r.Regs.SfrFind(d) = True) Then
        Print #f, FormatCodeStatemente(2, d, "=", FormatTextOutput(r.sfr(d), "H4"), "load input configuration register")
      End If

    '-----------------------------------------------------------------
    ' Code statements for the OutputConfiguration x register for all ports together (x = 0-2)
    '-----------------------------------------------------------------
'      For i = 0 To 2
'        d = "CPC_POCON" & i
'          If (r.Regs.SfrFind(d) = True) Then
'            Print #f, FormatCodeStatemente(2, d, "=", FormatTextOutput(r.sfr(d), "H4"), "load output configuration register" & i)
'          End If
'      Next i

    Print #f, ""


    ' do for each port in the system
    For Each Port In cPort
      lDIRx = 0
      lODx = 0
      lALTSEL0x = 0
      lALTSEL1x = 0
      lPUDSELx = 0
      lPUDENx = 0
      lOUTx = 0
      lPICONx = 0
      lPOCONx = 0
      vPort = Port.PortNumber 
      sPort = "P" & vPort
      lUnusedPins = 0
      '------------------------------------------------------------------------------------------------
      ' Configuration of Port x:
      '------------------------------------------------------------------------------------------------
      Print #f, FormatSectionHeader(2, 1, "Configuration of Port " & sPort & ":")

      ' do for each pin of port x
      For iPin = Port.FirstPin To Port.LastPin
        sDirectionReg = GetDirectionRegName(vPort, iPin)
        sOpenDrainReg = GetOpenDrainRegName(vPort, iPin)
        sOutputReg = GetOutputRegName(vPort, iPin)
        sPullupPulldownEnableReg = GetPullupPulldownEnableRegName(vPort, iPin)
        sPullupPulldownSelectReg = GetPullupPulldownSelectRegName(vPort, iPin)
        sOutputDriverEnableReg = GetOutputDriverEnableRegName(vPort, iPin)
        sAlternateSelect0Reg = GetAlternateSelect0RegName(vPort, iPin)
        sAlternateSelect1Reg = GetAlternateSelect1RegName(vPort, iPin)

        bIsGeneralInput = False
        bIsGeneralOutput = False
        bIsAlternateInput = False
        bIsAlternateOutput = False
        sPin = sPort & "_" & iPin

        If (cPins.Use(sPin) = TRUE) Then  ' is the pin availible

          '-----------------------------------------------------------------
          ' Comments for the General pin function
          '-----------------------------------------------------------------
          Select Case (r.v("MuxFor_" & sPin))
            Case 2  ' pin is general output
                     bIsGeneralOutput = True
                     d = sPort & "." & iPin & " is used as general purpose output"
                     Print #f, FormatCommentsForSource(2, 1, d)    
 
            Case 1  ' pin is general input
                     bIsGeneralInput = True
                     d = sPort & "." & iPin & " is used as general input"
                     Print #f, FormatCommentsForSource(2, 1, d)    
          End Select

          '-----------------------------------------------------------------
          ' Comments for the Alternate pin function
          '-----------------------------------------------------------------
          ' do for each alternate pin function of pin x
        	For l = 1 To cPins.AlternateNameCount(sPin)
            sAlternateName = cPins.AlternateName(sPin, l)
            Select Case (r.v("MuxFor_" & sAlternateName))
              Case 2  ' pin is alternate output
                     bIsAlternateOutput = True
                     d = sPort & "." & iPin & " is used as alternate output for the " & cPins.AlternateDescription(sAlternateName)
                     Print #f, FormatCommentsForSource(2, 1, d)    
'                     Exit For

              Case 1  ' pin is alternate input
                     bIsAlternateInput = True
                     d = sPort & "." & iPin & " is used as alternate input for the " & cPins.AlternateDescription(sAlternateName)
                     Print #f, FormatCommentsForSource(2, 1, d)    
            End Select
         	Next l

          ' checks if the pin is currently used
          If (bIsAlternateOutput = False AND bIsGeneralOutput = False AND bIsAlternateInput = False AND bIsGeneralInput = False) Then
            ' pin x is not used 
            lUnusedPins = lUnusedPins + 1
          End If
        
          '-----------------------------------------------------------------
          ' Comments for the Direction register for each pin
          '-----------------------------------------------------------------
          ' the direction register is only set for general outputs (alternate outputs are set in their own 
          ' initialization function)
          If (bIsGeneralOutput) Then
            If (r.Regs.BitFind(sDirectionReg) = True) Then
              If (r.v(sDirectionReg) = 1) Then
                lDIRx = lDIRx + 2 ^ iPin
              End If
            End If
          End If

          '-----------------------------------------------------------------
          ' Comments for the OpenDrain register for each pin
          '-----------------------------------------------------------------
          ' the open-drain register is set for both general AND alternate outputs
          If (bIsAlternateOutput Or bIsGeneralOutput) Then
            If (r.Regs.BitFind(sOpenDrainReg) = True) Then
              If (r.v(sOpenDrainReg) = 1) Then
                lODx = lODx + 2 ^ iPin
                d = "open drain output is selected"
              Else
                d = "push/pull output is selected"
              End If
              Print #f, FormatCommentsForInit(1, d)    
            End If
          End If

          '-----------------------------------------------------------------
          ' Comments for the DataOutput register for each pin
          '-----------------------------------------------------------------
          ' the output register is set only for general outputs
          If (bIsGeneralOutput) Then
            If (r.Regs.BitFind(sOutputReg) = True) Then
              If (r.v(sOutputReg) = 1) Then
                lOUTx = lOUTx + 2 ^ iPin
                d = "the pin status is high level"
              Else
                d = "the pin status is low level"
              End If
              Print #f, FormatCommentsForInit(1, d)    
            End If
          End If

          '-----------------------------------------------------------------
          ' Comments for the PullupPulldownEnable and Select register for each pin
          '-----------------------------------------------------------------
          ' the pullup/pulldown select and enable register is set for both general AND alternate inputs
          If (bIsAlternateInput OR bIsGeneralInput) Then  
            If (r.Regs.BitFind(sPullupPulldownEnableReg) = True) Then
              If (r.v(sPullupPulldownEnableReg) = 1) Then
                lPUDENx = lPUDENx + 2 ^ iPin
                If (r.Regs.BitFind(sPullupPulldownSelectReg) = True) Then
                  If (r.v(sPullupPulldownSelectReg) = 1) Then
                       d = "pull-up device is assigned"
                       lPUDSELx = lPUDSELx + 2 ^ iPin
                  Else
                       d = "pull-down device is assigned"
                  End If
                End If
              Else
                  d = "pull device is disabled (tristate) "
              End If
              Print #f, FormatCommentsForInit(1, d)    
            End If
          End If

          ' the alternate output register 0 and 1 is only set for general outputs (alternate outputs are 
          ' set in their own initialization function). Both registers are 0 if the pin is used as general
          ' output so nothing is to do here !!
          If (bIsGeneralOutput) Then
            If (r.Regs.BitFind(sAlternateSelect0Reg) = True) Then
              If (r.v(sAlternateSelect0Reg) = 1) Then
                lALTSEL0x = lALTSEL0x + 2 ^ iPin
              End If
            End If
            If (r.Regs.BitFind(sAlternateSelect1Reg) = True) Then
              If (r.v(sAlternateSelect1Reg) = 1) Then
                lALTSEL1x = lALTSEL1x + 2 ^ iPin
              End If
            End If
          End If


          '-----------------------------------------------------------------
          ' Comments for the InputThresholdType register for each pin
          '-----------------------------------------------------------------
          ' the input configuration register is set for both general AND alternate inputs
          If (bIsAlternateInput OR bIsGeneralInput) Then  
            If (cPort("P" & vPort).InputThresholdType = 1) Then ' for each pin
                sInputConfigurationReg = GetInputConfigurationRegNamePinwise(vPort, iPin)
                If (r.Regs.BitFind(sInputConfigurationReg) = True) Then
                  d = "input threshold type: "
                  If (r.v(sInputConfigurationReg) = 1) Then
                    d = d & "CMOS-like input"
                  Else
                    d = d & "TTL input"
                  End If
                  Print #f, FormatCommentsForInit(1, d)    
                End If
            End If
          End If

          '-----------------------------------------------------------------
          ' Comments for the OutputEdgeCharacteristic register for each pin
          '-----------------------------------------------------------------
          ' the output edge characteristic register is set for both general AND alternate outputs
          If (bIsAlternateOutput OR bIsGeneralOutput) Then  
            If (cPort("P" & vPort).OutputEdgeType = 1) Then ' for each pin
                sOutputEdgeCharcReg = GetOutputEdgeCharcRegNamePinwise(vPort, iPin)
                If (r.Regs.BitFind(sOutputEdgeCharcReg) = True) Then
                  d = "output edge characteristic: "
                  If (r.v(sOutputEdgeCharcReg) = 1) Then
                    d = d & "slow timing"
                  Else
                    d = d & "normal timing"
                  End If
                  Print #f, FormatCommentsForInit(1, d)    
                End If
            End If
          End If

          '-----------------------------------------------------------------
          ' Comments for the OutputDriverCharacteristic register for each pin
          '-----------------------------------------------------------------
          ' the output driver characteristic register is set for both general AND alternate outputs
          If (bIsAlternateOutput OR bIsGeneralOutput) Then  
            If (cPort("P" & vPort).OutputDriverType = 1) Then ' for each pin
                sOutputDriverCharcReg = GetOutputDriverCharcRegNamePinwise(vPort, iPin)
                If (r.Regs.BitFind(sOutputDriverCharcReg) = True) Then
                  d = "output driver characteristic: "
                  Select Case (r.v(sOutputDriverCharcReg))
                      Case 0
                          d = d & "high current mode"
                      Case 1
                          d = d & "dynamic current mode"
                      Case 2
                          d = d & "low current mode"
                  End Select
                  Print #f, FormatCommentsForInit(1, d)    
                End If
            End If
          End If

          '-----------------------------------------------------------------
          ' Comments for the OutputDriverEnable register for each pin
          '-----------------------------------------------------------------
          ' the pad hold register is set only for general outputs
          If (bIsGeneralOutput) Then
            If (r.Regs.BitFind(sOutputDriverEnableReg) = True) Then
              If (r.v(sOutputDriverEnableReg) = 1) Then
                d = "enable output driver in power down mode"
              Else
                d = "disable output driver in power down mode"
              End If
              Print #f, FormatCommentsForInit(1, d)    
            End If
          End If
        Else

          lUnusedPins = lUnusedPins + 1 'for not evalible pins

        End If  ' if pin is availible       
      Next iPin ' for each pin of the port


      ' check if no pin of the port should be used
      If (lUnusedPins = (Port.LastPin - Port.FirstPin + 1)) Then
        d = "no pin of port "  & sPort & " is used"
        Print #f, FormatCommentsForInit(1, d)    
      Else
        '-----------------------------------------------------------------
        ' Comments for the InputThresholdType register for each nible, byte or port
        '-----------------------------------------------------------------
        Select Case (cPort("P" & vPort).InputThresholdType)
            Case 1  ' for each pin

            Case 2  ' for each nible
                Print #f, ""   
                For iNible = 0 To 3
                  sInputConfigurationReg = GetInputConfigurationRegNameNiblewise(vPort, iNible)
                  If (r.Regs.BitFind(sInputConfigurationReg) = True) Then
                    d = "P" & vPort & "." & 4 * iNible & " - P" & vPort & "." & 3 + 4 * iNible & " threshold type: "
                    If (r.v(sInputConfigurationReg) = 1) Then
                      d = d & "CMOS-like input"
                    Else
                      d = d & "TTL input"
                    End If
                    Print #f, FormatCommentsForSource(2, 1, d)    
                  End If
                Next iNible

            Case 3  ' for each byte
                Print #f, ""   
                For iByte = 0 To 1
                  sInputConfigurationReg = GetInputConfigurationRegNameBytewise(vPort, iByte)
                  If (r.Regs.BitFind(sInputConfigurationReg) = True) Then
                    d = "P" & vPort & "." & 8 * iByte & " - P" & vPort & "." & 7 + 8 * iByte & " threshold type: "
                    If (r.v(sInputConfigurationReg) = 1) Then
                      d = d & "CMOS-like input"
                    Else
                      d = d & "TTL input"
                    End If
                    Print #f, FormatCommentsForSource(2, 1, d)    
                  End If
                Next iByte

            Case 4  ' for each port
                Print #f, ""   
                sInputConfigurationReg = GetInputConfigurationRegNamePortwise(vPort)
                If (r.Regs.BitFind(sInputConfigurationReg) = True) Then
                  d = "P" & vPort &  " threshold type: "
                  If (r.v(sInputConfigurationReg) = 1) Then
                    d = d & "CMOS-like input"
                  Else
                    d = d & "TTL input"
                  End If
                  Print #f, FormatCommentsForSource(2, 1, d)    
                End If
        End Select

        '-----------------------------------------------------------------
        ' Comments for the OutputDriverCharacteristic register for each nible, byte or port
        '-----------------------------------------------------------------
        Select Case (cPort("P" & vPort).OutputDriverType)
            Case 1  ' for each pin

            Case 2  ' for each nible
                Print #f, ""   
                For iNible = 0 To 3
                  sOutputDriverCharcReg = GetOutputDriverCharcRegNameNiblewise(vPort, iNible)
                  If (r.Regs.BitFind(sOutputDriverCharcReg) = True) Then
                    d = "P" & vPort & "." & 4 * iNible & " - P" & vPort & "." & 3 + 4 * iNible & " output driver characteristic: "
'                    Select Case (r.v(sOutputDriverCharcReg))
                    If (r.v(sOutputDriverCharcReg) = 0 Or _
                        r.v(sOutputDriverCharcReg) = 1 Or _
                        r.v(sOutputDriverCharcReg) = 2) Then
                            d = d & "strong driver"
                    ElseIf (r.v(sOutputDriverCharcReg) = 3 Or r.v(sOutputDriverCharcReg) = 7) Then
                            d = d & "weak driver"
                    ElseIf (r.v(sOutputDriverCharcReg) = 4 Or _
                            r.v(sOutputDriverCharcReg) = 5 Or _
                            r.v(sOutputDriverCharcReg) = 6) Then
                            d = d & "medium driver"
                    End If
                    Print #f, FormatCommentsForSource(2, 1, d)    
                  End If
                Next iNible

            Case 3  ' for each byte

            Case 4  ' for each port

        End Select

        '-----------------------------------------------------------------
        ' Comments for the OutputEdgeCharacteristic register for each nible, byte or port
        '-----------------------------------------------------------------
        Select Case (cPort("P" & vPort).OutputEdgeType)
            Case 1  ' for each pin

            Case 2  ' for each nible
                Print #f, ""   
                For iNible = 0 To 3
                  sOutputEdgeCharcReg = GetOutputEdgeCharcRegNameNiblewise(vPort, iNible)
                  If (r.Regs.BitFind(sOutputEdgeCharcReg) = True) Then
                    d = "P" & vPort & "." & 4 * iNible & " - P" & vPort & "." & 3 + 4 * iNible & " output edge characteristic: "
                    If (r.v(sOutputEdgeCharcReg) = 0 Or r.v(sOutputEdgeCharcReg) = 4) Then
                      d = d & "sharp edge mode"
                    ElseIf (r.v(sOutputEdgeCharcReg) = 1 Or r.v(sOutputEdgeCharcReg) = 5) Then
                      d = d & "medium edge mode"
                    ElseIf (r.v(sOutputEdgeCharcReg) = 2 Or r.v(sOutputEdgeCharcReg) = 6) Then
                      d = d & "soft edge mode"
                    Else
                      d = d & "no edge mode"
                    End If
                    Print #f, FormatCommentsForSource(2, 1, d)    
                  End If
                Next iNible

            Case 3  ' for each byte

            Case 4  ' for each port

        End Select
      End If  ' check if no pin of the port should be used


      '-----------------------------------------------------------------
      '-----------------------------------------------------------------
      ' Begin Code statements for each port
      '-----------------------------------------------------------------
      '-----------------------------------------------------------------
      Print #f, ""
      '-----------------------------------------------------------------
      ' Code statements for the Open Drain register for each port
      '-----------------------------------------------------------------
      d = "OD" & sPort
      If (r.Regs.SfrFind(d) = True) Then
        Print #f, FormatCodeStatemente(2, d, "=", FormatTextOutput(lODx, "H4"), "load open-drain register")
      End If

      '-----------------------------------------------------------------
      ' Code statements for the DataOutput register for each port
      '-----------------------------------------------------------------
      d = sPort & "_OUT"
      If (r.Regs.SfrFind(d) = True) Then
        Print #f, FormatCodeStatemente(2, d, "=", FormatTextOutput(lOUTx, "H4"), "load data output register")
      End If

      '-----------------------------------------------------------------
      ' Code statements for the Data register for each port
      '-----------------------------------------------------------------
      d = sPort
      If (r.Regs.SfrFind(d) = True) Then
        Print #f, FormatCodeStatemente(2, d, "=", FormatTextOutput(lOUTx, "H4"), "load data register")
      End If

      '-----------------------------------------------------------------
      ' Code statements for the PullupPulldownSelect register for each port
      '-----------------------------------------------------------------
      d = sPort & "_PUDSEL"
      If (r.Regs.SfrFind(d) = True) Then
        Print #f, FormatCodeStatemente(2, d, "=", FormatTextOutput(lPUDSELx, "H4"), "load pullup/pulldown select register")
      End If

      '-----------------------------------------------------------------
      ' Code statements for the PullupPulldownEnable register for each port
      '-----------------------------------------------------------------
      d = sPort & "_PUDEN"
      If (r.Regs.SfrFind(d) = True) Then
        Print #f, FormatCodeStatemente(2, d, "=", FormatTextOutput(lPUDENx, "H4"), "load pullup/pulldown enable register")
      End If

      '-----------------------------------------------------------------
      ' Code statements for the InputConfiguration register for each port
      '-----------------------------------------------------------------
      If (cPort("P" & vPort).InputThresholdType = 1) Then  ' for each pin
        d = "PICON"
        If (r.Regs.SfrFind(d) = True) Then
          Print #f, FormatCodeStatemente(2, d, "=", FormatTextOutput(r.sfr(d), "H4"), "load input configuration register")
        End If
      End If

      '-----------------------------------------------------------------
      ' Code statements for the AlternateSelect0 register for each port
      '-----------------------------------------------------------------
      d = "ALTSEL0" & sPort
      If (r.Regs.SfrFind(d) = True) Then
        Print #f, FormatCodeStatemente(2, d, "=", FormatTextOutput(lALTSEL0x, "H4"), "load alternate output function select register 0")
      End If

      '-----------------------------------------------------------------
      ' Code statements for the AlternateSelect1 register for each port
      '-----------------------------------------------------------------
      d = "ALTSEL1" & sPort
      If (r.Regs.SfrFind(d) = True) Then
        Print #f, FormatCodeStatemente(2, d, "=", FormatTextOutput(lALTSEL1x, "H4"), "load alternate output function select register 1")
      End If

      '-----------------------------------------------------------------
      ' Code statements for the OutputConfiguration x register for each port 
      '-----------------------------------------------------------------
      d = "POCON" & vPort
        If (r.Regs.SfrFind(d) = True) Then
          Print #f, FormatCodeStatemente(2, d, "=", FormatTextOutput(r.sfr(d), "H4"), "load output control register")
        End If

      '-----------------------------------------------------------------
      ' Code statements for the OutputDriverEnable register for each port
      '-----------------------------------------------------------------
      d = sPort & "_PHEN"
      If (r.Regs.SfrFind(d) = True) Then
        Print #f, FormatCodeStatemente(2, d, "=", FormatTextOutput(r.sfr(d), "H4"), "load output driver enable register")
      End If

      '-----------------------------------------------------------------
      ' Code statements for the Direction register for each port
      '-----------------------------------------------------------------
      d = "D" & sPort
      If (r.Regs.SfrFind(d) = True) Then
        Print #f, FormatCodeStatemente(2, d, "=", FormatTextOutput(lDIRx, "H4"), "load direction register")
      End If
      Print #f, ""
    Next Port


    Print #f, ""
    Print #f, uc.GetUserCode("(IO_Function,3)",2) 
    Print #f, ""
    Print #f, "} " & END_OF_FUNCTION & r.v("IO_NAME_" & sName)
    Print #f, ""
    Print #f, ""
    
    End If
    '------------------------------------------------------------------------------------------------
    ' Other function
    '------------------------------------------------------------------------------------------------

    Print #f, ""
    Print #f, ""
    Print #f, uc.GetUserCode("(IO_General,10)",0)
    Print #f, ""  

    'close file
    Close f
    
    IOGenerateC = True
    Exit Function
    
IOGenerateCError:
    Errorbox("Code generation for IO failed", Error$)
    Close f
    Exit Function
End Function


'*****************************************************************************
'Description:
'        Generates the code for the IO.h file.
'-----------------------------------------------------------------------------
'Parameters:
'        r                reference to the Registers object
'-----------------------------------------------------------------------------
'Returns:
'        True            on successfull operation
'        False           else
'*****************************************************************************
Function IOGenerateH(r As ProjectData) As Boolean
    On Error GoTo IOGenerateHError
    
    Dim vIndex As Variant
    Dim sIndex As String
    Dim i As Integer
    Dim f As Variant
    Dim d As String
    Dim sName As String
    Dim dc As DAvECollection
    Dim uc As UserCode
    Dim func As FunctionClass
    Dim para As ParameterClass
    Dim cPorts As DAvECollection
    Dim Port As Port
    Dim cPins As Object
    Dim sPin As String
    Dim iPin As Integer
    Dim n As String
    Dim sDirectionReg As String
   
    IOGenerateH = False

    Set dc = ObjectCollection("MODULENAMES")
    Set uc = New UserCode
    Set func = New  FunctionClass
    Set cPorts = ObjectCollection("PORTS")
    Set cPins = ObjectCollection("PORTPINS")
    Set para = New ParameterClass

    sIndex = "IO" ' & vIndex

    'refresh the decriptions of the functions and macros  
    RefreshFunctionDescriptions(vIndex, func, r)
    
    'refresh the decriptions of the parameters
    RefreshParameterDescriptions(vIndex, para, r)

    'read usercode
    uc.ReadFile((StripFilenameAndExtension(r.LoadedFile)) & "\" & r.v("IO_HFILE"))
    
    'open IO.h
    f = FreeFile
    Open CStr(StripFilenameAndExtension(r.LoadedFile)) & "\" & r.v("IO_HFILE") For Output As f
    
    '------------------------------------------------------------------------------------------------
    ' module header
    '------------------------------------------------------------------------------------------------
    d = FormatModuleDescription(GetModuleHeaderH(sIndex))
    Print #f, Rtf.GenerateModuleHeader(DefGetValue("ProductVersion"), StripPath(r.LoadedFile), dc(sIndex).ModuleDescription, r.v(sIndex & "_CFILE"), r.v("MAIN_CPU_TYPE"), r.v("MAIN_COMPILER"), d)
            
    Print #f, uc.GetUserCode("(IO_Header,1)",0)
    Print #f, ""
    Print #f, Rtf.GenerateNote((r.v("IO_Notes")))
    Print #f, ""
    Print #f, "#ifndef _" & StripExtension(r.v("IO_HFILE")) & "_H_"
    Print #f, "#define _" & StripExtension(r.v("IO_HFILE")) & "_H_"
    Print #f, ""
    Print #f, SECTION_PROJECT_INCLUDES
    Print #f, ""  'DAvE includes'
    Print #f, uc.GetUserCode("(IO_Header,2)",0)
    Print #f, ""
    Print #f, ""
    Print #f, SECTION_MACROS
    Print #f, ""  'DAvE global macro definitions; not used as functions'
    Print #f, uc.GetUserCode("(IO_Header,3)",0)
    Print #f, ""
    Print #f, ""
    Print #f, SECTION_DEFINES
    Print #f, ""  'DAvE global #define definitions'
    Print #f, "//----------------------------------------------------------------------------"
    Print #f, "// Defines for the parameter PinName"
    Print #f, "//----------------------------------------------------------------------------"
    Print #f, ""

    For Each Port In cPorts
      For iPin = 0 To 15
        sPin = "P" & Port.PortNumber & "_" & iPin
        If (cPins.Use(sPin) = TRUE) Then
            n = sPin
'            Print #f, FormatParameterStatement(r, para, sIndex & "_PARA_" & n, "P" & Port.PortNumber & "_P" & Port.PortNumber & "_" & iPin)
            Print #f, FormatParameterStatement(r, para, sIndex & "_PARA_" & n, "P" & Port.PortNumber & "_P" & iPin)
        End If
      Next iPin
      Print #f, ""
      'debug.print Port.PortName & "  " & Port.Description
    Next Port
    
    Print #f, ""
    Print #f, "//----------------------------------------------------------------------------"
    Print #f, "// Defines used by DAvE"
    Print #f, "//----------------------------------------------------------------------------"
    Print #f, ""

    For Each Port In cPorts
      For iPin = 0 To 15
        sPin = "P" & Port.PortNumber & "_" & iPin
        If (cPins.Use(sPin) = TRUE) Then
            'Print #f, "#define IN" & r.v("P" & Port.PortNumber & "_NAME_" & sPin) & "       ((T_Reg32 *) (PORT" & Port.PortNumber & "_BASE + 0x14))->bit" & iPin
'            Print #f, "#define IN" & r.v(sIndex & "_PARA_" & sPin) & "       P" & Port.PortNumber & "_P" & Port.PortNumber & "_" & iPin
            Print #f, "#define IN" & r.v(sIndex & "_PARA_" & sPin) & "       P" & Port.PortNumber & "_P" & iPin
        End If
      Next iPin
      Print #f, ""
      For iPin = 0 To 15
        sPin = "P" & Port.PortNumber & "_" & iPin
        sDirectionReg = GetDirectionRegName(Port.PortNumber, iPin)
        If (cPins.Use(sPin) = TRUE And r.Regs.BitFind(sDirectionReg) = True) Then
            'Print #f, "#define D" & r.v("P" & Port.PortNumber & "_NAME_" & sPin) & "       ((T_Reg32 *) (PORT" & Port.PortNumber & "_BASE + 0x18))->bit" & iPin
'            Print #f, "#define D" & r.v(sIndex & "_PARA_" & sPin) & "       DP" & Port.PortNumber & "_DP" & Port.PortNumber & "_" & iPin
            Print #f, "#define D" & r.v(sIndex & "_PARA_" & sPin) & "       DP" & Port.PortNumber & "_P" & iPin
        End If
      Next iPin
      Print #f, ""
    Next Port
    
    Print #f, uc.GetUserCode("(IO_Header,4)",0)
    Print #f, ""
    Print #f, ""
    Print #f, SECTION_TYPEDEFS
    Print #f, ""  'DAvE type definitions'
    Print #f, uc.GetUserCode("(IO_Header,5)",0)
    Print #f, ""
    Print #f, ""
    Print #f, SECTION_IMPORTED_GLOBAL_VARIABLES
    Print #f, ""  'DAvE external declarations of imported global variables'
    Print #f, uc.GetUserCode("(IO_Header,6)",0)
    Print #f, ""
    Print #f, ""
    Print #f, SECTION_GLOBAL_VARIABLES
    Print #f, ""  'DAvE definition of global variables'
    Print #f, uc.GetUserCode("(IO_Header,7)",0)
    Print #f, ""
    Print #f, ""
    Print #f, SECTION_GLOBAL_PROTOTYPES
    Print #f, ""  'DAvE declarations of functions which should become global'
    
    sName = "Init"
    If (r.v("IO_USE_" & sName) = 1) Then
      Print #f, FormatFunctionDeclaration(r, func, "IO_NAME_" & sName) & ";"
    End If
    
    Print #f, ""
    Print #f, ""
    Print #f, uc.GetUserCode("(IO_Header,8)",0)
    Print #f, ""
    Print #f, ""
                          'DAvE declarations of global macros'
    '------------------------------------------------------------------------------------------------
    ' IO_ubReadPin macro
    '------------------------------------------------------------------------------------------------
    sName = "ReadPin"
    If (r.v("IO_USE_" & sName) = 1) Then
      Print #f, FormatFunctionHeader(r, func, "IO_NAME_" & sName)        

      Print #f, "#define " & FormatFunctionDeclaration(r, func, "IO_NAME_" & sName) & " PinName"
      Print #f, ""
      Print #f, ""
    End If

    '------------------------------------------------------------------------------------------------
    ' IO_vSetPin macro
    '------------------------------------------------------------------------------------------------
    sName = "SetPin"
    If (r.v("IO_USE_" & sName) = 1) Then
      Print #f, FormatFunctionHeader(r, func, "IO_NAME_" & sName)        

      Print #f, "#define " & FormatFunctionDeclaration(r, func, "IO_NAME_" & sName) & " PinName = 1"
      Print #f, ""
      Print #f, ""
    End If

    '------------------------------------------------------------------------------------------------
    ' IO_vResetPin macro
    '------------------------------------------------------------------------------------------------
    sName = "ResetPin"
    If (r.v("IO_USE_" & sName) = 1) Then
      Print #f, FormatFunctionHeader(r, func, "IO_NAME_" & sName)        

      Print #f, "#define " & FormatFunctionDeclaration(r, func, "IO_NAME_" & sName) & " PinName = 0"
      Print #f, ""
      Print #f, ""
    End If

    '------------------------------------------------------------------------------------------------
    ' IO_vTogglePin macro
    '------------------------------------------------------------------------------------------------
    sName = "TogglePin"
    If (r.v("IO_USE_" & sName) = 1) Then
      Print #f, FormatFunctionHeader(r, func, "IO_NAME_" & sName)        

      Print #f, "#define " & FormatFunctionDeclaration(r, func, "IO_NAME_" & sName) & " PinName = !PinName"
      Print #f, ""
      Print #f, ""
    End If

    '------------------------------------------------------------------------------------------------
    ' IO_vSetPinIn macro
    '------------------------------------------------------------------------------------------------
    sName = "SetPinIn"
    If (r.v("IO_USE_" & sName) = 1) Then
      Print #f, FormatFunctionHeader(r, func, "IO_NAME_" & sName)        

      Print #f, "#define " & FormatFunctionDeclaration(r, func, "IO_NAME_" & sName) & " D##PinName = 0"
      Print #f, ""
      Print #f, ""
    End If

    '------------------------------------------------------------------------------------------------
    ' IO_vSetPinOut macro
    '------------------------------------------------------------------------------------------------
    sName = "SetPinOut"
    If (r.v("IO_USE_" & sName) = 1) Then
      Print #f, FormatFunctionHeader(r, func, "IO_NAME_" & sName)        

      Print #f, "#define " & FormatFunctionDeclaration(r, func, "IO_NAME_" & sName) & " D##PinName = 1"
      Print #f, ""
      Print #f, ""
    End If

    '------------------------------------------------------------------------------------------------
    ' IO_uwReadPort macro
    '------------------------------------------------------------------------------------------------
    sName = "ReadPort"
    If (r.v("IO_USE_" & sName) = 1) Then
      Print #f, FormatFunctionHeader(r, func, "IO_NAME_" & sName)        

      Print #f, "#define " & FormatFunctionDeclaration(r, func, "IO_NAME_" & sName) & " PortName
      Print #f, ""
      Print #f, ""
    End If

    '------------------------------------------------------------------------------------------------
    ' IO_vWritePort macro
    '------------------------------------------------------------------------------------------------
    sName = "WritePort"
    If (r.v("IO_USE_" & sName) = 1) Then
      Print #f, FormatFunctionHeader(r, func, "IO_NAME_" & sName)        

      Print #f, "#define " & FormatFunctionDeclaration(r, func, "IO_NAME_" & sName) & " PortName = uwData"
      Print #f, ""
      Print #f, ""
    End If

    '------------------------------------------------------------------------------------------------
    ' IO_vSetPortIn macro
    '------------------------------------------------------------------------------------------------
    sName = "SetPortIn"
    If (r.v("IO_USE_" & sName) = 1) Then
      Print #f, FormatFunctionHeader(r, func, "IO_NAME_" & sName)        

      Print #f, "#define " & FormatFunctionDeclaration(r, func, "IO_NAME_" & sName) & " D##PortName &= ~uwMask"
      Print #f, ""
      Print #f, ""
    End If

    '------------------------------------------------------------------------------------------------
    ' IO_vSetPortOut macro
    '------------------------------------------------------------------------------------------------
    sName = "SetPortOut"
    If (r.v("IO_USE_" & sName) = 1) Then
      Print #f, FormatFunctionHeader(r, func, "IO_NAME_" & sName)        

      Print #f, "#define " & FormatFunctionDeclaration(r, func, "IO_NAME_" & sName) & " D##PortName |= uwMask"
      Print #f, ""
      Print #f, ""
    End If

  
    Print #f, SECTION_INTERRUPT_VECTORS
    Print #f, ""  'DAvE interrupt vector definitions
    Print #f, uc.GetUserCode("(IO_Header,9)",0)
    Print #f, ""
    Print #f, ""
    Print #f, "#endif  // ifndef _" & StripExtension(r.v("IO_HFILE")) & "_H_"
    
    'close file
    Close f

    
    IOGenerateH = True
    Exit Function
    
IOGenerateHError:
    Exit Function
End Function
