Attribute VB_Name = "Module1"
'#Uses "..\include\Const.inc"
'#Uses "..\include\Global.inc"
'#Uses "..\include\Format.inc"
'#Uses "..\include\Port.inc"
'#Uses "..\classes\FunctionClass.cls
'#Uses "..\classes\Port.cls
'#Uses "..\classes\PortPin.cls
'#Uses "Include.inc"
Option Explicit
'*****************************************************************************
' Module:
'        IO
'-----------------------------------------------------------------------------
' Description:
'        This file contains functions for generating code for the
'        module 'IO'.
'
'-----------------------------------------------------------------------------
' History:
'
'        Rev. Author         Date        Description
'        ---------------------------------------------------------------------
'        0.1  Sunil          08-10-04     initial version
'        0.2  Sunil          15-11-04     definition of IO_NAME_TogglePin macro changed.
'                                         definition of IO_NAME_ReadPort macro changed.
'                                         definition of IO_NAME_WritePort macro changed.
'                                         direction register macro definitions removed.
'        0.3  Sunil          01-12-04     The port direction register setting instruction
'                                         corrected (input and output direction was reversed)
'        0.4  Sunil          18-01-05     Default values of PUDSEL and PUDEN registers are
'                                         changed according to ITS. (not zero)
'
'
'*****************************************************************************


'*****************************************************************************
'Description:
'        This functions initiates the code generation for the IO module.
'-----------------------------------------------------------------------------
'Parameters:
'        r                reference to the Registers object
'        vIndex           a parameter
'-----------------------------------------------------------------------------
'Returns:
'        True            on successful operation
'        False           else
'*****************************************************************************
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, vIndex)) 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, vIndex)) 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


