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\ModuleClass.cls"
'#Uses "Include.inc"

Option Explicit
'*****************************************************************************
' Module:
'        MAIN
'-----------------------------------------------------------------------------
' Description:
'        This file contains functions for generating code for the
'        module 'MAIN'.
'
'-----------------------------------------------------------------------------
' History:
'
'        Rev. Author         Date        Description
'        ---------------------------------------------------------------------
'        1.0   ahe         27.04.00     final version
'        1.1   ahe         20.06.00     final version for C167CS
'
'        ---------------------------------------------------------------------
'        5.0   ahe         31.07.00     final version for C161CS/JC/JI
'                                       added SYSCON1 .. 3
'
'        ---------------------------------------------------------------------
'              ahe         25.10.00     final version for
'                                         C167CS
'                                         C161CS/JC/JI
'                                         C167CR/SR r2
'
'
'        ---------------------------------------------------------------------
'        6.0   ahe         05.11.01     final version for Pegasus
'
'        6.1   ahe         05.06.02     set the value of PLLCON
'              ahe         07.08.02     set CPUCON1, CPUCON2 and VECSEG
'
'        6.2   ahe         23.08.02     delete CPUCON2 register (requirement from Ursula Kelling)
'        6.3   ste         13.12.02     XC167CI added
'                                       comments for CS timing added
'                                       comment for RDYMODx corrected
'        6.4   ste         24.02.03     comments for System Clock changed
'        ---------------------------------------------------------------------
'              ste         01.10.03     register declaration for TwinCAN changed
'                                       (not bitaddressable)
'
'        ---------------------------------------------------------------------
'        7.0               12.08.04     final version for XC164CM Pegasus lite
'                                       - removed EBC related code lines
'                                       - checked to avoid the same bitnames in same sfr.
'
'*****************************************************************************

'*****************************************************************************
'Description:
'        This functions initiates the code generation for the MAIN module.
'-----------------------------------------------------------------------------
'Parameters:
'        r                reference to the Registers object
'        vIndex           a parameter
'-----------------------------------------------------------------------------
'Returns:
'        True            on successfull operation
'        False           else
'*****************************************************************************
Function StartGenerateCode(r As ProjectData, vIndex As Variant) As Boolean
    On Error GoTo StartGenerateCodeError
    StartGenerateCode = False

    Dim sVarPre As String
    sVarPre = "MAIN"
    
    ' write file MAIN.h
    If (Not MAINGenerateH(r, vIndex)) Then Exit Function
           If (Not r.AddFile(r.s(sVarPre & "_HFILE"))) Then Exit Function

    ' write file MAIN.c
    If (Not MAINGenerateC(r, vIndex)) Then Exit Function
           If (Not r.AddFile(r.s(sVarPre & "_CFILE"))) Then Exit Function

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

'*****************************************************************************
'Description:
'        Generates the code for the MAIN.C file.
'-----------------------------------------------------------------------------
'Parameters:
'        r                reference to the Registers object
'        vIndex           a parameter
'-----------------------------------------------------------------------------
'Returns:
'        True            on successfull operation
'        False           else
'*****************************************************************************
Function MAINGenerateC(r As ProjectData, vIndex As Variant) As Boolean
    On Error GoTo MAINGenerateCError

    MAINGenerateC = False
    
    Dim i As Integer
    Dim ib As Integer
    Dim f As Variant
    Dim v As Variant
    Dim d As String
    Dim n As String
    Dim dc As DAvECollection
    Dim uc As UserCode
    Dim func As FunctionClass
    Dim sAlternatePinName(1 To 4) As String
    Dim mo As ModuleClass
    Dim sVarPre As String
    Dim sRegPre As String
    Dim iCS_Max As Integer
    Dim lCopyRGSAD As Long
    Dim dF As Double

    sVarPre = "MAIN"

    Set dc = ObjectCollection("MODULENAMES")
    Set uc = New UserCode
    Set func = New FunctionClass

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

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

    'open MAIN.c
    f = FreeFile
    Open CStr(StripFilenameAndExtension(r.LoadedFile)) & "\" & r.v(sVarPre & "_CFILE") For Output As f
    
    '------------------------------------------------------------------------------------------------
    ' module header
    '------------------------------------------------------------------------------------------------
    d = "This file contains the project initialization function."
    d = FormatModuleDescription(d)

    Print #f, Rtf.GenerateModuleHeader(DefGetValue("ProductVersion"), StripPath(r.LoadedFile), dc(sVarPre).ModuleDescription, r.v(sVarPre & "_CFILE"), r.v("MAIN_CPU_TYPE"), r.v("MAIN_COMPILER"), d)
          
    Print #f, uc.GetUserCode("(" & sVarPre & "_General,1)", 0)   'USER CODE for application specific descriptions'
    Print #f, ""
    Print #f, Rtf.GenerateNote((r.v(sVarPre & "_Notes")))
    Print #f, ""
    
    'Notes for EBC
    If Not (r.v("EBC_Notes") = "") Then
        Print #f, Rtf.GenerateNote("Notes of EBC Module:" & vbCrLf & r.v("EBC_Notes"))
        Print #f, ""
    End If

    Print #f, SECTION_PROJECT_INCLUDES
    Print #f, ""  'DAvE includes'
    Print #f, "#include """ & r.v("MAIN_HFile") & """"
    Print #f, ""
    Print #f, uc.GetUserCode("(" & sVarPre & "_General,2)", 0)
    Print #f, ""
    Print #f, ""
    Print #f, SECTION_MACROS
    Print #f, ""  'DAvE local macro definitions'
    Print #f, uc.GetUserCode("(" & sVarPre & "_General,3)", 0)
    Print #f, ""
    Print #f, ""
    Print #f, SECTION_DEFINES
    Print #f, ""  'DAvE local #define definitions'
    Print #f, uc.GetUserCode("(" & sVarPre & "_General,4)", 0)
    Print #f, ""
    Print #f, ""
    Print #f, SECTION_TYPEDEFS
    Print #f, ""  'DAvE type defintions'
    Print #f, uc.GetUserCode("(" & sVarPre & "_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("(" & sVarPre & "_General,6)", 0)
    Print #f, ""
    Print #f, ""
    Print #f, SECTION_GLOBAL_VARIABLES
    Print #f, ""  'DAvE definitions of global variables'
    Print #f, uc.GetUserCode("(" & sVarPre & "_General,7)", 0)
    Print #f, ""
    Print #f, ""
    Print #f, SECTION_EXTERNAL_PROTOTYPES
    Print #f, ""  'DAvE external declarations of imported functions'
    Print #f, uc.GetUserCode("(" & sVarPre & "_General,8)", 0)
    Print #f, ""
    Print #f, ""
    Print #f, SECTION_LOCAL_PROTOTYPES
    Print #f, ""  'DAvE declarations of internal local functions'
    Print #f, uc.GetUserCode("(" & sVarPre & "_General,9)", 0)
    Print #f, ""
    Print #f, ""

    '------------------------------------------------------------------------------------------------
    '------------------------------------------------------------------------------------------------
    ' MAIN_vInit function
    '------------------------------------------------------------------------------------------------
    '------------------------------------------------------------------------------------------------
    n = "Init"
'    If (r.v(sVarPre & "_USE_" & n) = 1) Then
      Print #f, FormatFunctionHeader(r, func, sVarPre & "_NAME_" & n)
      Print #f, uc.GetUserCode("(" & n & ",1)", 0)     'USER CODE for application specific descriptions'
      Print #f, ""
      Print #f, FormatFunctionDeclaration(r, func, sVarPre & "_NAME_" & n)
      Print #f, "{"
      Print #f, uc.GetUserCode("(" & n & ",2)", 2)
      Print #f, ""

      '------------------------------------------------------------------------------------------------
      ' Configuration of the System Clock:
      '------------------------------------------------------------------------------------------------
      Print #f, FormatSectionHeader(2, 1, "Configuration of the System Clock:")

      If (r.v("PLLCON_PLLCTRL") = 0) Then
          d = "bypass PLL clock multiplier; the VCO is OFF"
      ElseIf (r.v("PLLCON_PLLCTRL") = 1) Then
          d = "bypass PLL clock multiplier; the VCO is running"
      ElseIf (r.v("PLLCON_PLLCTRL") = 2) Then
          d = "VCO clock used, input clock is switched off"
      ElseIf (r.v("PLLCON_PLLCTRL") = 3) Then
          d = "VCO clock used, input clock is connected"
      End If
      Print #f, FormatCommentsForInit(1, d)

      d = "input frequency is " & r.v("MAIN_OSC") & " MHz"
      Print #f, FormatCommentsForInit(1, d)

      If (r.v("PLLCON_PLLVB") = 0) Then
          d = "VCO output frequency 100 .. 150 MHz"
      ElseIf (r.v("PLLCON_PLLVB") = 1) Then
          d = "VCO output frequency 150 .. 200 MHz"
      ElseIf (r.v("PLLCON_PLLVB") = 2) Then
          d = "VCO output frequency 200 .. 250 MHz"
      End If
      Print #f, FormatCommentsForInit(1, d)


      If (IsNumeric(Get_FCPU(r)) = True) Then
        d = "system clock is " & GetSystemClock(r) & " MHz"
        Print #f, FormatCommentsForInit(1, d)
      Else
        d = "system clock is too high (" & GetSystemClock(r) & " MHz)"
        Print #f, FormatCommentsForInit(2, d)
      End If

      Print #f, ""
      Print #f, "  MAIN_vUnlockProtecReg();       // unlock write security"
      v = 0
      v = r.sfr("PLLCON")
      Print #f, FormatCodeStatemente(2, "PLLCON", "=", FormatTextOutput(v, "H4"), "load PLL control register")
      Print #f, ""
      Print #f, ""

      '------------------------------------------------------------------------------------------------
      ' Begin of Important Settings for the Start-Up File
      '------------------------------------------------------------------------------------------------
      Print #f, FormatSectionHeader(2, 2, "Begin of Important Settings for the Start-Up File")
      
      d = "All following settings must be set in the start-up file. You can use DAvE's " & _
          "project file (*.dpt) to include this register values into your compiler EDE."
      Print #f, FormatCommentsForSource(2, 1, d)
      
      Print #f, ""

      '------------------------------------------------------------------------------------------------
      ' initialization of the CPUCON1 Register:
      '------------------------------------------------------------------------------------------------
      Print #f, FormatSectionHeader(4, 1, "Initialization of the CPUCON1 Register:")

      'VECSC
      d = "- space between two vectors is " & 2 * 2 ^ r.v("CPUCON1_VECSC") & " words"
      Print #f, FormatCommentsForSource(4, 1, d)

      'WDTCTL
      If (r.v("CPUCON1_WDTCTL") = 0) Then
          d = "- DISWDT executable until End of Init"
      Else
          d = "- DISWDT/ENWDT always executable"
      End If
      Print #f, FormatCommentsForSource(4, 1, d)

      'SGTDIS
      If (r.v("CPUCON1_SGTDIS") = 0) Then
          d = "- segmentation is enabled"
      Else
          d = "- segmentation is disabled"
      End If
      Print #f, FormatCommentsForSource(4, 1, d)

      'INTSCXT
      If (r.v("CPUCON1_INTSCXT") = 0) Then
          d = "- switch context is not interruptible"
      Else
          d = "- switch context is interruptible"
      End If
      Print #f, FormatCommentsForSource(4, 1, d)

      'BP
      If (r.v("CPUCON1_BP") = 0) Then
          d = "- branch prediction is disabled"
      Else
          d = "- branch prediction is enabled"
      End If
      Print #f, FormatCommentsForSource(4, 1, d)

      'ZCJ
      If (r.v("CPUCON1_ZCJ") = 0) Then
          d = "- zero cycle jump function is disabled"
      Else
          d = "- zero cycle jump function is enabled"
      End If
      Print #f, FormatCommentsForSource(4, 1, d)

      Print #f, ""
      d = "this register must be set in the start-up file"
      Print #f, FormatCommentsForSource(4, 2, d)
      d = "CPUCON1  =  " & FormatTextOutput(r.sfr("CPUCON1"), "H4")
      Print #f, FormatCommentsForSource(4, 2, d)
      Print #f, ""

      ''------------------------------------------------------------------------------------------------
      '' initialization of the CPUCON2 Register:
      ''------------------------------------------------------------------------------------------------
      'Print #f, FormatSectionHeader(4, 1, "Initialization of the CPUCON2 Register:")
      '
      ''FIFOFED
      'If (r.v("CPUCON2_FIFOFED") = 0) Then
      '    d = "- FIFO is disabled"
      'Else
      '    d = "- FIFO filled with up to " & r.v("CPUCON2_FIFOFED") & " instruction per cycle"
      'End If
      'Print #f, FormatCommentsForSource(4, 1, d)
      '
      ''FIFOFED
      'If (r.v("CPUCON2_FIFOFED") > 0) Then
      '    If (r.v("CPUCON2_FIFODEPTH") = 0) Then
      '        d = "- no FIFO"
      '    ElseIf (r.v("CPUCON2_FIFODEPTH") = 1) Then
      '        d = "- 1 FIFO entry"
      '    Else
      '        d = "- " & r.v("CPUCON2_FIFODEPTH") & " FIFO entries"
      '    End If
      '    Print #f, FormatCommentsForSource(4, 1, d)
      'End If
      '
      ''BYPPF
      'If (r.v("CPUCON2_BYPPF") = 0) Then
      '    d = "- bypass path from prefetch to decode disabled"
      'Else
      '    d = "- bypass path from prefetch to decode available"
      'End If
      'Print #f, FormatCommentsForSource(4, 1, d)
      '
      ''BYPF
      'If (r.v("CPUCON2_BYPF") = 0) Then
      '    d = "- bypass path from fetch to decode disabled"
      'Else
      '    d = "- bypass path from fetch to decode available"
      'End If
      'Print #f, FormatCommentsForSource(4, 1, d)
      '
      ''EIOIAEN
      'If (r.v("CPUCON2_EIOIAEN") = 0) Then
      '    d = "- injection acknowledge by destructive read not guaranteed"
      'Else
      '    d = "- injection acknowledge by destructive read guaranteed"
      'End If
      'Print #f, FormatCommentsForSource(4, 1, d)
      '
      ''STEN
      'If (r.v("CPUCON2_STEN") = 0) Then
      '    d = "- stall Instruction disabled"
      'Else
      '    d = "- stall Instruction enabled"
      'End If
      'Print #f, FormatCommentsForSource(4, 1, d)
      '
      ''LFIC
      'If (r.v("CPUCON2_LFIC") = 0) Then
      '    d = "- linear follower instruction cache disabled"
      'Else
      '    d = "- linear follower instruction cache enabled"
      'End If
      'Print #f, FormatCommentsForSource(4, 1, d)
      '
      ''OVRUN
      'If (r.v("CPUCON2_OVRUN") = 0) Then
      '    d = "- overrun of pipeline bubbles not allowed"
      'Else
      '    d = "- overrun of pipeline bubbles allowed"
      'End If
      'Print #f, FormatCommentsForSource(4, 1, d)
      '
      ''RETST
      'If (r.v("CPUCON2_RETST") = 0) Then
      '    d = "- return stack is disabled"
      'Else
      '    d = "- return stack is enabled"
      'End If
      'Print #f, FormatCommentsForSource(4, 1, d)
      '
      ''DAID
      'If (r.v("CPUCON2_DAID") = 0) Then
      '    d = "- injection requests on atomic sequences are denied to allow reprioritization by the interrupt controller"
      'Else
      '    d = "- injection requests on atomic sequences are processed as soon as the atomic sequence is finished; no reprioritization"
      'End If
      'Print #f, FormatCommentsForSource(4, 1, d)
      '
      ''SL
      'If (r.v("CPUCON2_SL") = 0) Then
      '    d = "- short loop mode disabled"
      'Else
      '    d = "- short loop mode enabled"
      'End If
      'Print #f, FormatCommentsForSource(4, 1, d)
      '
      'Print #f, ""
      'd = "this register must be set in the start-up file"
      'Print #f, FormatCommentsForSource(4, 2, d)
      'd = "CPUCON2  =  " & FormatTextOutput(r.sfr("CPUCON2"), "H4")
      'Print #f, FormatCommentsForSource(4, 2, d)
      'Print #f, ""

      '------------------------------------------------------------------------------------------------
      ' initialization of the VECSEG Register:
      '------------------------------------------------------------------------------------------------
      Print #f, FormatSectionHeader(4, 1, "Initialization of the VECSEG Register:")

      If (r.sfr("VECSEG") = &HC0) Then
          d = "- start from internal program memory"
      ElseIf (r.sfr("VECSEG") = &HBF) Then
          d = "- start from boot memory"
      ElseIf (r.sfr("VECSEG") = 0) Then
          d = "- start from external memory"
      Else
          d = "- start from a segment specified from the system"
      End If
      Print #f, FormatCommentsForSource(4, 1, d)

      Print #f, ""
      d = "this register must be set in the start-up file"
      Print #f, FormatCommentsForSource(4, 2, d)
      d = "VECSEG  =  " & FormatTextOutput(r.sfr("VECSEG"), "H4")
      Print #f, FormatCommentsForSource(4, 2, d)
      Print #f, ""

      '------------------------------------------------------------------------------------------------
      ' initialization of the SYSCON0 Register:
      '------------------------------------------------------------------------------------------------
      Print #f, FormatSectionHeader(4, 1, "Initialization of the SYSCON0 Register:")
      Print #f, ""
      d = "this register must be set in the start-up file"
      Print #f, FormatCommentsForSource(4, 2, d)
      d = "SYSCON0  =  " & FormatTextOutput(r.sfr("SYSCON0"), "H4")
      Print #f, FormatCommentsForSource(4, 2, d)
      Print #f, ""

      If (r.v("SCU_USE_Init") = 0) Then
          '------------------------------------------------------------------------------------------------
          ' initialization of the SYSCON1 Register:
          '------------------------------------------------------------------------------------------------
          Print #f, FormatSectionHeader(4, 1, "Initialization of the SYSCON1 Register:")

          '------------------------------------------------- SYSCON1_CPSYS
          Select Case (r.v("SYSCON1_CPSYS"))
                      Case (0)
                           d = "clock prescaler for system is fpll / 1"
                      Case (1)
                           d = "clock prescaler for system is fpll / 2"
          End Select
          Print #f, FormatCommentsForSource(4, 1, d)

          '*********************** new code *****************************
          '------------------------------------------------- SYSCON1_CPPD
          'Select Case (r.v("SYSCON1_CPPD"))
           '           Case (0)
                           d = "clock prescaler for PD+ bus is fcpu / 1"
            '          Case (1)
             '              d = "clock prescaler for PD+ bus is fcpu / 2"
          'End Select
          Print #f, FormatCommentsForSource(4, 1, d)
          '*********************** new code *****************************
          Print #f, ""
          d = "this register must be set in the start-up file"
          Print #f, FormatCommentsForSource(4, 2, d)
          v = 0
          v = v + r.v("SYSCON1_CPSYS") * 2 ^ 8 '+ r.v("SYSCON1_CPPD") * 2 ^ 12
          d = "SYSCON1  =  " & FormatTextOutput(v, "H4")
          Print #f, FormatCommentsForSource(4, 2, d)
          Print #f, ""
      End If
 
      If (r.v("SCU_USE_Init") = 0) Then
          '------------------------------------------------------------------------------------------------
          ' initialization of the SYSCON3 Register:
          '------------------------------------------------------------------------------------------------
          Print #f, FormatSectionHeader(4, 1, "Initialization of the SYSCON3 Register:")
          Print #f, ""
          d = "this register must be set in the start-up file"
          Print #f, FormatCommentsForSource(4, 2, d)
          v = 0
          d = "SYSCON3  =  " & FormatTextOutput(v, "H4")
          Print #f, FormatCommentsForSource(4, 2, d)
          Print #f, ""
      End If
 