'*****************************************************************************
'Description:
'        Generates the code for the IO.c file.
'-----------------------------------------------------------------------------
'Parameters:
'        r                reference to the Registers object
'        vIndex           a parameter
'-----------------------------------------------------------------------------
'Returns:
'        True            on successful operation
'        False           else
'*****************************************************************************
Function IOGenerateC(r As ProjectData, vIndex As Variant) As Boolean
    On Error GoTo IOGenerateCError
    
    Dim f As Variant
    Dim d As String
    Dim iPin As Integer
    Dim sPort As String
    Dim vPort As Variant
    Dim sPin As String
    Dim iAltNameIndex As Integer
    Dim sAlternateName As String
    Dim lUnusedPins As Long
    Dim iPageNumber As Integer
    
    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 iPage As Integer
    Dim sDirectionReg As String
    Dim sOpenDrainReg As String
    Dim sOutputReg As String
    Dim sPullupPulldownEnableReg As String
    Dim sPullupPulldownSelectReg As String
    
    Dim bIsGeneralInput As Boolean
    Dim bIsGeneralOutput As Boolean
    Dim bIsAlternateInput As Boolean
    Dim bIsAlternateOutput As Boolean
    
    Dim dc As DAvECollection
    Dim uc As UserCode
    Dim func As FunctionClass
    Dim cPort As DAvECollection
    'Dim cPins As PortPin
    Dim cPins As Object
    Dim Port As Port
    
    IOGenerateC = False

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

    'refresh the decriptions of the functions and macros
    Call RefreshFunctionDescriptions(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("IO"))
    Print #f, Rtf.GenerateModuleHeader(DefGetValue("ProductVersion"), StripPath(r.LoadedFile), dc("IO").ModuleDescription, r.v("IO_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, ""
            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
    '------------------------------------------------------------------------------------------------
    If (r.v("IO_USE_Init") = 1) Then
            Print #f, FormatFunctionHeader(r, func, "IO_NAME_Init")
            Print #f, uc.GetUserCode("(IO_Init,1)", 0)     'USER CODE for application specific descriptions'
            Print #f, ""
                      '<--                     max. 78 characters                                -->'
            Print #f, FormatFunctionDeclaration(r, func, "IO_NAME_Init")
            Print #f, "{"
            Print #f, uc.GetUserCode("(IO_Init,2)", 2)
            Print #f, ""
            
            Print #f, ""
            Print #f, FormatCommentsForSource(2, 1, "***********************************************************************")
            Print #f, FormatCommentsForSource(2, 1, "Note : All peripheral related IO configurations are done in the respective peripheral modules (alternate functions selection)")
            Print #f, FormatCommentsForSource(2, 1, "")
            Print #f, FormatCommentsForSource(2, 1, "If no pins are selected DAvE assumes that registers are in default settings")
            Print #f, FormatCommentsForSource(2, 1, "***********************************************************************")
            Print #f, ""
            ' variable to avoid unnecessary page switches
            iPageNumber = 0
            
            For Each Port In cPort
                lDIRx = 0
                lODx = 0
                lALTSEL0x = 0
                lALTSEL1x = 0
                
                lOUTx = 0
                vPort = Port.PortNumber
                sPort = "P" & vPort
                lPUDSELx = GetActualPUDSELDefaultValue(r, sPort)
                lPUDENx = GetActualPUDENDefaultValue(r, sPort)
                lUnusedPins = 0
                  
                '------------------------------------------------------------------------------------------------
                ' Configuration of Port x:
                '------------------------------------------------------------------------------------------------
                Print #f, FormatSectionHeader(2, 1, "Configuration of Port " & sPort & ":")
                
                For iPin = Port.FirstPin To Port.LastPin
                    sDirectionReg = sPort & "_DIR_P" & iPin
                    sOpenDrainReg = sPort & "_OD_P" & iPin
                    sOutputReg = sPort & "_DATA_P" & iPin
                    sPullupPulldownEnableReg = sPort & "_PUDEN_P" & iPin
                    sPullupPulldownSelectReg = sPort & "_PUDSEL_P" & 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 & ":"
                                    Print #f, FormatCommentsForSource(2, 1, d)
                                    If sPort = "P2" Then
                                        d = "is used as general purpose input"
                                        Print #f, FormatCommentsForInit(1, d)
                                        d = "input driver is disabeld"
                                        Print #f, FormatCommentsForInit(1, d)
                                    Else
                                        d = "is used as general purpose output"
                                        Print #f, FormatCommentsForInit(1, d)
                                    End If
                                    
                
                           Case 1  ' pin is general input
                                    bIsGeneralInput = True
                                    d = sPort & "." & iPin & ":"
                                    Print #f, FormatCommentsForSource(2, 1, d)
                                    d = "is used as general input"
                                    Print #f, FormatCommentsForInit(1, d)
                                    If sPort = "P2" Then
                                        d = "input driver is enabled"
                                        Print #f, FormatCommentsForInit(1, d)
                                    End If
                                    
                         End Select
                         
                         '-----------------------------------------------------------------
                        ' Comments for the Alternate pin function
                        '-----------------------------------------------------------------
                        ' do for each alternate pin function of pin x
                        For iAltNameIndex = 1 To cPins.AlternateNameCount(sPin)
                            sAlternateName = cPins.AlternateName(sPin, iAltNameIndex)
                            Select Case (r.v("MuxFor_" & sAlternateName))
                              Case 2  ' pin is alternate output
                                     bIsAlternateOutput = True
                                     ' if the pin is not used as general input  and not as alternate input
                                     If (bIsGeneralInput = False And bIsGeneralOutput = False And bIsAlternateInput = False) Then
                                       d = sPort & "." & iPin & ":"
                                       Print #f, FormatCommentsForSource(2, 1, d)
                                     End If
                                     d = "is used as alternate output for the " & cPins.AlternateDescription(sAlternateName)
                                     Print #f, FormatCommentsForInit(1, d)
                
                              Case 1  ' pin is alternate input
                                     bIsAlternateInput = True
                                     ' if the pin is not used as general input and not as alternate output
                                     If (bIsGeneralInput = False And bIsGeneralOutput = False And bIsAlternateOutput = False) Then
                                       d = sPort & "." & iPin & ":"
                                       Print #f, FormatCommentsForSource(2, 1, d)
                                     End If
                                     d = "is used as alternate input for the " & cPins.AlternateDescription(sAlternateName)
                                     Print #f, FormatCommentsForInit(1, d)
                            End Select
                        Next iAltNameIndex
                         
                    End If
                    
                    ' checks if the pin is currently used
                    If (bIsAlternateOutput = False And bIsGeneralOutput = False And bIsAlternateInput = False _
                            And bIsGeneralInput = False Or Not cPins.Use(sPin)) 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 sPort <> "P2" Then
                        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
                    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 (bIsAlternateOutput Or bIsGeneralOutput Or bIsAlternateInput Or bIsGeneralInput) Then
                      If (r.Regs.BitFind(sPullupPulldownEnableReg) = True) Then
                        If (r.v(sPullupPulldownEnableReg) = 1) Then
                          lPUDENx = lPUDENx Or 2 ^ iPin
                          If (r.Regs.BitFind(sPullupPulldownSelectReg) = True) Then
                            If (r.v(sPullupPulldownSelectReg) = 1) Then
                                 d = "pull-up device is assigned"
                                 lPUDSELx = lPUDSELx Or 2 ^ iPin
                            Else
                                 d = "pull-down device is assigned"
                                 lPUDSELx = lPUDSELx And (Not (2 ^ iPin))
                            End If
                          End If
                        Else
                            d = "pull device is disabled (tristate) "
                            lPUDENx = lPUDENx And (Not 2 ^ iPin)
                        End If
                        Print #f, FormatCommentsForInit(1, d)
                      End If
                    End If
        
                Next iPin
                
                ' 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)
                    End If
                
                '-----------------------------------------------------------------
                '-----------------------------------------------------------------
                ' Begin Code statements for each port
                '-----------------------------------------------------------------
                '-----------------------------------------------------------------
                Print #f, ""
                '-----------------------------------------------------------------
                ' Code statements for the Open Drain register for each port
                '-----------------------------------------------------------------
                
                d = sPort & "_OD"
                If (r.Regs.SfrFind(d) = True) Then
                    If r.sfr(d) <> 0 Then
                      iPage = 3
                      If iPageNumber <> 3 Then
                        Print #f, FormatCodeStatemente(2, "SFR_PAGE(" & PORT_PAGE_NAME & iPage & ", noSST);", "", "", "switch to page " & iPage)
                        iPageNumber = 3
                      End If
                      Print #f, FormatCodeStatemente(2, d, "=", formattextoutput(lODx, "H2"), "load open-drain register")
                    End If
                End If
                
                '-----------------------------------------------------------------
                ' Code statements for the PullupPulldownSelect register for each port
                '-----------------------------------------------------------------
                If (lUnusedPins <> (Port.LastPin - Port.FirstPin + 1)) Then
                    d = sPort & "_PUDSEL"
                    If (r.Regs.SfrFind(d) = True) Then
                        If r.sfr(d) <> GetPUDSELDefaultValue(r, sPort) Then
                            iPage = 1
                            Print #f, ""
                            If iPageNumber <> 1 Then
                                Print #f, FormatCodeStatemente(2, "SFR_PAGE(" & PORT_PAGE_NAME & iPage & ", noSST);", "", "", "switch to page " & iPage)
                                iPageNumber = 1
                            End If
                            Print #f, FormatCodeStatemente(2, d, "=", formattextoutput(lPUDSELx, "H2"), "load pullup/pulldown select register")
                        End If
                    End If
                
                    '-----------------------------------------------------------------
                    ' Code statements for the PullupPulldownEnable register for each port
                    '-----------------------------------------------------------------
                    d = sPort & "_PUDEN"
                    If (r.Regs.SfrFind(d) = True) Then
                        If r.sfr(d) <> GetPUDENDefaultValue(r, sPort) Then
                            If iPageNumber <> 1 Then
                                iPage = 1
                                Print #f, FormatCodeStatemente(2, "SFR_PAGE(" & PORT_PAGE_NAME & iPage & ", noSST);", "", "", "switch to page " & iPage)
                                iPageNumber = 1
                            End If
                            Print #f, FormatCodeStatemente(2, d, "=", formattextoutput(lPUDENx, "H2"), "load pullup/pulldown enable register")
                        End If
                    End If
                End If
                '-----------------------------------------------------------------
                ' Code statements for the AlternateSelect0 register for each port
                '-----------------------------------------------------------------