'      '------------------------------------------------------------------------------------------------
'      ' Initialization of EBC
'      '------------------------------------------------------------------------------------------------
'      Print #f, FormatSectionHeader(4, 1, "Initialization of EBC")
'
'      Print #f, ""
'      d = "this register must be set in the start-up file"
'      Print #f, FormatCommentsForSource(4, 2, d)
'
'      d = "EBCMOD1  =  " & FormatTextOutput(r.sfr("EBCMOD1"), "H4")
'      Print #f, FormatCommentsForSource(4, 2, d)
'      Print #f, ""
'
'      If (r.v("EBCMOD0_EBCDIS") = 0) Then
'          d = "EBC is enabled"
'      Else
'          d = "EBC is disabled"
'      End If
'      Print #f, FormatCommentsForSource(4, 1, d)
'
'
'      If (r.v("EBCMOD0_EBCDIS") = 0) Then
'          If (r.v("EBCMOD0_BYTDIS") = 1) Then
'              d = "pin #BHE is disabled"
'          Else
'              d = "pin #BHE is enabled"
'          End If
'          Print #f, FormatCommentsForSource(4, 1, d)
'
'          If (r.v("EBCMOD0_BYTDIS") = 0) Then
'              If (r.v("EBCMOD0_WRCFG") = 0) Then
'                  d = "#WR and #BHE retain their normal function"
'              Else
'                  d = "#WR acts as #WRL, #BHE acts as #WRH"
'              End If
'              Print #f, FormatCommentsForSource(4, 1, d)
'          End If
'
'          If (r.v("EBCMOD0_ALEDIS") = 0) Then
'              d = "pin ALE is enabled"
'          Else
'              d = "pin ALE is disabled"
'          End If
'          Print #f, FormatCommentsForSource(4, 1, d)
'
'          i = r.v("EBCMOD0_SAPEN")
'          If (i = 0) Then
'              d = "no segment address pins enabled"
'          ElseIf (i = 1) Then
'              d = "as segment address is one pin enabled ( A[16] )"
'          Else
'              d = "as segment address are " & i & " pins enabled ( A[" & 15 + i & "] .. A[16] )"
'          End If
'          Print #f, FormatCommentsForSource(4, 1, d)
'
'          i = r.v("EBCMOD0_CSPEN")
'          If (i = 0) Then
'              d = "no chip select pin enabled"
'          ElseIf (i = 1) Then
'              d = "#CS0 is enabled"
'          Else
'              'd = "#CS" & i & " .. #CS0 are enabled"
'              d = "#CS" & i - 1 & " .. #CS0 are enabled"
'          End If
'          Print #f, FormatCommentsForSource(4, 1, d)
'
'          If (r.v("EBCMOD0_RDYDIS") = 0) Then
'              d = "pin #READY is enabled"
'          Else
'              d = "pin #READY is disabled"
'          End If
'          Print #f, FormatCommentsForSource(4, 1, d)
'
'          If (r.v("EBCMOD0_RDYDIS") = 0) Then
'              If (r.v("EBCMOD0_RDYPOL") = 0) Then
'                  d = "#READY is active low"
'              Else
'                  d = "#READY is active high"
'              End If
'              Print #f, FormatCommentsForSource(4, 1, d)
'          End If
'
'          If (r.v("EBCMOD0_ARBEN") = 0) Then
'              d = "bus arbitration is disabled, P6.7 .. P6.5 may used for general purpose IO"
'          Else
'              d = "bus arbitration is enabled, P6.7 .. P6.5 serve as #BREQ, #HLDA and #HOLD"
'          End If
'          Print #f, FormatCommentsForSource(4, 1, d)
'
'          If (r.v("EBCMOD0_ARBEN") = 1) Then
'              If (r.v("EBCMOD0_SLAVE") = 0) Then
'                  d = "bus arbiter acts in master mode"
'              Else
'                  d = "bus srbiter acts in slave mode"
'              End If
'              Print #f, FormatCommentsForSource(4, 1, d)
'          End If
'
'          Print #f, ""
'          d = "this register must be set in the start-up file"
'          Print #f, FormatCommentsForSource(4, 2, d)
'
'          d = "EBCMOD0  =  " & FormatTextOutput(r.sfr("EBCMOD0"), "H4")
'          Print #f, FormatCommentsForSource(4, 2, d)
'          Print #f, ""
'
'          If (r.v("EBCMOD0_ARBEN") = 1) Then
'              sAlternatePinName(1) = "HOLD_n"
'              sAlternatePinName(2) = "HLDA_n_I"
'              sAlternatePinName(3) = "HLDA_n_O"
'              sAlternatePinName(4) = "BREQ_n"
'              Call SetAlternatePinStatements(f, r, sAlternatePinName())
'          End If
'
'
'          If (r.Exist("MuxFor_CS4_n") = True) Then
'              iCS_Max = 4
'          Else
'              iCS_Max = 3
'          End If
'
'          For i = 0 To iCS_Max
'              If (r.v("FCONCS" & i & "_ENCS" & i) = 1) Then
'                  Print #f, FormatSectionHeader(4, 1, "---------- chip select " & i & " is enabled ----------")
'
'
'                  Select Case (r.v("FCONCS" & i & "_BTYP" & i))
'                         Case (0)
'                               d = "- 8-bit Demultiplexed Bus"
'                         Case (1)
'                               d = "- 8-bit Multiplexed Bus"
'                         Case (2)
'                               d = "- 16-bit Demultiplexed Bus"
'                         Case (3)
'                               d = "- 16-bit Multiplexed Bus"
'                  End Select
'                  Print #f, FormatCommentsForSource(4, 1, d)
'
'                  If (r.v("FCONCS" & i & "_RDYEN" & i) = 0) Then
'                      d = "access time is controlled by bitfield PHE" & i
'                  Else
'                      d = "access time is controlled by bitfield PHE" & i & " and #READY signal"
'                  End If
'                  Print #f, FormatCommentsForSource(4, 1, d)
'
'                  If (r.v("FCONCS" & i & "_RDYEN" & i) = 1) Then
''                      If (r.v("FCONCS" & i & "_RDYMOD" & i) = 1) Then
'                      If (r.v("FCONCS" & i & "_RDYMOD" & i) = 0) Then
'                          d = "asynchronous #READY"
'                      Else
'                          d = "synchronous #READY"
'                      End If
'                      Print #f, FormatCommentsForSource(4, 1, d)
'                  End If
'                  Print #f, ""
'                  d = "this register must be set in the start-up file"
'                  Print #f, FormatCommentsForSource(4, 2, d)
'                  d = "FCONCS" & i & "  =  " & FormatTextOutput(r.sfr("FCONCS" & i), "H4")
'                  Print #f, FormatCommentsForSource(4, 2, d)
'                  Print #f, ""
'
'                  d = "Phase A: " & r.v("TCONCS" & i & "_" & "PHA" & i) & " clock cycles"
'                  Print #f, FormatCommentsForSource(4, 1, d)
'                  d = "Phase B: " & r.v("TCONCS" & i & "_" & "PHB" & i) + 1 & " clock cycles"
'                  Print #f, FormatCommentsForSource(4, 1, d)
'                  d = "Phase C: " & r.v("TCONCS" & i & "_" & "PHC" & i) & " clock cycles"
'                  Print #f, FormatCommentsForSource(4, 1, d)
'                  d = "Phase D: " & r.v("TCONCS" & i & "_" & "PHD" & i) & " clock cycles"
'                  Print #f, FormatCommentsForSource(4, 1, d)
'                  d = "Phase E: " & r.v("TCONCS" & i & "_" & "PHE" & i) + 1 & " clock cycles"
'                  Print #f, FormatCommentsForSource(4, 1, d)
'                  d = "Read Phase F: " & r.v("TCONCS" & i & "_" & "RDPHF" & i) & " clock cycles"
'                  Print #f, FormatCommentsForSource(4, 1, d)
'                  d = "Write Phase F: " & r.v("TCONCS" & i & "_" & "WRPHF" & i) & " clock cycles"
'                  Print #f, FormatCommentsForSource(4, 1, d)
'                  Print #f, ""
'                  d = "this register must be set in the start-up file"
'                  Print #f, FormatCommentsForSource(4, 2, d)
'                  d = "TCONCS" & i & "  =  " & FormatTextOutput(r.sfr("TCONCS" & i), "H4")
'                  Print #f, FormatCommentsForSource(4, 2, d)
'                  Print #f, ""
'
'                  If (i > 0) Then
'                      '-------------------------------------------- ADDRSELx_RGSZ
'                      d = "address range size selection: "
'                      Select Case (r.v("ADDRSEL" & i & "_RGSZ" & i))
'                               Case (0)
'                                     d = d & "4 KByte"
'                               Case (1)
'                                     d = d & "8 KByte"
'                               Case (2)
'                                     d = d & "16 KByte"
'                               Case (3)
'                                     d = d & "32 KByte"
'                               Case (4)
'                                     d = d & "64 KByte"
'                               Case (5)
'                                     d = d & "128 KByte"
'                               Case (6)
'                                     d = d & "256 KByte"
'                               Case (7)
'                                     d = d & "512 KByte"
'                               Case (8)
'                                     d = d & "1 MByte"
'                               Case (9)
'                                     d = d & "2 MByte"
'                               Case (10)
'                                     d = d & "4 MByte"
'                               Case (11)
'                                     d = d & "8 MByte"
'                      End Select
'                      Print #f, FormatCommentsForSource(4, 1, d)
'
'                      lCopyRGSAD = r.v("ADDRSEL" & i & "_RGSAD" & i)
'                      If (r.v("ADDRSEL" & i & "_RGSZ" & i) > 0) Then
'                        lCopyRGSAD = 0
'                        lCopyRGSAD = (r.v("ADDRSEL" & i & "_RGSAD" & i) \ _
'                                      2 ^ (r.v("ADDRSEL" & i & "_RGSZ" & i))) * _
'                                      2 ^ (r.v("ADDRSEL" & i & "_RGSZ" & i))
'                      End If
'                      d = "start address (A23..A0): " & FormatTextOutput(lCopyRGSAD, "H3") & "000"
'                      Print #f, FormatCommentsForSource(4, 1, d)
'                      Print #f, ""
'                      d = "this register must be set in the start-up file"
'                      Print #f, FormatCommentsForSource(4, 2, d)
'                      d = "ADDRSEL" & i & "  =  " & FormatTextOutput(r.sfr("ADDRSEL" & i), "H4")
'                      Print #f, FormatCommentsForSource(4, 2, d)
'                      Print #f, ""
'                  End If
'
'              Else
'                  Print #f, FormatSectionHeader(4, 1, "---------- chip select " & i & " is disabled ----------")
'                  Print #f, ""
'                  Print #f, ""
'              End If
'          Next i
'      End If

      '------------------------------------------------------------------------------------------------
      ' End of Important Settings for the Start-Up File
      '------------------------------------------------------------------------------------------------
      Print #f, FormatSectionHeader(2, 2, "End of Important Settings for the Start-Up File")
      Print #f, ""
      Print #f, ""
      

      '------------------------------------------------------------------------------------------------
      ' Initialization of the Peripherals:
      '------------------------------------------------------------------------------------------------
      Print #f, FormatSectionHeader(2, 0, "Initialization of the Peripherals:")
      Print #f, ""

      For Each mo In dc
        If (mo.ModuleName <> "MAIN" And mo.ModuleName <> "LIN") Then
          
          If (mo.ModuleWithCG) Then
            If (r.v(mo.ModuleName & "_USE_Init") = 1) Then
                  d = "initializes the " & mo.ModuleDescription
                  Print #f, FormatCommentsForSource(2, 0, d)
                  Print #f, "  " & r.v(mo.ModuleName & "_NAME_INIT") & "();"
                  Print #f, ""
            End If
          End If

        End If
      Next mo

      Print #f, uc.GetUserCode("(" & n & ",3)", 2)
      Print #f, ""

      If (r.v("PSW_IEN") = 1) Then
        d = "globally enable interrupts"
        Print #f, FormatCommentsForSource(2, 0, d)
      Else
        d = "globally disable interrupts"
        Print #f, FormatCommentsForSource(2, 2, d)
      End If

      v = 0
      v = r.v("PSW_IEN")

      Print #f, FormatCodeStatemente(2, "PSW_IEN", "=", FormatTextOutput(v, "F"), "")

      Print #f, ""
      Print #f, "} " & END_OF_FUNCTION & r.v(sVarPre & "_NAME_" & n)
      Print #f, ""
      Print #f, ""

    '------------------------------------------------------------------------------------------------
    '------------------------------------------------------------------------------------------------
    ' MAIN_UnlockProtecReg function
    '------------------------------------------------------------------------------------------------
    '------------------------------------------------------------------------------------------------
    n = "UnlockProtecReg"
    If (r.v("MAIN_USE_" & n) = 1) Then
      Print #f, FormatFunctionHeader(r, func, sVarPre & "_NAME_" & n)
      Print #f, uc.GetUserCode("(" & n & ",1)", 0)     'USER CODE for application specific descriptions'
      Print #f, ""
      Print #f, FormatFunctionDeclaration(r, func, sVarPre & "_NAME_" & n)
      Print #f, "{"
      Print #f, "  ubyte ubPASSWORD;"
      Print #f, ""
      Print #f, "  if((SCUSLS & 0x1800) == 0x0800)      // if low protected mode"
      Print #f, "  {"
      Print #f, ""
      Print #f, "    ubPASSWORD = SCUSLS & 0x00FF;"
      Print #f, "    ubPASSWORD = ~ubPASSWORD;"
      Print #f, "    SCUSLC = 0x8E00 | ubPASSWORD;      // command 4"
      Print #f, ""
      Print #f, "  }  // end if low protected mode"
      Print #f, ""
      Print #f, "  if((SCUSLS & 0x1800) == 0x1800)      // if write protected mode"
      Print #f, "  {"
      Print #f, "    SCUSLC = 0xAAAA;                   // command 0"
      Print #f, "    SCUSLC = 0x5554;                   // command 1"
      Print #f, ""
      Print #f, "    ubPASSWORD = SCUSLS & 0x00FF;"
      Print #f, "    ubPASSWORD = ~ubPASSWORD;"
      Print #f, ""
      Print #f, "    SCUSLC = 0x9600 | ubPASSWORD;      // command 2"
      Print #f, "    SCUSLC = 0x0800;                   // command 3; new PASSWOR is 0x00"
      Print #f, ""
      Print #f, "    ubPASSWORD = SCUSLS & 0x00FF;"
      Print #f, "    ubPASSWORD = ~ubPASSWORD;"
      Print #f, "    SCUSLC = 0x8E00 | ubPASSWORD;      // command 4"
      Print #f, ""
      Print #f, "  }  // end if write protected mode"
      Print #f, ""
      Print #f, "} //  End of function " & r.v(sVarPre & "_NAME_" & n)
      Print #f, ""
      Print #f, ""
    End If

    '------------------------------------------------------------------------------------------------
    '------------------------------------------------------------------------------------------------
    ' main function
    '------------------------------------------------------------------------------------------------
    '------------------------------------------------------------------------------------------------
    n = "Main"
'    If (r.v(sVarPre & "_USE_" & n) = 1) Then
      Print #f, FormatFunctionHeader(r, func, sVarPre & "_NAME_" & n)
      Print #f, uc.GetUserCode("(" & n & ",1)", 0)     'USER CODE for application specific descriptions'
      Print #f, ""
      Print #f, FormatFunctionDeclaration(r, func, sVarPre & "_NAME_" & n)
      Print #f, "{"
      Print #f, uc.GetUserCode("(" & n & ",2)", 2)
      Print #f, ""
      Print #f, "  MAIN_vInit();"
      Print #f, ""
      Print #f, uc.GetUserCode("(" & n & ",4)", 2)
      Print #f, ""
      Print #f, "} " & END_OF_FUNCTION & r.v(sVarPre & "_NAME_" & n)
      Print #f, ""
      Print #f, ""
'    End If


    '------------------------------------------------------------------------------------------------
    ' Other function
    '------------------------------------------------------------------------------------------------

    Print #f, ""
    Print #f, uc.GetUserCode("(" & sVarPre & "_General,10)", 0)
    Print #f, ""


    'close file
    Close f
    
    MAINGenerateC = True
    Exit Function
    
MAINGenerateCError:
    Close f
    Exit Function
End Function


'*****************************************************************************
'Description:
'        Generates the code for the MAIN.h file.
'-----------------------------------------------------------------------------
'Parameters:
'        r                reference to the Registers object
'        vIndex           a parameter
'-----------------------------------------------------------------------------
'Returns:
'        True            on successfull operation
'        False           else
'*****************************************************************************
Function MAINGenerateH(r As ProjectData, vIndex As Variant) As Boolean
    On Error GoTo MAINGenerateHError

    MAINGenerateH = False
    
    Dim i As Integer
    Dim f As Variant
    Dim v As Variant
    Dim d As String
    Dim n As String
    Dim dc As DAvECollection
    Dim uc As UserCode
    Dim func As FunctionClass
    Dim sVarPre As String
    Dim mo As ModuleClass

    sVarPre = "MAIN"
   
    Set dc = ObjectCollection("MODULENAMES")
    Set uc = New UserCode
    Set func = New FunctionClass

    'refresh the decriptions of the functions and macros
    RefreshFunctionDescriptions(vIndex, func, r)
    
    'read usercode
    uc.ReadFile ((StripFilenameAndExtension(r.LoadedFile)) & "\" & r.v(sVarPre & "_HFILE"))
    
    'open MAIN.h
    f = FreeFile

    Open CStr(StripFilenameAndExtension(r.LoadedFile)) & "\" & r.v(sVarPre & "_HFILE") For Output As f
    
    '------------------------------------------------------------------------------------------------
    ' module header
    '------------------------------------------------------------------------------------------------
    d = FormatModuleDescription(GetModuleHeaderH(sVarPre))
    Print #f, Rtf.GenerateModuleHeader(DefGetValue("ProductVersion"), StripPath(r.LoadedFile), dc(sVarPre).ModuleDescription, r.v(sVarPre & "_HFILE"), r.v("MAIN_CPU_TYPE"), r.v("MAIN_COMPILER"), d)
            
    Print #f, uc.GetUserCode("(" & sVarPre & "_Header,1)", 0)
    Print #f, ""
    Print #f, Rtf.GenerateNote((r.v(sVarPre & "_Notes")))
    Print #f, ""

'    'Notes for EBC
'    If Not (r.v("EBC_Notes") = "") Then
'        Print #f, Rtf.GenerateNote("Notes of EBC Module:" & vbCrLf & r.v("EBC_Notes"))
'        Print #f, ""
'    End If

    Print #f, "#ifndef _" & StripExtension(r.v(sVarPre & "_HFILE")) & "_H_"
    Print #f, "#define _" & StripExtension(r.v(sVarPre & "_HFILE")) & "_H_"
    Print #f, ""
    Print #f, SECTION_PROJECT_INCLUDES
    Print #f, ""  'DAvE includes'
    Print #f, uc.GetUserCode("(" & sVarPre & "_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("(" & sVarPre & "_Header,3)", 0)
    Print #f, ""
    Print #f, ""
    Print #f, SECTION_DEFINES
    
    If (InStr(r.v("MAIN_Compiler"), "Keil")) Then
      Print #f, "#define KEIL"

      If (r.v("WDT_USE_TriggerWDT") = 1) Then
          Print #f, "#define SRVWDT _srvwdt_()"
      End If

      If (r.v("SCU_USE_Init") = 1) Then
          Print #f, "#define PWRDN _pwrdn_();"
          Print #f, "#define IDLE _idle_();"
      End If

    End If
    If (InStr(r.v("MAIN_Compiler"), "Tasking")) Then
      Print #f, "#define TASKING"

      If (r.v("WDT_USE_TriggerWDT") = 1) Then
          Print #f, "#define SRVWDT _srvwdt()"
      End If

      If (r.v("SCU_USE_Init") = 1) Then
          Print #f, "#define PWRDN _pwrdn();"
          Print #f, "#define IDLE _idle();"
      End If

    End If
    
    Print #f, ""  'DAvE global #define definitions'
    Print #f, uc.GetUserCode("(" & sVarPre & "_Header,4)", 0)
    Print #f, ""
    Print #f, ""
    Print #f, SECTION_SFR_DECLARATION

    ' todo ... begin
    Dim l As Long
    Dim sOldSfr As String
    Dim sOldBlock As String
    Dim iHelp As Integer
    Dim sHelp As String

    Dim lBitCount As Long
    Dim szBitName As String
    Dim szSfrAddress As String
    Dim szSfrName As String
    Dim iBitPos As Integer
    Dim szBitSfrName As String
    Dim iBitWidth As Integer
    Dim bBitAddressable As Boolean

    Const MAX_CHARACTER_BITNAME = 25
    Const MAX_CHARACTER_SFRNAME = 23
    
    Print #f, ""
    Print #f, ""

    '---------------------------------------------------------------------------------------------------------
    'define's for PEC-Registers, da nicht im REGS-File enthalten
    '---------------------------------------------------------------------------------------------------------
    iHelp = MAX_CHARACTER_SFRNAME - 5
    Print #f, "// The source and destination pointers SRCPx and DSTPx"
    v = 0
    For i = 0 To 7
      v = 60480 + i * 4
      Print #f, "#define SRCP" & i & Space(iHelp) & "(*((uword volatile *) " & FormatTextOutput(v, "H4") & "))"
   
      v = 60482 + i * 4
      Print #f, "#define DSTP" & i & Space(iHelp) & "(*((uword volatile *) " & FormatTextOutput(v, "H4") & "))"
    Next i
    '---------------------------------------------------------------------------------------------------------
    'end of define's for PEC-Registers
    '---------------------------------------------------------------------------------------------------------
   
   
    For l = 1 To r.Regs.SfrCount
      r.Regs.SfrIndex = l
   
      ' get values for sfr
      szSfrAddress = r.Regs.SfrAdress
      szSfrName = r.Regs.SfrName
   
      ' print sfr infos
      Print #f, ""
      If (Len(szSfrName) >= MAX_CHARACTER_SFRNAME) Then
        iHelp = 1
      Else
        iHelp = MAX_CHARACTER_SFRNAME - Len(szSfrName)
      End If
      Print #f, "// " & r.Regs.SfrDescription
   
      If (InStr(szSfrAddress, "0x20") = 0) Then
          Print #f, "#define " & szSfrName & Space(iHelp) & "(*((uword volatile *) " & szSfrAddress & "))"
          bBitAddressable = True
      Else
          'ahe 01.10.2001
          'fr TwinCAN data-Page 0x20
          Print #f, "#define " & szSfrName & Space(iHelp) & "(*((uword volatile far *) " & szSfrAddress & "))"
          bBitAddressable = False
      End If
   
      If ((InStr(szSfrAddress, "0xFE") = 0) And (InStr(szSfrAddress, "0xE") = 0)) Then

        For i = 1 To r.Regs.SfrConnectedBitsCount
          r.Regs.BitIndex = r.Regs.SfrConnectedBitsIndex(i)
   
          ' get values for bit
          szBitName = r.Regs.BitName
          szBitSfrName = r.Regs.BitSfrName
          iBitPos = r.Regs.BitPos
          iBitWidth = r.Regs.BitWidth
   
          If (iBitWidth = 1) Then
            ' print bit infos
            ' get only the second part of the bit name
            sHelp = Right(szBitName, Len(szBitName) - Len(szSfrName) - 1)
   
            If (Len(szBitName) >= MAX_CHARACTER_BITNAME) Then
              iHelp = 1
            Else
              iHelp = MAX_CHARACTER_BITNAME - Len(sHelp)
            End If
   
            'check to avoid same name for different bits of same sfr
            If Not (sHelp = "0") Then
              If (bBitAddressable = True) Then
                Print #f, "#define " & szSfrName & "_" & sHelp & Space(iHelp) & "((T_Reg16 *) " & szSfrAddress & ")->bit" & iBitPos
              Else
                Print #f, "#define " & szSfrName & "_" & sHelp & Space(iHelp) & FormatTextOutput(2 ^ iBitPos, "H4")
              End If
            End If

          End If
        Next i
      End If
    Next l
 
    
    Print #f, ""
    Print #f, ""
    ' todo end


    Print #f, SECTION_TYPEDEFS
    Print #f, ""  'DAvE type definitions'
    Print #f, "typedef unsigned char  ubyte;    // 1 byte unsigned; prefix: ub "
    Print #f, "typedef signed char    sbyte;    // 1 byte signed;   prefix: sb "
    Print #f, "typedef unsigned int   uword;    // 2 byte unsigned; prefix: uw "
    Print #f, "typedef signed int     sword;    // 2 byte signed;   prefix: sw "
    Print #f, "typedef unsigned long  ulong;    // 4 byte unsigned; prefix: ul "
    Print #f, "typedef signed long    slong;    // 4 byte signed;   prefix: sl "
    Print #f, ""
    Print #f, "typedef volatile struct"
    Print #f, "{"
    Print #f, "  unsigned int    bit0      : 1;"
    Print #f, "  unsigned int    bit1      : 1;"
    Print #f, "  unsigned int    bit2      : 1;"
    Print #f, "  unsigned int    bit3      : 1;"
    Print #f, "  unsigned int    bit4      : 1;"
    Print #f, "  unsigned int    bit5      : 1;"
    Print #f, "  unsigned int    bit6      : 1;"
    Print #f, "  unsigned int    bit7      : 1;"
    Print #f, "  unsigned int    bit8      : 1;"
    Print #f, "  unsigned int    bit9      : 1;"
    Print #f, "  unsigned int    bit10     : 1;"
    Print #f, "  unsigned int    bit11     : 1;"
    Print #f, "  unsigned int    bit12     : 1;"
    Print #f, "  unsigned int    bit13     : 1;"
    Print #f, "  unsigned int    bit14     : 1;"
    Print #f, "  unsigned int    bit15     : 1;"
    Print #f, "}  T_Reg16;"
    Print #f, ""
    Print #f, uc.GetUserCode("(" & sVarPre & "_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("(" & sVarPre & "_Header,6)", 0)
    Print #f, ""
    Print #f, ""
    Print #f, SECTION_GLOBAL_VARIABLES
    Print #f, ""  'DAvE definition of global variables'
    Print #f, uc.GetUserCode("(" & sVarPre & "_Header,7)", 0)
    Print #f, ""
    Print #f, ""
    Print #f, SECTION_GLOBAL_PROTOTYPES
    Print #f, ""  'DAvE declarations of functions which should become global'
    Print #f, ""
    Print #f, "void " & r.v("MAIN_NAME_UnlockProtecReg") & "(void);"
    Print #f, ""
    Print #f, uc.GetUserCode("(" & sVarPre & "_Header,8)", 0)
    Print #f, ""
    Print #f, ""
                  'DAvE declarations of global macros'


    '------------------------------------------------------------------------------------------------
    ' Interrupt Vectors
    '------------------------------------------------------------------------------------------------
    Print #f, SECTION_INTERRUPT_VECTORS
    Print #f, ""  'DAvE interrupt vector definitions
    Print #f, uc.GetUserCode("(" & sVarPre & "_Header,9)", 0)
    Print #f, ""
    Print #f, ""
    
    '------------------------------------------------------------------------------------------------
    ' Project Includes
    '------------------------------------------------------------------------------------------------
    Print #f, SECTION_PROJECT_INCLUDES
    Print #f, ""  'DAvE project includes
    
    If (InStr(r.v("MAIN_Compiler"), "Keil")) Then
      Print #f, "#include <Intrins.h>"
    End If
    If (InStr(r.v("MAIN_Compiler"), "Tasking")) Then
      Print #f, "#include <C166.h>"
    End If
    
    Print #f, ""

    For Each mo In dc
      
    'If (mo.ModuleName <> "MAIN") Then
    If (mo.ModuleName <> "MAIN" And mo.ModuleName <> "LIN") Then
      If (mo.ModuleWithCG) Then
        If (r.v(mo.ModuleName & "_USE_Init") = 1) Then
          Print #f, "#include  """ & r.v(mo.ModuleName & "_HFile") & """"
        End If
      End If
    End If
    
    Next mo
    Print #f, ""

    Print #f, uc.GetUserCode("(" & sVarPre & "_Header,10)", 0)
    Print #f, ""
    Print #f, ""
    Print #f, "#endif  // ifndef _" & StripExtension(r.v(sVarPre & "_HFILE")) & "_H_"

   
    'close file
    Close f
    
    MAINGenerateH = True
    Exit Function
    
MAINGenerateHError:
    Close f
    Errorbox "Code generation for " & sVarPre & " failed", Err.Description
    Exit Function
End Function