'                d = sPort & "_ALTSEL0"
'                If (r.Regs.SfrFind(d) = True) Then
'                    iPage = 2
'                    Print #f, ""
'                    Print #f, FormatCodeStatemente(2, "SFR_PAGE(" & PORT_PAGE_NAME & iPage & ", noSST);", "", "", "switch to page " & iPage)
'                    Print #f, FormatCodeStatemente(2, d, "=", FormatTextOutput(lALTSEL0x, "H2"), "load alternate output function select register 0")
'                End If
'
'                '-----------------------------------------------------------------
'                ' Code statements for the AlternateSelect1 register for each port
'                '-----------------------------------------------------------------
'                d = sPort & "_ALTSEL1"
'                If (r.Regs.SfrFind(d) = True) Then
'                    Print #f, FormatCodeStatemente(2, d, "=", FormatTextOutput(lALTSEL1x, "H2"), "load alternate output function select register 1")
'                End If
                
                '-----------------------------------------------------------------
                ' Code statements for the Direction register for each port
                '-----------------------------------------------------------------
                d = sPort & "_DIR"
                If (r.Regs.SfrFind(d) = True) Then
                    If lDIRx <> 0 Then
                        Print #f, ""
                        If iPageNumber <> 0 Then
                            iPage = 0
                            Print #f, FormatCodeStatemente(2, "SFR_PAGE(" & PORT_PAGE_NAME & iPage & ", noSST);", "", "", "switch to page " & iPage)
                            iPageNumber = 0
                        End If
                        Print #f, FormatCodeStatemente(2, d, "=", formattextoutput(lDIRx, "H2"), "load direction register")
                    End If
                End If
                
                '-----------------------------------------------------------------
                ' Code statements for the DataOutput register for each port
                '-----------------------------------------------------------------
                d = sPort & "_DATA"
                If (r.Regs.SfrFind(d) = True) Then
                    If r.sfr(d) <> 0 Then
                        Print #f, FormatCodeStatemente(2, d, "=", formattextoutput(lOUTx, "H2"), "load data output register")
                    End If
                End If
                
                
                
                Print #f, ""
            Next Port
            
            If iPageNumber <> 0 Then
                iPage = 0
                Print #f, FormatCodeStatemente(2, "SFR_PAGE(" & PORT_PAGE_NAME & iPage & ", noSST);", "", "", "switch to page " & iPage)
            End If
            Print #f, ""
            Print #f, uc.GetUserCode("(IO_Init,3)", 2)
            Print #f, ""
            Print #f, "} " & END_OF_FUNCTION & r.v("IO_NAME_Init")
            Print #f, ""
            Print #f, ""
    End If
    '------------------------------------------------------------------------------------------------
    ' Other functions: none
    '------------------------------------------------------------------------------------------------

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

    'close file
    Close f

    IOGenerateC = True
    Exit Function

IOGenerateCError:
    Close f
    Exit Function
End Function


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

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

    'refresh the decriptions of the functions and macros
    RefreshFunctionDescriptions func, 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("IO"))
    Print #f, Rtf.GenerateModuleHeader(DefGetValue("ProductVersion"), StripPath(r.LoadedFile), dc("IO").ModuleDescription, r.v("IO_HFILE"), 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, uc.GetUserCode("(IO_Header,4)", 0)
            Print #f, ""

    For Each Port In cPorts
      iPort = Port.PortNumber

            Print #f, FormatComments(0, 0, "", "", Port.Description)
            Print #f, ""
        If (r.v("P" & iPort & "_Notes") <> "") Then
            Print #f, Rtf.GenerateNote(r.v("P" & iPort & "_Notes"))
            Print #f, ""
        End If

    If ((Port.Addr Mod 8) = 0) Then        ' only bit-addressable ports
        For iPin = Port.FirstPin To Port.LastPin
            If cPins.Use("P" & iPort & "_" & iPin) = True Then
                Print #f, SfrBitDeclaration(r, r.v("P" & iPort & "_NAME_" & "P" & iPort & "_" & iPin), _
                                            formattextoutput(Port.Addr + iPin, "H2"), "")
            End If
        Next iPin
    Else
        Print #f, FormatComments(0, 0, "", "", "This port is not bit-addressable.")
    End If
        Print #f, ""
    Next Port

            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'
            

    
    ' for each function in this 'func' object
    For l = 1 To func.FunctionCount
        ' get the function name which was insert in 'Include.inc' with 'AddFunction()'
        d = func.FunctionName(l)

        ' get only the third part of the function name (e.g "Init")
        sName = Right(d, Len(d) - InStr(d, "NAME") - Len("NAME"))

        ' only if the use variable of the function is selected and the function is a really function
        ' (not a macro or a ISR)
        If ((r.v("IO_USE_" & sName) = 1) And (func.FunctionSort(d) = 1)) Then
            Print #f, FormatFunctionDeclaration(r, func, d) & ";"
        End If
    Next l

            Print #f, ""
            Print #f, ""
            Print #f, uc.GetUserCode("(IO_Header,8)", 0)
            Print #f, ""
            Print #f, ""
    
                          'DAvE declarations of global macros'
    '------------------------------------------------------------------------------------------------
    ' IO_ReadPin macro
    '------------------------------------------------------------------------------------------------
    If (r.v("IO_USE_ReadPin") = 1) Then
            Print #f, FormatFunctionHeader(r, func, "IO_NAME_ReadPin")

            Print #f, "#define " & r.v("IO_NAME_ReadPin") & "(PinName) PinName"
            Print #f, ""
    End If
    '------------------------------------------------------------------------------------------------
    ' IO_SetPin macro
    '------------------------------------------------------------------------------------------------
    If (r.v("IO_USE_SetPin") = 1) Then
            Print #f, FormatFunctionHeader(r, func, "IO_NAME_SetPin")

            Print #f, "#define " & r.v("IO_NAME_SetPin") & "(PinName) PinName = 1"
            Print #f, ""
    End If
    '------------------------------------------------------------------------------------------------
    ' IO_ResetPin macro
    '------------------------------------------------------------------------------------------------
    If (r.v("IO_USE_ResetPin") = 1) Then
            Print #f, FormatFunctionHeader(r, func, "IO_NAME_ResetPin")

            Print #f, "#define " & r.v("IO_NAME_ResetPin") & "(PinName) PinName = 0"
            Print #f, ""
    End If
    '------------------------------------------------------------------------------------------------
    ' IO_TogglePin macro
    '------------------------------------------------------------------------------------------------
    If (r.v("IO_USE_TogglePin") = 1) Then
            Print #f, FormatFunctionHeader(r, func, "IO_NAME_TogglePin")

            Print #f, "#define " & r.v("IO_NAME_TogglePin") & "(PinName) PinName ^= 1"
            Print #f, ""
    End If
    '------------------------------------------------------------------------------------------------
    ' IO_ReadPort macro
    '------------------------------------------------------------------------------------------------
    If (r.v("IO_USE_ReadPort") = 1) Then
            Print #f, FormatFunctionHeader(r, func, "IO_NAME_ReadPort")

            Print #f, "#define " & r.v("IO_NAME_ReadPort") & "(PortName) PortName##_DATA"
            Print #f, ""
    End If
    '------------------------------------------------------------------------------------------------
    ' IO_WritePort macro
    '------------------------------------------------------------------------------------------------
    If (r.v("IO_USE_WritePort") = 1) Then
            Print #f, FormatFunctionHeader(r, func, "IO_NAME_WritePort")

            Print #f, "#define " & r.v("IO_NAME_WritePort") & "(PortName, Data) PortName##_DATA = Data"
            Print #f, ""
    End If
    '------------------------------------------------------------------------------------------------
    ' IO_SetInput macro
    '------------------------------------------------------------------------------------------------
    If (r.v("IO_USE_SetInput") = 1) Then
            Print #f, FormatFunctionHeader(r, func, "IO_NAME_SetInput")

            Print #f, "#define " & r.v("IO_NAME_SetInput") & "(PortName, Mask) { \"
            Print #f, "  ubyte ubEA = " & CORE_PREFIX & "IEN0 & " & formattextoutput(BitMask(r, CORE_PREFIX & "IEN0", "EA"), "H2") & "; \"
            Print #f, "  " & CORE_PREFIX & "IEN0 &= ~(ubyte)" & formattextoutput(BitMask(r, CORE_PREFIX & "IEN0", "EA"), "H2") & "; \"
           '' Print #f, FormatCodeStatemente(2, "SFR_PAGE(" & PORT_PAGE_NAME & "0, SST1); \", "", "", "")
           Print #f, "  SFR_PAGE(_pp0, SST1); \"
            Print #f, "  PortName##_DIR &= ~(ubyte)(Mask); \"
            ''Print #f, FormatCodeStatemente(2, "SFR_PAGE(" & PORT_PAGE_NAME & "0, RST1); \", "", "", "")
            Print #f, "  SFR_PAGE(_pp0, RST1); \"
            Print #f, "  " & CORE_PREFIX & "IEN0 |= ubEA; }"
            Print #f, ""
    End If
    '------------------------------------------------------------------------------------------------
    ' IO_SetOutput macro
    '------------------------------------------------------------------------------------------------
    If (r.v("IO_USE_SetOutput") = 1) Then
            Print #f, FormatFunctionHeader(r, func, "IO_NAME_SetOutput")

            Print #f, "#define " & r.v("IO_NAME_SetOutput") & "(PortName, Mask) { \"
            Print #f, "  ubyte ubEA = " & CORE_PREFIX & "IEN0 & " & formattextoutput(BitMask(r, CORE_PREFIX & "IEN0", "EA"), "H2") & "; \"
            Print #f, "  " & CORE_PREFIX & "IEN0 &= ~(ubyte)" & formattextoutput(BitMask(r, CORE_PREFIX & "IEN0", "EA"), "H2") & "; \"
            ''Print #f, FormatCodeStatemente(2, "SFR_PAGE(" & PORT_PAGE_NAME & "0, SST1); \", "", "", "")
            Print #f, "  SFR_PAGE(_pp0, SST1); \"
            Print #f, "  PortName##_DIR |= Mask; \"
           '' Print #f, FormatCodeStatemente(2, "SFR_PAGE(" & PORT_PAGE_NAME & "0, RST1); \", "", "", "")
            Print #f, "  SFR_PAGE(_pp0, RST1); \"
            Print #f, "  " & CORE_PREFIX & "IEN0 |= ubEA; }"
            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:
    Close f
    ErrorBox "error Header", Err.Description
    Exit Function
End Function


