%%
%%
%%
%%
%%Copyright1994-2019TheMathWorks,Inc.
%%
%%Abstract:
%%LibrarytosupportthenotionofanRTModelobject
%%
 
%if EXISTS("_RTMDLLIB_") == 0
%assign _RTMDLLIB_ = 1
 
%include "rtmspecmacs.tlc"
%include "rtmisreqfcns.tlc"
%include "rtmdllib_obs.tlc"
 
%%------------------------------------------------------------------------------
%%RTMrecordcreationSECTION:
%%------------------------------------------------------------------------------
%%HassupportforcreatingaTLCrecordsthat:
%%-knowaboutthedatafieldsinanrtModel
%%-knowaboutspecialinlineoperationstortModeldatafields
%%------------------------------------------------------------------------------
 
%%Function:DocFunction{OtherUsefulFunctions}LibGetSimStruct===============
%%Abstract:
%%ReturnsthemodelSimStructorSimStructfunctionargumentname
%%
%function LibGetSimStruct() void
  %return SLibCG_GetRTMArgumentName()
%endfunction
 
%%Function:SLibGetSimStruct==================================================
%%Abstract:
%%ReturnsthemodelSimStructorSimStructfunctionargument
%%
%function SLibGetSimStruct() void
  %return SLibCG_GetRTMArgumentName()
%endfunction
 
%%Function:SLibGetSimStructAllocatedVarName
%%Abstract:
%%Returnstheallocatedsimstructvariablename.Weshouldusethisfunction
%%onlywhenitissingle-instancecase.
%%
%function SLibGetSimStructAllocatedVarName() void
  %assert IsModelRefScalableBuild() || !MultiInstanceERTCode
  %return "%<::tSimStruct>_"
%endfunction
 
%%Function:SLibGetSimStructReferenceVarName
%%Abstract:
%%Returnsthereferencedsimstructvariablename.
%%
%function SLibGetSimStructReferenceVarName() void
  %return ::tSimStruct
%endfunction
 
 
%%Function:RTMCreateRTModelRecShell==========================================
%%Abstract:
%%CreateashelltoholdthertModelrecords.
%%
%function RTMCreateRTModelRecShell() void
  %if !EXISTS(RootRTMdlRecs)
    %assign ::RootRTMdlRecNum = 1
    %createrecord ::RootRTMdlRecs {}
    %return 1
  %else
    %return 0
  %endif
%endfunction %% RTMCreateRTModelRecShell
 
 
%%Function:RTMGetRTModelRecShell=============================================
%%Abstract:
%%CreateashelltoholdthertModelrecords.
%%
%function RTMGetRTModelRecShell() void
  %return ::RootRTMdlRecs
%endfunction %% RTMGetRTModelRecShell
 
 
%%Function:SLibRTModelNeedsZCTypes==================================================
%%Abstract:
%%Itispossiblethatthereal-timemodelusestheZCSigStatetypeevenif
%%thistypeisnotrequiredbytherestofthemodel.
%%
%function SLibRTModelNeedsZCTypes() void
 
  %assign needZCTypes = TLC_FALSE
  %if EXISTS(::RootRTMdlRecs)
    %assign rtRecs = RTMGetRTModelRecShell()
    %assign needZCTypes = %<rtRecs.ZCSignalValues.IsRequiredFcn>
  %endif
  %return needZCTypes
   
%endfunction
 
 
%%Function:FcnNeedRTMInMacroArg=============================================
%%Abstract:
%%DoesthemacroneedthertModelintheargmentlist?Incertaincases
%%whenusingtheglobaltimingengineformodelreference,wedonot
%%needthertModelintheargumentlist.
%function FcnNeedRTMInMacroArg(theRec)
  %assert ((theRec.UseRTModelForMR >= 0) && (theRec.UseRTModelForMR < 4))
  %if !IsModelReferenceTarget() || ...
    (theRec.UseRTModelForMR == 2) || ...
    ((theRec.UseRTModelForMR == 1) && IsModelReferenceForASimstructBasedTarget()) || ...
    ((theRec.UseRTModelForMR == 3) && !SuppressErrorStatus)
    %return TLC_TRUE
  %else
    %return TLC_FALSE
  %endif
%endfunction %%FcnNeedRTMInMacroArg
 
%%Function:FcnRTMCreateBaseRec===============================================
%%Abstract:
%%CreatesabasedatarecordforthertModel.
%%
%%Therecordcontainsinformationsuchas:
%%nameofvariableinrtModelstruct,placeinthertModelhierarchyfor
%%thefield,thedatatype,dataqualifier,andwhetherornotthe
%%fieldisrequiredtobepresentunconditionallyinthertModel.
%%
%%Inadditiontoalloftheaboveinformation,therecordalsohas
%%informationonwhetherornotitneedsaspecializedmacrofor
%%forwardingaccessestoSimStructsofchildS-functionstothertModel.
%%SuchmacrosarenecessarybecauseintheeraoftherootSimStruct,
%%childS-functionswouldsometimesreachintotherootSimStructfor
%%theinformation(e.g.ssGetT).Suchaccessesneedtonowbeforwarded
%%tothertModel.
%%
%function FcnRTMCreateBaseRec(rtRec, rName, vName, parent, dType, qual, ...
  ertMac, isReqFcn) void
   
  %addtorecord rtRec ...
  %<rName> { /
    RecType "Variable"; /
    VarRecNumber RootRTMdlRecNum; /
    VarName vName; /
    Parent parent; /
    DataType dType; /
    Qualifier qual; /
    ERTMacro ertMac; /
    StorageType ""; /
    ArrayDims []; /
    IsRequiredFcn isReqFcn; /
    NumSet 0; /
    NumGet 0; /
    TypeStr "" /
  }
   
  %assign ::RootRTMdlRecNum = RootRTMdlRecNum + 1
   
%endfunction %% FcnRTMCreateBaseRec
 
%%Function:FcnShouldGenerateRTM===============================================
%%Abstract:
%%DeterminesifweshouldgenerateRTM
%%
%function FcnShouldGenerateRTM(hStruct)
  %%
  %% Generate typedef from HStruct
  %%
  %% For simplified interface, we populate the default self (RTM) to have pointers to other groups (including default groups)
  %assign defaultSelfMaybeNeeded = ::CompiledModel.ModelRefSimpInterface == "1" && !SLibIsSelfUserDefinedAndStructured()
 
  %% For reusable top model, we always generate RTM. If there are no fields, we add an unused char to avoid compiler warnings.
  %% This is to maintain stable interface for top model entry point functions.
  %% There are some exceptions to this though, one of which is if the user has mapped Self, then we don't need to force
  %% the creation of this legacy RTM since we then use Self coder group to maintain the stable interface.
  %assign forceRTMCreation = MultiInstanceERTCode && !GenerateClassInterface && !SLibUseBackwardCompatibleReusableInterface() && !SLibIsSelfUserDefinedAndStructured()
   
  %return (hStruct.TotalNumFields > 0) || defaultSelfMaybeNeeded || forceRTMCreation
   
%endfunction %% FcnShouldGenerateRTM
 
%%Function:RTMAddRecSclr=====================================================
%%Abstract:
%%CreatesascalardatarecordforthertModel
%%
%function RTMAddRecSclr(rName, vName, parent, dType, qual, ertMac, ...
  isReqFcn) void
  %if qual != "" && qual != "CONST"
    %assign errTxt = "%<qual> is not a valid Qualifier for record '%<rName>'"...
      " in the rtModel object"
    %<LibReportError(errTxt)>
  %endif
  %assign rtRec = RTMGetRTModelRecShell()
  %<FcnRTMCreateBaseRec(rtRec,rName,vName,parent,dType,qual,ertMac,isReqFcn)>
  %assign rtRec.%<rName>.StorageType = "SCALAR"
%endfunction %% RTMAddRecSclr
 
 
%%Function:RTMAddRecPntr=====================================================
%%Abstract:
%%CreatesapointerdatarecordforthertModel
%%
%function RTMAddRecPntr(rName, vName, parent, dType, qual, ertMac, isReqFcn) void
  %assign rtRec = RTMGetRTModelRecShell()
  %<FcnRTMCreateBaseRec(rtRec,rName,vName,parent,dType,qual,ertMac,isReqFcn)>
  %assign rtRec.%<rName>.StorageType = "POINTER"
%endfunction %% RTMAddRecPntr
 
%%Function:RTMAddRecVolatilePntr=====================================================
%%Abstract:
%%CreatesapointerdatarecordforthertModel
%%
%function RTMAddRecVolatilePntr(rName, vName, parent, dType, qual, ertMac, ...
  isReqFcn) void
  %assign rtRec = RTMGetRTModelRecShell()
  %<FcnRTMCreateBaseRec(rtRec,rName,vName,parent,dType,qual,ertMac,isReqFcn)>
  %assign rtRec.%<rName>.StorageType = "VOLATILEPOINTER"
%endfunction %% RTMAddRecPntr
 
%%Function:RTMAddRecPntrPntr=================================================
%%Abstract:
%%CreatesapointerpointerdatarecordforthertModel
%%
%function RTMAddRecPntrPntr(rName, vName, parent, dType, qual, ertMac, ...
  isReqFcn) void
  %assign rtRec = RTMGetRTModelRecShell()
  %<FcnRTMCreateBaseRec(rtRec,rName,vName,parent,dType,qual,ertMac,isReqFcn)>
  %assign rtRec.%<rName>.StorageType = "POINTERPOINTER"
%endfunction %% RTMAddRecPntrPntr
 
%%Function:RTMAddRecArry======================================================
%%Abstract:
%%CreatesanarraydatarecordforthertModel
%%
%function RTMAddRecArry(rName, vName, parent, dType, qual, ertMac, ...
  dims, isReqFcn) void
  %if qual != "" && qual != "CONST"
    %assign errTxt = "%<qual> is not a valid Qualifier for record '%<rName>'"...
      " in the rtModel object"
    %<LibReportError(errTxt)>
  %endif
  %assign rtRec = RTMGetRTModelRecShell()
   
  %<FcnRTMCreateBaseRec(rtRec,rName,vName,parent,dType,qual,ertMac,isReqFcn)>
  %assign rtRec.%<rName>.StorageType = "ARRAY"
  %assign rtRec.%<rName>.ArrayDims = dims
%endfunction %% RTMAddRecArry
 
 
%%Function:RTMAddRecIdxedAccs================================================
%%Abstract:
%%Addarecordthatindicateshowtogeneratedanindexedinlineaccessof
%%avectorrtModelfield.
%%
%%Therecordcontainsinformationsuchas:
%%-nameofvariableinrtModelstructthatisbeingaccessed
%%-informationonwhetherornotweneedtogenerateamacroforthe
%%givenfieldintothertmodel.hfile.Themacrowillbeoftheform
%%rtmGetSampleTime.Itisusedbyfilesinthertw/c/srcdirectory.
%%(Thereasonweusemacrosinrtw/c/src/isthatthesefilesretainthe
%%abilitytorunbasedontherootSimStructinsteadofthertModel.
%%IfweareusingtherootSimStruct,thertmmacrosautomatically
%%getmappedtomacrosfortherootSimStruct).
%%-informationonwhetherornotitneedsaspecializedmacrofor
%%forwardingaccessestoSimStructsofchildS-functionstothertModel.
%%
%function RTMAddRecIdxedAccs(rName, accessedRec) void
  %assign rtRec = RTMGetRTModelRecShell()
   
  %createrecord /
  %<rName> { /
    RecType "IndexedAccess";/
    AccessedRec accessedRec; /
    NumGet 0; /
    NumSet 0 /
  }
   
  %assign rtRec = rtRec + %<rName>
%endfunction %% RTMAddRecIdxedAccs
 
 
%%Function:RTMAddRecSpecialAccs==============================================
%%Abstract:
%%Addarecordthatindicateshowtogeneratedanspecialinlineaccessof
%%avectorrtModelfield.
%%
%%Therecordcontainsinformationsuchas:
%%-namesofthefieldsinrtModelstructthatarebeingaccessed
%%-otherargsusedintheaccess
%%-thespecificaccessmethodtocallinthecaseofa'set','get',
%%or'is'access.
%%-informationonwhetherornotweneedtogenerateamacroforthe
%%givenfieldintothertmodel.hfile.
%%-informationonwhetherornotitneedsaspecializedmacrofor
%%forwardingaccessestoSimStructsofchildS-functionstothertModel.
%%-ForthemodelreferencetargetwithGlobalTimingEngine,thefield
%%UseRTModelForMRspecifieswhetherthemacroshavertModelintheargument
%%list.TheargumentuseTimingBridgespecifiesifanyoftheset,get
%%orisfunctionsneedthetimingbridge.Thesehavenoeffectfor
%%non-modelreferencetargets.
%%
%function RTMAddRecSpecialAccs(rName, getFcn, setFcn, isFcn, oFcn, sva, ...
  nArgs, args, useTimingBridge, useRTModelForMR, ertMac) void
 
  %assign rtRec = RTMGetRTModelRecShell()
   
  %createrecord /
  %<rName> { /
    RecType "SpecialAccess"; /
    ERTMacro ertMac; /
    GetFcn getFcn; /
    SetFcn setFcn; /
    IsFcn isFcn; /
    OtherFcn oFcn; /
    SetHasValArg sva; /
    NumArgs nArgs; /
    Args args; /
    NumGet 0; /
    NumSet 0; /
    UseTimingBridge useTimingBridge /
    UseRTModelForMR useRTModelForMR; /
    Name rName /
  }
   
  %assign rtRec = rtRec + %<rName>
%endfunction %% RTMAddRecSpecialAccs
 
 
%%Function:RTMAddRecDummy====================================================
%%Abstract:
%%AddadummyrecordthatforwardsoldSimStructaccessestonever-never
%%land
%%
%function RTMAddRecDummy(rName) void
  %assign rtRec = RTMGetRTModelRecShell()
 
  %createrecord /
  %<rName> { /
    RecType "Dummy" /
  }
   
  %assign rtRec = rtRec + %<rName>
%endfunction %% RTMAddRecDummy
 
 
%%------------------------------------------------------------------------------
%%RTMaccessSECTION:
%%------------------------------------------------------------------------------
%%ThissectionisdevotedtomethodsthatarecalledfromallovertheTLCcode
%%toaccessafieldoftheRTModel.Theappropriateaccessisgeneratedfrom
%%theinformationinthecorrespondingTLCrecordfortheRTModel.
%%------------------------------------------------------------------------------
 
 
%%Function:FcnRTMGenErr======================================================
%%Abstract:
%%GenerateanRTMError
%%
%function FcnRTMGenErr(errKey, recName) void
  %switch(errKey)
    %case "ACCESSREC_NOT_FOUND"
      %assign errTxt = "RT_MODEL record %<recName> does not have a matching "...
    "access record"
      %break
    %case "RECTYPE_NOT_FOUND"
      %assign errTxt = "RT_MODEL record %<recName> has unknown RecType"
      %break
    %case "FIELD_NOT_FOUND"
      %assign errTxt = "RT_MODEL record %<recName> not found"
      %break
    %case "WRONGTYPE"
      %assign errTxt = "RT_MODEL record %<recName> processed using " ...
    "incorrect TLC function"
      %break
    %case "BADSPECIALACCS"
      %assign errTxt = "RT_MODEL record %<recName> accessed with " ...
    "incorrect special access"
      %break
    %default
      %assign errTxt = "Unknown error occurred in RT_MODEL generation"
      %break
  %endswitch
  %<LibReportError(errTxt)>
%endfunction
 
%function getRTMFieldPointerFromCGType(dataType,varIndex)
  %assign elem = ""
  %switch (dataType)
    %case "PARAMETER"
      %assign varGroupIdx = ...
        FcnSysVarGroupIndex(System[GetBaseSystemIdx()], "Parameter", 0)
      %assign elem = "RVG" + STRING(varGroupIdx)
      %break
    %case "BLOCKIO"
      %assign varGroupIdx = ...
        FcnSysVarGroupIndex(System[GetBaseSystemIdx()], "BlockIO", 0)
      %if SLibGetUseRTMcgType()
        %assign elem = "VG" + STRING(varGroupIdx)
      %else
        %assign elem = "RVG" + STRING(varGroupIdx)
      %endif
      %break
    %case "DWORK"
      %assign varGroupIdx = ...
        FcnSysVarGroupIndex(System[GetBaseSystemIdx()], "DWork", 0)
      %if SLibGetUseRTMcgType()
        %assign elem = "VG" + STRING(varGroupIdx)
      %else
        %assign elem = "RVG" + STRING(varGroupIdx)
      %endif
      %break
    %case "INPUTS"
      %assign varGroupIdx = ...
        FcnSysVarGroupIndex(System[GetBaseSystemIdx()], "ExternalInput", 0)
      %if SLibGetUseRTMcgType()
        %assign elem = "VG" + STRING(varGroupIdx)
      %endif
      %break
    %case "OUTPUTS"
      %assign varGroupIdx = ...
        FcnSysVarGroupIndex(System[GetBaseSystemIdx()], "ExternalOutput", 0)
      %if SLibGetUseRTMcgType()
        %assign elem = "VG" + STRING(varGroupIdx)
      %endif
      %break
    %case "STANDALONE"
      %% Accessed as individual variables
      %assert varIndex >= 0
      %assign elem = varIndex
      %break
    %case "ZC_SIG_STATE"
      %assign varGroupIdx = ...
        FcnSysVarGroupIndex(System[GetBaseSystemIdx()], "ZCEvent", 0)
      %if SLibGetUseRTMcgType()
        %assign elem = "VG" + STRING(varGroupIdx)
      %else
        %assign elem = "RVG" + STRING(varGroupIdx)
      %endif
      %break
    %default
      %break
  %endswitch
  %if !ISEMPTY(elem)
    %return SLibGetFieldPointerFromSelf(elem,TLC_FALSE)
  %else
    %return ""
  %endif
%endfunction
 
%%Function:FcnGenFieldAccessString===========================================
%%Abstract:
%%Generatesastringfortheaccessofaplainfield
%%
%function FcnGenFieldAccessString(theRec,forGetOrSet,optIdx,optSetVal,...
  rtmName) void
  %assign retStr = ""
  %if FcnRTMFieldIsRequired(theRec)
    %<SLibCG_AccessRTM()>
    %assign parent = theRec.Parent
    %assign parentStr = (parent == "") ? "" : "%<parent>."
    %assign derefStr = "->"
    %assign retStr = "%<rtmName>%<derefStr>%<parentStr>%<theRec.VarName>"
  %elseif (SLibGetUseRTMcgType())
    %assign retStr = getRTMFieldPointerFromCGType(theRec.DataType,-1)
  %endif
  %if !ISEMPTY(retStr)
    %assign idxStr = (optIdx == "") ? "" : "[%<optIdx>]"
    %assign retStr = retStr + idxStr
    %if forGetOrSet == "set"
      %assign retStr = retStr + " = (%<optSetVal>)"
    %endif
  %endif
  %return retStr
%endfunction %% FcnGenFieldAccessString
 
 
%%Function:FcnUpdateRecUsage=================================================
%%Abstract:
%%Updatetheusageinfoforarecord
%%
%function FcnUpdateRecUsage(theRec, accessType) void
  %switch (accessType)
    %case "get"
      %assign theRec.NumGet = theRec.NumGet + 1
      %break
    %case "is"
    %case "set"
      %assign theRec.NumSet = theRec.NumSet + 1
      %break
  %endswitch
%endfunction %% FcnUpdateRecUsage
 
%%Function:getReusedParentSystem=====================================
%%Abstract:
%%Helpermethodtogetthecorrectparentreusedsystemforaccessingrtmodel
%%
%function getReusedParentSystem(system)
  %if ISFIELD(system,"RTWSystemCodeOptIntf") || LibIsServer(system)
    %% Consider only public servers, because utility functions are inlined.
    %assign reusedParentSys = System[system.HStructDeclSystemIdx]
  %else
    %assign reusedParentSys = System[system.ReusedParentSystemIdx]
  %endif
  %if LibIsServer(reusedParentSys)
    %assert reusedParentSys.SystemIdx != system.SystemIdx
    %return getReusedParentSystem(reusedParentSys)
  %else
    %return reusedParentSys
  %endif
%endfunction
 
%%Function:FcnUpdateRTModelInterfaceArg=====================================
%%Abstract:
%%UpdatetheinterfaceforasystemtoincludethertModel.
%%
%function FcnUpdateRTModelInterfaceArg(system, rtmName) void
  %% We now put the rtModel as an argument in all reusable functions
  %% if it is used. Previously we only did this for MultiInstanceERTCode.
  %% Guard this with (MultiInstanceERTCode || GenerateSFunction) to get the
  %% old behavior
  %<SLibCG_AccessRTM()>
  %assign outRTMName = rtmName
  %if ::BlockFcn != "Unknown"
    %% We may pass in the HStructDeclSystem when calling this
    %% function, but we want to know the actual system that the
    %% caller lives in. We can get this information if SystemIdx
    %% is in scope.
    %if EXISTS(SystemIdx)
      %assign ownersys = System[SystemIdx]
    %else
      %assign ownersys = system
    %endif
    %assign accessTid = ownersys.CurrentTID
    %assign reusedParentSys = getReusedParentSystem(ownersys)
 
    %% Single-instance and non-inlined Simulink Functions in referenced models,
    %% access the rtModel directly from the global DWork variable.
    %assign modIdx = system.CGIRModuleIdx
    %assign module = ::CompiledModel.RTWCGModules.RTWCGModule[modIdx]
 
    %if module.SimplifiedInterface && !GenerateClassInterface
      %assign outRTMName = LibGetSimStruct()
    %elseif ownersys.CrossNoArgFcnBound
      %<SLibAccessArgHelper(reusedParentSys.Interface.RTMArgDef, "Global",accessTid)>
       
      %% For Simulink Functions, we need to initialize the rtmodel in the start function
      %if LibIsServer(ownersys)
        %assign interf = System[GetBaseSystemIdx()].Interface
         
        %<SLibAccessThisSysFcnArgHelper(interf.RTMArgDef, "Start", "Global", "", TLC_TRUE)>
        %<SLibAccessArg(interf.RTMArgDef, "Start", 0, 0)>
         
        %% Mark this system as accessing canonical parmeters so it is always generated
        %assign interf.CacheCanonicalPrmInStart = TLC_TRUE
      %endif
      %if (UsingMalloc || (MultiInstanceERTCode && !GenerateClassInterface)) && !ISFIELD(reusedParentSys.Interface, "tsysRTM")
        %addtorecord reusedParentSys.Interface tsysRTM ::tSimStruct
      %endif
      %if !(IsModelReferenceSimTarget() && LibIsServer(ownersys) && SLibIsModelScopedServer(ownersys))
        %assign ownerModule = ::CompiledModel.RTWCGModules.RTWCGModule[ownersys.CGIRModuleIdx]
        %if ownerModule.NeedsSimStruct
          %assign outRTMName = LibGetSimStruct()
        %elseif GenerateClassInterface && SLibGetDoesSelfExist()
          %assign outRTMName = "getRTM()"
        %else
          %assign outRTMName = reusedParentSys.Interface.tsysRTM
        %endif
      %else
        %assign outRTMName = "(&" + FcnGetSFcnDWorkIdentifier(System[GetBaseSystemIdx()]) + ".rtm)"
      %endif
    %endif
    %<SLibAccessArgHelper(reusedParentSys.Interface.RTMArgDef,"",accessTid)>
  %endif
   
  %if SLibGetDoesSelfHasCoderDataGroup() && SLibIsSelfStructured() && !SLibCanInlineRTMIntoSelf()
    %assign selfCoderGroupArgumentName = SLibGetSelfCoderGroupArgumentName()
    %if !ISEMPTY(selfCoderGroupArgumentName) && (selfCoderGroupArgumentName == outRTMName)
      %assign fieldname = SLibGetRTMPointerVariableNameInsideSelfStructure()
        %if !ISEMPTY(fieldname)
          %assign outRTMName = outRTMName + "->" + SLibGetRTMPointerVariableNameInsideSelfStructure()
        %endif
    %endif
  %endif
  %if ((IsModelReferenceBaseSys(system) && (IsModelRefScalableBuild() || GenerateClassInterface)) ||...
    (GenerateClassInterface && SLibIsMultiInstanceServer(system)))
    %<SLibCG_UndoAccessRTM()>
  %endif
  %%
  %% Added for ert_main.cpp generation when GenerateClassInterface is selected
  %%
  %if GenerateClassInterface && ERTMainAccess == TLC_TRUE
    %assign outRTMName = "%<CPPObjectName>." + outRTMName
  %endif
  %return outRTMName
%endfunction %% FcnUpdateRTModelInterfaceArg
 
%%Function:FcnGenPlainAccess=================================================
%%Abstract:
%%GenerateaplainaccesstoandatafieldinthertModel.
%%
%function FcnGenPlainAccess(system, recordName, fcnGetOrSet, optIdx, ...
  optSetVal, rtmName) void
   
  %assign rtRecs = RTMGetRTModelRecShell()
  %assign retStr = "ACCESS_ERROR" %% assume
  %assign theRec = rtRecs.%<recordName>
 
  %% Update the rtModel interface argument
  %assign rtmName = FcnUpdateRTModelInterfaceArg(system, rtmName)
   
  %%
  %% Error check to make sure the function is called for the appropriate
  %% record
  %%
  %if (theRec.RecType != "Variable")
    %<FcnRTMGenErr("WRONGTYPE", theRec)>
  %endif
   
  %%
  %% Increment access numbers
  %%
  %<FcnUpdateRecUsage(theRec, fcnGetOrSet)>
   
  %%
  %% Generate the actual access
  %%
  %assign retStr = FcnGenFieldAccessString(theRec,fcnGetOrSet,...
    optIdx, optSetVal, rtmName)
     
  %return retStr
%endfunction %% FcnGenPlainAccess
 
 
%%Function:FcnGenIndexedAccess===============================================
%%Abstract:
%%GenerateanindexedaccesstoandatafieldinthertModel.
%%
%function FcnGenIndexedAccess(system, recordName, fcnGetOrSet, optIdx, ...
  optSetVal, rtmName) void
  %assign rtRecs = RTMGetRTModelRecShell()
  %assign theRec = rtRecs.%<recordName>
 
  %% Update the rtModel interface argument
  %assign rtmName = FcnUpdateRTModelInterfaceArg(system, rtmName)
 
  %%
  %% Error check to make sure the function is called for the appropriate
  %% record
  %%
  %if (theRec.RecType != "IndexedAccess")
    %<FcnRTMGenErr("WRONGTYPE", theRec)>
  %endif
   
  %%
  %% Increment access numbers
  %%
  %<FcnUpdateRecUsage(theRec, fcnGetOrSet)>
   
  %%
  %% Generate the actual access
  %%
  %assign refRec = rtRecs.%<theRec.AccessedRec>
  %assign retStr = FcnGenFieldAccessString(refRec,fcnGetOrSet,...
    optIdx, optSetVal, rtmName)
   
  %return retStr
%endfunction %% FcnGenIndexedAccess
 
 
%%Function:FcnGenSpecialAccess===============================================
%%Abstract:
%%Generateaspecialaccess
%%
%function FcnGenSpecialAccess(system, recordName, accessType, nArgs, args, ...
  optSetVal, rtmName) void
   
  %assign rtRecs = RTMGetRTModelRecShell()
  %assign theRec = rtRecs.%<recordName>
  %if SuppressErrorStatus && recordName == "ErrorStatus"
    %assign rtmName = "0"
  %endif
  %% Update the rtModel interface argument if it is being used in the macro
  %% This is not required for a deployment diagram, since there are not reusable
  %% functions generated for a deployment diagram, and the rtmName is given.
  %if !ISEQUAL(rtmName,"0") && FcnNeedRTMInMacroArg(theRec) && ...
    (!LibIsDeploymentDiagram()) && rtmName != "getRTM()"
    %assign rtmName = FcnUpdateRTModelInterfaceArg(system, rtmName)
  %endif
 
  %if GenerateClassInterface && EXISTS(::GeneratingMainFunction) &&...
    ::GeneratingMainFunction
    %%%if ::CPPObjectName == "this"
    %% %assign rtmName = "this->getRTM()"
    %%%else
     
    %assign rtmName = "%<CPPObjectName>.getRTM()"
     
    %%%endif
     
    %%%assign rtmName = "getRTM()"
  %endif
     
  %%
  %% Error check to make sure the function is called for the appropriate
  %% record
  %%
  %if (theRec.RecType != "SpecialAccess")
    %<FcnRTMGenErr("WRONGTYPE", theRec)>
  %endif
   
  %%
  %% Increment access numbers
  %%
  %<FcnUpdateRecUsage(theRec, accessType)>
 
  %%
  %% Update the global timing bridge accessed flag
  %if IsModelReferenceTarget()
    %assign accFlag = theRec.UseTimingBridge
    %assign needTimingBridge = TLC_FALSE
    %assign needGlobalTID = TLC_FALSE
    %switch accessType
      %case "get"
        %assign needTimingBridge = (accFlag[0] > 0)
        %assign needGlobalTID = (accFlag[0] > 1)
        %break
      %case "set"
        %assign needTimingBridge = (accFlag[1] > 0)
        %assign needGlobalTID = (accFlag[1] > 1)
        %break
      %case "is"
        %assign needTimingBridge = (accFlag[2] > 0)
        %assign needGlobalTID = (accFlag[2] > 1)
        %break
    %endswitch
    %if needTimingBridge
      %assign ::tMdlRefTimingBridgeAccessed = TLC_TRUE
    %endif
    %if needGlobalTID
      %assign ::tMdlRefGlobalTIDMapAccessed = TLC_TRUE
      %assign ::tMdlRefNeedTIDArgs = TLC_TRUE
    %endif
  %endif
   
  %%
  %% Get the name of the macro
  %%
  %assign accFcn = ""
  %switch accessType
    %case "is"
      %assign accFcn = "Is"
      %break
    %case "get"
      %assign accFcn = "Get"
      %break
    %case "set"
      %assign accFcn = "Set"
      %break
    %case "other"
      %assign accFcn = ""
      %break
  %endswitch
   
  %assign comma = ""
  %if FcnNeedRTMInMacroArg(theRec)
    %assign retStr = "rtm%<accFcn>%<recordName>(%<rtmName>"
    %assign comma = ", "
  %else
    %assign retStr = "rtm%<accFcn>%<recordName>("
  %endif
 
  %%
  %% Check that we have the correct number of other args
  %%
  %if theRec.NumArgs != nArgs
    %<FcnRTMGenErr("BADSPECIALACCS", theRec)>
  %endif
   
  %foreach argIdx = theRec.NumArgs
    %assign retStr = retStr + comma
    %assign thisarg = args[argIdx]
    %assign retStr = retStr + thisarg
    %assign comma = ", "
  %endforeach
   
  %if accessType == "set"
    %assign retStr = retStr + comma + optSetVal
  %endif
   
  %assign retStr = retStr + ")"
 
  %return retStr
%endfunction %% FcnGenSpecialAccess
 
 
%<LibAddToCompiledModel("RealTimeModelAccessed", 0)>
 
%%Function:RTMDispatchToAccessFcn============================================
%%Abstract:
%%Dispatchtotheappropriateaccessfunction
%%
%function RTMsDispatchToAccessFcn(system, recordName, fcnGetOrSet, optIdx, ...
  optSetVal, rtmName) void
   
  %assign rtRecs = RTMGetRTModelRecShell()
 
  %if !ISFIELD(rtRecs, recordName)
    %<FcnRTMGenErr("FIELD_NOT_FOUND", recordName)>
  %endif
   
  %assign theRec = rtRecs.%<recordName>
   
  %switch (theRec.RecType)
    %case "Variable"
      %assign retStr = FcnGenPlainAccess(system, recordName, fcnGetOrSet, ...
        optIdx, optSetVal, rtmName)
      %break
    %case "IndexedAccess"
      %assign retStr = FcnGenIndexedAccess(system, recordName, fcnGetOrSet, ...
    optIdx, optSetVal, rtmName)
      %break
    %case "SpecialAccess"
      %if TYPE(optIdx) == "Vector"
        %assign nArgs = SIZE(optIdx,1)
      %else
        %assign nArgs = (optIdx == "") ? 0 : 1
      %endif
      %assign retStr = FcnGenSpecialAccess(system, recordName, fcnGetOrSet, ...
    nArgs, ["%<optIdx>"], optSetVal, rtmName)
      %break
    %case "Dummy"
    %default
      %% Do nothing
      %assign retStr = ""
      %break
  %endswitch
   
  %% Check if we are using a macro that does not need
  %% the RTMODEL in the argument list. This is true for
  %% - clockTick%<idx>
  %% - clockTickH%<idx>
  %% - taskTime
  %% - T
  %% - TPtr
  %% - firstInitCond
  %% - special sample hit
  %% This is specified in the field useRTModelForMR in the special
  %% access macro definition in rtmdldefs.tlc
  %if SuppressErrorStatus && recordName == "ErrorStatus"
    %% do nothing becuase Macro is NoOp
  %elseif !WHITE_SPACE(retStr) && ...
    (theRec.RecType != "SpecialAccess" || FcnNeedRTMInMacroArg(theRec))
    %assign ::CompiledModel.RealTimeModelAccessed = TLC_TRUE
  %endif
  %return retStr
%endfunction
 
 
%%Function:RTMSet============================================================
%%Abstract:
%%Returncodefordoinga"set"onafieldinthertModel
%%
%function RTMsSet(system, recordName, initVal) void
   
  %if GenRTModel
    %%
    %% Take care of the case where people may have given a TLC numeric index
    %%
    %if TYPE(initVal) != "String"
      %assign initVal = "%<initVal>"
    %endif
     
    %if !GenerateClassInterface
      %assign setStr = RTMsDispatchToAccessFcn(system, recordName, "set", "", ...
        initVal, GetSimStructExpr(system,::tSimStruct))
    %else
      %if LibSystemIsReusedFcn(system)
        %assign rtmAccessMethod = ::tSimStruct
      %else
        %assign rtmAccessMethod = "getRTM()"
      %endif
      %assign setStr = RTMsDispatchToAccessFcn(system, recordName, "set", "", ...
        initVal, GetSimStructExpr(system, rtmAccessMethod))
    %endif
  %else
    %assign setStr = "ssSet" + recordName + "(%<SLibGetSimStruct()>, %<initVal>)"
  %endif
   
  %return setStr
%endfunction %% RTMSet
 
 
%%Function:RTMuSet===========================================================
%%Abstract:
%%Returncodefordoinga"set"onafieldinthertModel.Thisfunction
%%isdifferentfromRTMSetinthatitappendsanunderscoreinfront
%%oftheSimStructaccess.WhenwemovetotheactualrtModel,this
%%functioncanbeobsoleted.
%%
%function RTMsuSet(system, recordName, initVal) void
  %assign setStr = RTMsSet(system, recordName, initVal)
  %if !GenRTModel
    %assign setStr = "_%<setStr>"
  %endif
  %return setStr
%endfunction %% RTMuSet
 
 
%%Function:RTMSetIdxed=======================================================
%%Abstract:
%%Returncodefordoinga"set"onafieldinthertModel.Thisfunction
%%isusedwhenanindexingvariableisalsospecified.
%%
%function RTMsSetIdxed(system, recordName, fldIdx, initVal) void
  %if GenRTModel
    %%
    %% Take care of the case where people may have given a TLC numeric index
    %%
    %if TYPE(fldIdx) != "String"
      %assign fldIdx = "%<fldIdx>"
    %endif
    %%
    %% Take care of the case where people may have given a TLC numeric index
    %%
    %if TYPE(initVal) != "String"
      %assign initVal = "%<initVal>"
    %endif
     
    %assign setStr = RTMsDispatchToAccessFcn(system, recordName, "set", fldIdx, ...
      initVal, GetSimStructExpr(system, ::tSimStruct))
  %else
    %assign setStr = "ssSet" + recordName + "(%<SLibGetSimStruct()>, " ...
      "%<fldIdx>, %<initVal>)"
  %endif
  %return setStr
%endfunction %% RTMSetIdxed
 
 
%%Function:RTMuSetIdxed=======================================================
%%Abstract:
%%Returncodefordoinga"set"onafieldinthertModel.Thisfunction
%%isdifferentfromRTMSetinthatitappendsanunderscoreinfront
%%oftheSimStructaccess.WhenwemovetotheactualrtModel,this
%%functioncanbeobsoleted.
%%
%function RTMsuSetIdxed(system, recordName, fldIdx, initVal) void
  %assign setStr = RTMsSetIdxed(system, recordName, fldIdx, initVal)
  %if !GenRTModel
    %assign setStr = "_%<setStr>"
  %endif
  %return setStr
%endfunction %% RTMuSetIdxed
 
 
%%Function:RTMGet============================================================
%%Abstract:
%%Returncodefordoinga"get"onafieldinthertModel
%%
%function RTMsGet(system, recordName) void
  %if GenRTModel
    %assign fldStr = RTMsDispatchToAccessFcn(system, recordName,"get","","",GetSimStructExpr(system, ::tSimStruct))
    %assign getStr = "%<fldStr>"
  %else
    %assign getStr = "ssGet" + recordName + "(%<SLibGetSimStruct()>)"
  %endif
  %return getStr
%endfunction %% RTMGet
 
 
%%Function:RTMuGet===========================================================
%%Abstract:
%%Returncodefordoinga"get"onafieldinthertModel.Thisfunction
%%isdifferentfromRTMGetinthatitappendsanunderscoreinfront
%%oftheSimStructaccess.WhenwemovetotheactualrtModel,this
%%functioncanbeobsoleted.
%%
%function RTMsuGet(system, recordName) void
  %assign getStr = RTMsGet(system, recordName)
  %if !GenRTModel
    %assign getStr = "_%<getStr>"
  %endif
  %return getStr
%endfunction %% RTMuGet
 
 
%%Function:RTMGetIdxed=======================================================
%%Abstract:
%%Returncodefordoinga"get"onafieldinthertModel.Thisfunction
%%isusedwhenanindexingvariableisalsospecified.
%%
%function RTMsGetIdxed(system, recordName, fldIdx) void
  %if GenRTModel
    %%
    %% Take care of the case where people may have given a TLC numeric index
    %%
    %if TYPE(fldIdx) != "String"
      %assign fldIdx = "%<fldIdx>"
    %endif
     
    %assign fldStr = RTMsDispatchToAccessFcn(system, recordName, "get", fldIdx, ...
      "", GetSimStructExpr(system, ::tSimStruct))
    %assign getStr = "%<fldStr>"
  %else
    %assign getStr = "ssGet" + recordName + "(%<SLibGetSimStruct()>, %<fldIdx>)"
  %endif
   
  %return getStr
%endfunction %% RTMGetIdxed
 
 
%%Function:RTMIs=============================================================
%%Abstract:
%%Returncodefordoinga"is"onafieldinthertModel
%%
%function RTMsIs(system, recordName) void
  %if GenRTModel
    %assign isStr = FcnGenSpecialAccess(system, recordName, "is", 0, ...
      [], "", GetSimStructExpr(system, ::tSimStruct))
  %else
    %assign isStr = "ssIs" + recordName + "(%<SLibGetSimStruct()>)"
  %endif
  %return isStr
%endfunction %% RTMIs
 
%%Function:RTMsRaiseEventWithEnqueueUsingRateIndex==============================================
%%Abstract:
%%Returncalltogetscheduleapartitionwithrateindexsti
%%
%function RTMsRaiseEventWithEnqueueUsingRateIndex(system, sti) void
  %if GenRTModel
    %assign scheduleStr = FcnGenSpecialAccess(system, "RaiseEventWithEnqueueUsingRateIndex", ...
      "other", 1, ["%<sti>"], "", ::tSimStruct)
  %else
    %assign scheduleStr = "ssRaiseEventWithEnqueueUsingRateIndex(%<SLibGetSimStruct()>, %<sti>)"
  %endif
  %return scheduleStr
%endfunction %% RTMsRaiseEventWithEnqueueUsingRateIndex
 
%%Function:RTMsDisableTaskUsingRateIndex==============================================
%%Abstract:
%%Returncalltogetdisableapartitionwithrateindexsti
%%
%function RTMsDisableTaskUsingRateIndex(system, sti) void
  %if GenRTModel
    %assign disableStr = FcnGenSpecialAccess(system, "DisableTaskUsingRateIndex", ...
      "other", 1, ["%<sti>"], "", ::tSimStruct)
  %else
    %assign disableStr = "ssDisableTaskUsingRateIndex(%<SLibGetSimStruct()>, %<sti>)"
  %endif
  %return disableStr
%endfunction %% RTMsDisableTaskUsingRateIndex
 
%%Function:RTMsEnableTaskUsingRateIndex==============================================
%%Abstract:
%%Returncalltogetenableapartitionwithrateindexsti
%%
%function RTMsEnableTaskUsingRateIndex(system, sti) void
  %if GenRTModel
    %assign enableStr = FcnGenSpecialAccess(system, "EnableTaskUsingRateIndex", ...
      "other", 1, ["%<sti>"], "", ::tSimStruct)
  %else
    %assign enableStr = "ssEnableTaskUsingRateIndex(%<SLibGetSimStruct()>, %<sti>)"
  %endif
  %return enableStr
%endfunction %% RTMsEnableTaskUsingRateIndex
 
%%Function:RTMsGetTaskTimeCounterForTID==============================================
%%Abstract:
%%ReturncalltogettasktimecounterforgivenTID
%%
%function RTMsGetTaskTimeCounterForTID(system, tid) void
  %assign retVal = RTMsGetTaskTimeCounterForTIDGivenRTM(system, ::tSimStruct, tid)
  %return retVal
%endfunction %% RTMsGetTaskTimeCounterForTID
 
 
%%Function:RTMsGetTaskTimeCounterForTIDGivenRTM======================================
%%Abstract:
%%Returncalltogettasktimecounter
%%forgivenTIDgiventhertModel
%%
%function RTMsGetTaskTimeCounterForTIDGivenRTM(system, rtm, tid) void
  %assert GenRTModel && ...
    SLibIsERTCodeFormat()
  %assign getStr = RTMDispatchToAccessFcn("ClockTick%<tid>", "get", "",...
      "", rtm)
     
  %if SLibClockTickIsUnit32Pair(tid)
    %assert !PurelyIntegerCode
    %assign getStr2 = RTMDispatchToAccessFcn("ClockTickH%<tid>", "get", "",...
      "", rtm) + "* 4294967296.0"
    %assign getStr = "(" + getStr + "+" + getStr2 + ")"
  %endif
   
  %return getStr
%endfunction %% RTMsGetTaskTimeCounterForTIDGivenRTM
 
 
%%Function:RTMsGetTaskTimeForTID==============================================
%%Abstract:
%%ReturncalltogettasktimeforgivenTID
%%
%function RTMsGetTaskTimeForTID(system, tid) void
  %assign retVal = RTMsGetTaskTimeForTIDGivenRTM(system, GetSimStructExpr(system, ::tSimStruct), tid)
  %return retVal
%endfunction %% RTMsGetTaskTimeForTID
 
%%Function:FcnSampleTimeOffsetString======================
%%Abstract:
%%Returnstringtoadjusttasktimewhensampletime
%%offsetisnotzero
%function FcnSampleTimeOffsetString(tid) void
  %assign offset = 0
   
  %% Async sample time doesn't support sample time offset
  %if (SampleTime[tid].Asynchronous == "no")
    %assign offset = PurelyIntegerCode ? ...
      FcnComputeTaskTickOffset(tid) : SampleTime[tid].PeriodAndOffset[1]
  %endif
   
  %if (offset > 0)
    %return " + %<offset>"
  %else
    %return ""
  %endif
   
  %return offsetString
%endfunction %%FcnSampleTimeOffsetString
 
%%Function:FcnSampleTimeResolution=========================
%%Abstract:
%%Resturnstringtomultiplysampletimeresolution
%%
%function FcnSampleTimeResolution(tid)
 
  %% If accessing the sample time directly, disallow sample time inheritance
  %if ISFIELD(::CompiledModel,"ModelRefTsInheritance")
    %assign ::CompiledModel.ModelRefTsInheritance = "DISALLOW_SAMPLE_TIME_INHERITANCE"
  %endif
 
  %assign retStr = ""
  %if SampleTime[tid].ClockTickDataTypeId != tSS_DOUBLE
    %% only integer clock tick has resolution
    %assign res = SampleTime[tid].ClockTickStepSize
    
    %if PurelyIntegerCode
      %assign res = FcnComputeTaskTickLimit(tid)
      %if !ISFIELD(::CompiledModel,"WarnnedAbsTimeOnIntegerCode")
        %<SLibReportWarningWithId("RTW:tlc:AbsTimeOnIntegerCode")>
        %addtorecord ::CompiledModel WarnnedAbsTimeOnIntegerCode TLC_TRUE
      %endif
    %endif
    %% Even res == 1.0, we still emit * 1.0 so that the result is implicitly
    %% casted to a double type.
    %assert res > 0
    %assign retStr = " * %<res>"
  %endif
  %return retStr
%endfunction
 
%%Function:RTMGetTaskTimeForTIDGivenRTM======================================
%%Abstract:
%%ReturncalltogettasktimeforgivenTIDgiventhertModel
%%
%function RTMsGetTaskTimeForTIDGivenRTM(system, rtm, tid) void
  %if GenRTModel
    %<SLibSetNeedAbsoluteTime(tid)>
    %%
    %% Take care of the case where people may have given a TLC numeric index
    %%
    %assign tidStr = (TYPE(tid) != "String") ? "%<tid>" : tid
  
    %if !SLibIsERTCodeFormat()
      %assign getStr = RTMsDispatchToAccessFcn(system,"TaskTime","get",tidStr,"",rtm)
    %else
      %if IsModelReferenceTarget()
        %if IsModelReferenceForASimstructBasedTarget()
          %assign getStr = RTMsDispatchToAccessFcn(system,"TaskTime","get",tidStr,"",rtm)
        %else
          %% We should only access the tPtr from the timing bridge if we know
          %% the pointer will be filled in by the parent, so we need to
          %% specify that the taskTime has been accessed.
          %if SampleTime[tid].NeedFloatTime == "yes"
            %assign base = "%<SLibGetGlobalTimingBridge()>->taskTime"
            %assign indx = "%<FcnGetMdlRefGlobalTIDMap("")>[%<tid>]"
            %return "(*(%<base>[%<indx>]))"
          %else
            %assign tic = RTMGet("ClockTick%<tid>")
            %if SLibClockTickIsUnit32Pair(tid) && !PurelyIntegerCode
              %% PurelyIntegerCode does not support timer data type tSS_TIMER_UINT32_PAIR
              %assign highTic = RTMGet("ClockTickH%<tid>")
              %assign tic = "( %<tic> + %<highTic>*4294967296.0 )"
            %endif
            %assign getStr = "(%<tic>%<FcnSampleTimeResolution(tid)>%<FcnSampleTimeOffsetString(tid)>)"
          %endif
        %endif
      %elseif SampleTime[tid].NeedFloatTime == "yes"
    %if RTMTaskTimeIsReqFcnForTID(tid)
      %assign getStr = RTMDispatchToAccessFcn("TaskTime%<tid>", "get", "", ...
        "", rtm)
    %else
      %assert RTMTimePtrIsReqFcn()
      %assign getStr = RTMDispatchToAccessFcn("TimePtr", "get", "","", rtm)
      %assign getStr = getStr + "[%<tid>]"
    %endif
      %else
    %% Integer base time. Calculate tasktime from
    %% integer counter and resulution.
    %assign getStr = "((" + ...
      RTMsGetTaskTimeCounterForTIDGivenRTM(system, rtm, tid) + ...
          ") %<FcnSampleTimeResolution(tid)>" + ...
          "%<FcnSampleTimeOffsetString(tid)>)"
      %endif
    %endif
  %else
    %assign getStr = "ssGetTaskTime(%<LibGetSimStruct()>,%<tid>)"
  %endif
  %return getStr
%endfunction %% RTMGetTaskTimeForTIDGivenRTM
 
 
%%Function:RTMGetTaskTime====================================================
%%Abstract:
%%Returncalltogettasktime
%%
%function RTMsGetTaskTime(system) void
  %return RTMsGetTaskTimeForTID(system, LibTID())
%endfunction %% RTMGetTaskTime
 
 
%%Function:RTMIsContinuousTask===============================================
%%Abstract:
%%Returncalltocheckifcontinoustask
%%
%function RTMsIsContinuousTask(system) void
  %if ((::BlockFcn == "Derivative") || (::BlockFcn == "ForcingFunction") || (::BlockFcn == "MassMatrix"))
    %assign activeTid = 0
  %elseif ::isRAccel
    %assign activeTid = 0
  %else
    %assign activeTid = LibTID()
  %endif
  %if IsModelReferenceForASimstructBasedTarget()
    %assign simS = RTMsGet(system, "MdlRefSfcnS")
    %assign isStr ="ssIsContinuousTask(%<simS>, %<activeTid>)"
  %else
    %if SLibSingleTasking()
      %return "1"
    %elseif GenRTModel
      %assign isStr = FcnGenSpecialAccess(system, "ContinuousTask", "is", 1, ...
        ["%<activeTid>"], "", ::tSimStruct)
    %else
      %assign isStr = "ssIsContinuousTask(%<SLibGetSimStruct()>, %<activeTid>)"
    %endif
  %endif
  %return isStr
%endfunction %% RTMIsContinuousTask
 
 
%%Function:RTMIsSampleHit====================================================
%%Abstract:
%%Returncalltocheckifsamplehit
%%
%function RTMsIsSampleHit(system, tid) void
  %if ((::BlockFcn == "Derivative") || (::BlockFcn == "ForcingFunction") || (::BlockFcn == "MassMatrix"))
    %assign activeTid = 0
  %elseif ::isRAccel
    %assign activeTid = 0
  %else
    %assign activeTid = LibTID()
  %endif
  %if GenRTModel
    %assign useCppAccessMethod = GenerateClassInterface && ...
                                 (system.SystemIdx == GetBaseSystemIdx() || system.RTWSystemCode != 2 || ...
                                  SLibReusableSubsystemCppEncapEnabled())
    %assign isStr = FcnGenSpecialAccess(system, "SampleHit", "is", 2, ...
      ["%<tid>", "%<activeTid>"], "", useCppAccessMethod ? "getRTM()" : ::tSimStruct)
  %else
    %assign isStr = "ssIsSampleHit(%<SLibGetSimStruct()>, %<tid>, %<activeTid>)"
  %endif
  %return isStr
%endfunction %% RTMIsSampleHit
 
 
%%Function:RTMIsSpecialSampleHit=============================================
%%Abstract:
%%Returncalltocheckifspecialsamplehit
%%
%function RTMsIsSpecialSampleHit(system, sti, tid) void
  %if GenRTModel
    %assign useCppAccessMethod = GenerateClassInterface && ...
                                (system.SystemIdx == GetBaseSystemIdx() || system.RTWSystemCode != 2 || ...
                                 CGMODEL_ACCESS("CGModel.ReusableSubsystemCppEncap"))
    %assign isStr = FcnGenSpecialAccess(system, "SpecialSampleHit", "is", 3, ...
      ["%<sti>", "%<tid>", "%<LibTID()>"], "", useCppAccessMethod ? "getRTM()" : ::tSimStruct)
  %else
    %if ::isRAccel
      %assign activeTid = 0
    %else
      %assign activeTid = LibTID()
    %endif
    %assign isStr = ...
      "ssIsSpecialSampleHit(%<SLibGetSimStruct()>,%<sti>,%<tid>,%<activeTid>)"
  %endif
  %return isStr
%endfunction %% RTMIsSpecialSampleHit
 
 
%%Function:RTMChkMemAndReturnIfErr===========================================
%%Abstract:
%%ReturnacallforvalidatingmemoryinthertModel
%%
%function RTMsChkMemAndReturnIfErr(system, ptr) void
  %if CodeFormat != "S-Function"
    %assign validateStr = "rt_VALIDATE_MEMORY"
  %else
    %assign validateStr = "ss_VALIDATE_MEMORY"
  %endif
  %assign vStr = "%<validateStr>(%<SLibGetSimStruct()>," + ptr + ")"
  %return vStr
%endfunction %% RTMChkMemAndReturnIfErr
 
 
%%Function:RTMsSetBlkStateChange============================================
%%Abstract:
%%SetsBlkStateChangeflag.
%%
%function RTMsSetBlkStateChange(system) void
  %if IsModelReferenceForASimstructBasedTarget()
    %assign simS = RTMsGet(system, "MdlRefSfcnS")
    %assign setStr = "ssSetBlkStateChange(%<simS>)"
  %else
    %if GenRTModel
      %if SLibIsERTCodeFormat() && !IsModelReferenceTarget()
        %assign rts = "%<RTMGetSolverInfo()>"
      %else
        %assign rts = RTMsGet(system, "RTWSolverInfo")
      %endif
      %assign setStr = "rtsiSetBlkStateChange(%<rts>, %)"
    %else
      %assign setStr = "ssSetBlkStateChange(%<SLibGetSimStruct()>)"
    %endif
  %endif
  %if !ISFIELD(::CompiledModel, "HasContTimeOutputInconsistentWithStateAtMajorStep")
    %addtorecord ::CompiledModel HasContTimeOutputInconsistentWithStateAtMajorStep TLC_TRUE
  %endif
  %return setStr
%endfunction %% RTMsSetBlkStateChange
 
 
%%Function:RTMsGetBlkStateChange============================================
%%Abstract:
%%GetsBlkStateChangeflag.
%%
%function RTMsGetBlkStateChange(system) void
  %if IsModelReferenceForASimstructBasedTarget()
    %<SLibCG_AccessRTM()>
    %assign simS = RTMsGet(system, "MdlRefSfcnS")
    %assign getStr = "ssGetBlkStateChange(%<simS>)"
  %else
    %if GenRTModel
      %if SLibIsERTCodeFormat() && !IsModelReferenceTarget()
        %assign rts = "%<RTMGetSolverInfo()>"
      %else
        %assign rts = RTMsGet(system, "RTWSolverInfo")
      %endif
      %assign getStr = "rtsiGetBlkStateChange(%<rts>)"
    %else
      %assign getStr = "ssGetBlkStateChange(%<SLibGetSimStruct()>)"
    %endif
  %endif
  %return getStr
%endfunction %% RTMsGetBlkStateChange
 
%%Function:RTMsClearBlkStateChange==============================================
%%Abstract:
%%ClearBlkStateChangeflag.
%%
%%Function:RTMsClearBlkStateChange============================================
%%Abstract:
%%clearBlkStateChangeflag.
%%
%function RTMsClearBlkStateChange(system) void
  %if IsModelReferenceForASimstructBasedTarget()
    %assign simS = RTMsGet(system, "MdlRefSfcnS")
    %assign setStr = "ssClearBlkStateChange(%<simS>)"
  %else
    %if GenRTModel
      %if SLibIsERTCodeFormat() && !IsModelReferenceTarget()
        %assign rts = "%<RTMGetSolverInfo()>"
      %else
        %assign rts = RTMsGet(system, "RTWSolverInfo")
      %endif
      %assign setStr = "rtsiSetBlkStateChange(%<rts>, %)"
    %else
      %assign setStr = "ssClearBlkStateChange(%<SLibGetSimStruct()>)"
    %endif
  %endif
  %return setStr
%endfunction %% RTMsClearBlkStateChange
 
 
%%Function:RTMsSetContTimeOutputInconsistentWithStateAtMajorStep=============
%%Abstract:
%%Signalthattheblockoutputatmajortimeisconsistentwithitsstate
%%
%function RTMsSetContTimeOutputInconsistentWithStateAtMajorStep(system) void
  %if IsModelReferenceForASimstructBasedTarget()
    %assign simS = RTMsGet(system, "MdlRefSfcnS")
    %assign setStr = "ssSetContTimeOutputInconsistentWithStateAtMajorStep(%<simS>)"
  %else
    %if GenRTModel
      %if SLibIsERTCodeFormat() && !IsModelReferenceTarget()
        %assign rts = "%<RTMGetSolverInfo()>"
      %else
        %assign rts = RTMsGet(system, "RTWSolverInfo")
      %endif
      %assign setStr = "rtsiSetContTimeOutputInconsistentWithStateAtMajorStep(%<rts>, %)"
    %else
      %assign setStr = "ssSetContTimeOutputInconsistentWithStateAtMajorStep(%<SLibGetSimStruct()>)"
    %endif
  %endif
  %if !ISFIELD(::CompiledModel, "HasContTimeOutputInconsistentWithStateAtMajorStep")
    %addtorecord ::CompiledModel HasContTimeOutputInconsistentWithStateAtMajorStep TLC_TRUE
  %endif
  %return setStr
%endfunction %% RTMsSetContTimeOutputInconsistentWithStateAtMajorStep
 
 
%%Function:RTMsGetContTimeOutputInconsistentWithStateAtMajorStep============
%%Abstract:
%%getflagthatsignalsthattheblockoutputatmajortimeisconsistentwith
%%itsstate
%%
%function RTMsGetContTimeOutputInconsistentWithStateAtMajorStep(system) void
  %if IsModelReferenceForASimstructBasedTarget()
    %<SLibCG_AccessRTM()>
    %assign simS = RTMsGet(system, "MdlRefSfcnS")
    %assign getStr = "ssGetContTimeOutputInconsistentWithStateAtMajorStep(%<simS>)"
  %else
    %if GenRTModel
      %if SLibIsERTCodeFormat() && !IsModelReferenceTarget()
        %assign rts = "%<RTMGetSolverInfo()>"
      %else
        %assign rts = RTMsGet(system, "RTWSolverInfo")
      %endif
      %assign getStr = "rtsiGetContTimeOutputInconsistentWithStateAtMajorStep(%<rts>)"
    %else
      %assign getStr = "ssGetContTimeOutputInconsistentWithStateAtMajorStep(%<SLibGetSimStruct()>)"
    %endif
  %endif
  %return getStr
%endfunction %% RTMsGetContTimeOutputInconsistentWithStateAtMajorStep
 
%%Function:RTMsClearContTimeOutputInconsistentWithStateAtMajorStep==============================================
%%Abstract:
%%ClearContTimeOutputInconsistentWithStateAtMajorStepflag.
%%
%function RTMsClearContTimeOutputInconsistentWithStateAtMajorStep(system) void
  %if IsModelReferenceForASimstructBasedTarget()
    %assign simS = RTMsGet(system, "MdlRefSfcnS")
    %assign setStr = "ssClearContTimeOutputInconsistentWithStateAtMajorStep(%<simS>)"
  %else
    %if GenRTModel
      %if SLibIsERTCodeFormat() && !IsModelReferenceTarget()
        %assign rts = "%<RTMGetSolverInfo()>"
      %else
        %assign rts = RTMsGet(system, "RTWSolverInfo")
      %endif
      %assign setStr = "rtsiSetContTimeOutputInconsistentWithStateAtMajorStep(%<rts>, %)"
    %else
      %assign setStr = "ssClearContTimeOutputInconsistentWithStateAtMajorStep(%<SLibGetSimStruct()>)"
    %endif
  %endif
  %return setStr
%endfunction %% RTMsClearContTimeOutputInconsistentWithStateAtMajorStep
 
%%Function:RTMsSetBlockStateForSolverChangedAtMajorStep=============
%%Abstract:
%%Signalthattheblockoutputatmajortimeisconsistentwithitsstate
%%
%function RTMsSetBlockStateForSolverChangedAtMajorStep(system) void
  %if IsModelReferenceForASimstructBasedTarget()
    %assign simS = RTMsGet(system, "MdlRefSfcnS")
    %assign setStr = "ssSetBlockStateForSolverChangedAtMajorStep(%<simS>)"
     
    %assign ::CompiledModel.ReferencedModelMayResetSolver = TLC_TRUE
  %else
    %if GenRTModel
      %if SLibIsERTCodeFormat() && !IsModelReferenceTarget()
        %assign rts = "%<RTMGetSolverInfo()>"
      %else
        %assign rts = RTMsGet(system, "RTWSolverInfo")
      %endif
      %assign setStr = "rtsiSetBlockStateForSolverChangedAtMajorStep(%<rts>, %)"
    %else
      %assign setStr = "ssSetBlockStateForSolverChangedAtMajorStep(%<SLibGetSimStruct()>)"
    %endif
  %endif
  %return setStr
%endfunction %% RTMsSetBlockStateForSolverChangedAtMajorStep
 
%%Function:RTMGetErrStat=====================================================
%%Abstract:
%%Returncodefordoinga"get"onErrorStatusfieldinthertModel
%%
%function RTMsGetErrStat(system) void
  %if IsModelReferenceForASimstructBasedTarget()
    %assign simS = RTMsGet(system, "MdlRefSfcnS")
    %return "ssGetErrorStatus(%<simS>)"
  %endif
  %return RTMsGet(system, "ErrorStatus")
%endfunction %% RTMGetErrStat
 
 
%%Function:RTMSetErrStat=====================================================
%%Abstract:
%%Returncodeforsettingtheerrorstatus
%%
%function RTMsSetErrStat(system, errStat) void
  %if IsModelReferenceForASimstructBasedTarget()
    %assign simS = RTMsGet(system, "MdlRefSfcnS")
    %return "ssSetErrorStatus(%<simS>, %<errStat>)"
  %endif
  %return RTMsSet(system, "ErrorStatus", errStat)
%endfunction %% RTMSetErrStat
 
%%Function:RTMsGetAbsTolVector============================================
%%Abstract:
%%Gettheabsolutetolerancevector.
%%
%function RTMsGetAbsTolVector(system)
  %if IsModelReferenceForASimstructBasedTarget()
    %assign simS = RTMsGet(system, "MdlRefSfcnS")
    %assign setStr = "ssGetAbsTolVector(%<simS>)"
  %else
    %assign setStr = "ssGetAbsTolVector(%<SLibGetSimStruct()>)"
  %endif
  %return setStr
%endfunction %% RTMGetAbsTolVector
 
%%Function:RTMsGetAbsTolControlVector========================================
%%Abstract:
%%Gettheabsolutetolerancecontrolvector.
%%
%function RTMsGetAbsTolControlVector(system)
  %if IsModelReferenceForASimstructBasedTarget()
    %assign simS = RTMsGet(system, "MdlRefSfcnS")
    %assign setStr = "ssGetAbsTolControlVector(%<simS>)"
  %else
    %assign setStr = "ssGetAbsTolControlVector(%<SLibGetSimStruct()>)"
  %endif
  %return setStr
%endfunction %% RTMGetAbsTolControlVector
 
 
 
%%Function:RTMsGetPerturbMinVector============================================
%%Abstract:
%%Gettheperturbminvector
%%
%function RTMsGetPerturbMinVector(system)
  %if IsModelReferenceForASimstructBasedTarget()
    %assign simS = RTMsGet(system, "MdlRefSfcnS")
    %assign setStr = "ssGetJacobianPerturbationBoundsMinVec(%<simS>)"
  %else
    %assign setStr = "ssGetJacobianPerturbationBoundsMinVec(%<SLibGetSimStruct()>)"
  %endif
  %return setStr
%endfunction %% RTMGetPerturbMinVector
 
%%Function:RTMsGetPerturbMaxVector============================================
%%Abstract:
%%Gettheperturbmaxvector
%%
%function RTMsGetPerturbMaxVector(system)
  %if IsModelReferenceForASimstructBasedTarget()
    %assign simS = RTMsGet(system, "MdlRefSfcnS")
    %assign setStr = "ssGetJacobianPerturbationBoundsMaxVec(%<simS>)"
  %else
    %assign setStr = "ssGetJacobianPerturbationBoundsMaxVec(%<SLibGetSimStruct()>)"
  %endif
  %return setStr
%endfunction %% RTMGetPerturbMaxVector
 
 
 
%%Function:RTMSetSolverNeedsReset============================================
%%Abstract:
%%Setssolverneedsresetflag.
%%
%function RTMsSetSolverNeedsReset(system) void
  %if IsModelReferenceForASimstructBasedTarget()
    %assign simS = RTMsGet(system, "MdlRefSfcnS")
    %assign setStr = "ssSetSolverNeedsReset(%<simS>)"
     
    %assign ::CompiledModel.ReferencedModelMayResetSolver = TLC_TRUE
  %else
    %if GenRTModel
      %if SLibIsERTCodeFormat() && !IsModelReferenceTarget()
        %assign rts = "%<RTMGetSolverInfo()>"
        %assign setStr = "rtsiSetSolverNeedsReset(%<rts>, %)"
      %else
        %assign rts = RTMsGet(system, "RTWSolverInfo")
        %assign setStr = "rtsiSetSolverNeedsReset(%<rts>, %)"
      %endif
    %else
      %assign setStr = "ssSetSolverNeedsReset(%<SLibGetSimStruct()>)"
    %endif
  %endif
  %return setStr
%endfunction %% RTMSetSolverNeedsReset
 
%%Function:RTMsGetBlockStateForSolverChangedAtMajorStep============================================
%%Abstract:
%%Getstheflagtoindicatethatblockstatehaschangedatmajorstep
%%(output/update).Thisflagisusedbycontinuousblocks.
%%
%function RTMsGetBlockStateForSolverChangedAtMajorStep(system) void
  %if IsModelReferenceForASimstructBasedTarget()
    %assign simS = RTMsGet(system, "MdlRefSfcnS")
    %assign setStr = "ssGetBlockStateForSolverChangedAtMajorStep(%<simS>)"
  %else
    %if GenRTModel
      %if SLibIsERTCodeFormat() && !IsModelReferenceTarget()
        %assign rts = "%<RTMGetSolverInfo()>"
        %assign setStr = "rtsiGetBlockStateForSolverChangedAtMajorStep(%<rts>, %)"
      %else
        %assign rts = RTMsGet(system, "RTWSolverInfo")
        %assign setStr = "rtsiGetBlockStateForSolverChangedAtMajorStep(%<rts>, %)"
      %endif
    %else
      %assign setStr = "ssGetBlockStateForSolverChangedAtMajorStep(%<SLibGetSimStruct()>)"
    %endif
  %endif
  %return setStr
%endfunction %% RTMsGetBlockStateForSolverChangedAtMajorStep
 
 
%%Function:RTMModelMthsSet======================================================
%%Abstract:
%%Setamodel-methodsfield
%%
%function RTMsModelMthsSet(system, fldName,sVal) void
  %if GenRTModel
    %assign rts = RTMsGet(system, "RTWRTModelMethodsInfo")
    %assign transFldName = "UNHANDLED_FIELD"
    %switch fldName
      %case "mdlInitializeSizes"
    %assign transFldName = "InitSizesFcn"
    %break
      %case "mdlInitializeSampleTimes"
    %assign transFldName = "InitSampTimesFcn"
    %break
      %case "mdlStart"
    %assign transFldName = "StartFcn"
    %break
      %case "mdlOutputs"
    %assign transFldName = "OutputsFcn"
    %break
      %case "mdlUpdate"
    %assign transFldName = "UpdateFcn"
    %break
      %case "mdlDerivatives"
    %assign transFldName = "DervisFcn"
    %break
      %case "mdlProjection"
    %assign transFldName = "ProjectionFcn"
    %break
      %case "mdlForcingFunction"
    %assign transFldName = "ForcingFunctionFcn"
    %break
      %case "mdlMassMatrix"
    %assign transFldName = "MassMatrixFcn"
    %break
      %case "mdlTerminate"
    %assign transFldName = "TerminateFcn"
    %break
      %case "mdlDiscreteEvents"
    %assign transFldName = "DiscreteEventsFcn"
    %break
      %case "RTModelPtr"
    %assign transFldName = "RTModelPtr"
    %break
      %default
    %% BEGIN_ASSERT
    %break
    %% END_ASSERT
    %endswitch
    %assign setStr = "rtmiSet%<transFldName>((%<rts>), %<sVal>)"
  %else
    %assert fldName != "RTModelPtr"
    %assign setStr = "ssSet%<fldName>(%<SLibGetSimStruct()>, %<sVal>)"
  %endif
  %return setStr
%endfunction %% RTMModelMthsSet
 
 
%%Function:RTMsSolverSet=====================================================
%%Abstract:
%%Setasolver-specificfield
%%
%function RTMsSolverSet(system, fldName,sVal) void
  %if GenRTModel
    %if SLibIsERTCodeFormat()
      %assign rts = "%<RTMGetSolverInfo()>"
    %else
      %assign rts = RTMsGet(system, "RTWSolverInfo")
    %endif
    %assign setStr = "rtsiSet%<fldName>(%<rts>, %<sVal>)"
  %else
    %assign setStr = "ssSet%<fldName>(%<SLibGetSimStruct()>, %<sVal>)"
  %endif
  %return setStr
%endfunction %% RTMsSolverSet
 
 
%%Function:RTMSolverGet======================================================
%%Abstract:
%%Getasolver-specificfield
%%
%function RTMsSolverGet(system, fldName) void
  %if IsModelReferenceForASimstructBasedTarget()
    %assign simS = RTMsGet(system, "MdlRefSfcnS")
    %assign getStr = "ssGet%<fldName>(%<simS>)"
  %else
    %if GenRTModel
      %if SLibIsERTCodeFormat() && !IsModelReferenceTarget()
        %assign rts = RTMGetSolverInfo()
      %else
        %assign rts = RTMsGet(system, "RTWSolverInfo")
      %endif
      %assign getStr = "rtsiGet%<fldName>(%<rts>)"
    %else
      %assign getStr = "ssGet%<fldName>(%<SLibGetSimStruct()>)"
    %endif
  %endif
  %return getStr
%endfunction %% RTMSolverGet
 
 
%%Function:RTMSolverIs======================================================
%%Abstract:
%%Queryasolver-specificfield
%%
%function RTMsSolverIs(system, fldName) void
  %if IsModelReferenceForASimstructBasedTarget()
    %assign simS = RTMsGet(system, "MdlRefSfcnS")
    %assign isStr = "ssIsSolver%<fldName>(%<simS>)"
  %else
    %if GenRTModel
      %if SLibIsERTCodeFormat() && !IsModelReferenceTarget()
        %assign rts = RTMGetSolverInfo()
      %else
        %assign rts = RTMsGet(system, "RTWSolverInfo")
      %endif
      %assign isStr = "rtsiIsSolver%<fldName>(%<rts>)"
    %else
      %assign isStr = "ssIsSolver%<fldName>(%<SLibGetSimStruct()>)"
    %endif
  %endif
  %return isStr
%endfunction %% RTMSolverIs
 
 
%%Function:RTMSolverAssertCheck==============================================
%%Abstract:
%%Usedwithacceleratortogenerateconditionalsforthe
%%Simulinkconsistencychecker.
%%
%function RTMsSolverAssertCheck(system) void
  %if IsModelReferenceSimTarget()
    %assign simS = RTMsGet(system, "MdlRefSfcnS")
  %else
    %assert !GenRTModel
    %assign simS = SLibGetSimStruct()
  %endif
  %assign setStr = "_ssGetSolverAssertCheck(%<simS>)"
  %return setStr
%endfunction %% RTMSolverAssertCheck
 
 
%%Function:RTMLoggingSet=====================================================
%%Abstract:
%%ReturncodeforsettingaloggingrelatedfieldintheSimStruct.
%%
%function RTMsLoggingSet(system, recordName, initVal) void
  %if recordName == "RTWLogInfo"
    %openfile setFile
    %if SLibIsERTCodeFormat()
      %<RTMGetLoggingObject()> = %<initVal>;
    %else
      %<RTMsSet(system, "RTWLogInfo", "%<initVal>")>;
    %endif
    %closefile setFile
  %else
    %openfile setFile
    %assign setStr = "rtliSet" + recordName + ...
      "(%<RTMGetLoggingObject()>, %<initVal>)"
    %<setStr>;
    %closefile setFile
  %endif
   
  %return setFile
%endfunction %% RTMLoggingSet
   
 
%%Function:RTMLoggingGet=====================================================
%%Abstract:
%%ReturncodeforgettingaloggingrelatedfieldintheSimStruct.
%%
%function RTMsLoggingGet(system, recordName) void
  %assign setStr = "rtliGet" + recordName + ...
    "(%<RTMGetLoggingObject()>)"
   
  %return setStr
%endfunction %% RTMLoggingGet
   
 
%%Function:RTMGetModelSS=====================================================
%%Abstract:
%%ReturnsmodelSimStructwhenexplicitlyneeded.Thisisatemporary
%%functiontohelpmigrateawayfromtherootSimStruct
%%
%function RTMsGetModelSS(system,getAddressTakenCareOf) void
  %if getAddressTakenCareOf
    %if GenerateClassInterface && system.SystemIdx != GetBaseSystemIdx()
      %assign symbolName = "getRTM()"
    %else
      %assign symbolName = ::tSimStruct
    %endif
  %else
    %assign symbolName = GetSimStructExpr(system, ::tSimStruct)
  %endif
  %assign rtmName = FcnUpdateRTModelInterfaceArg(system, symbolName)
  %return rtmName
%endfunction %% RTMGetRootSS
 
%endif %% _RTMDLLIB_
 
 
%%Function:RTMUpdateIntegerAbsoluteTime======================================
%%Abstract:
%%UsedcurrentlybyERTtoupdatetime.ItisnotarealSimStrucmacro.
%%
%function RTMsUpdateIntegerAbsoluteTime(system) void
  %if GenRTModel
    %assign updStr = FcnGenSpecialAccess(system, "UpdateIntegerAbsoluteTime", ...
      "other", 0, [], "", ::tSimStruct)
  %else
    %assign updStr = "ssUpdateIntegerAbsoluteTime(%<SLibGetSimStruct()>)"
  %endif
  %return updStr
%endfunction %% RTMUpdateIntegerAbsoluteTime
 
 
%%Function:RTMUpdateRealAbsoluteTime======================================
%%Abstract:
%%UsedcurrentlybyERTtoupdatetime.ItisnotarealSimStrucmacro.
%%
%function RTMsUpdateRealAbsoluteTime(system) void
  %if GenRTModel
    %assign updStr = FcnGenSpecialAccess(system, "UpdateRealAbsoluteTime", ...
      "other", 0, [], "", ::tSimStruct)
  %else
    %assign updStr = "ssUpdateRealAbsoluteTime(%<SLibGetSimStruct()>)"
  %endif
  %return updStr
%endfunction %% RTMUpdateRealAbsoluteTime
 
%%Function:RTMUpdateRealAbsoluteTimeForTID===================================
%%Abstract:
%%UsedcurrentlybyERTtoupdatetimeforTID.ItisnotarealSimStrucmacro.
%%
%function RTMsUpdateRealAbsoluteTimeForTID(system, tid) void
  %assign updateRealTimeFromSolverInfo = ...
    (ISEQUAL(tid,0) || ISEQUAL(tid, "")) && ((NumContStates > 0) || ...
    (GenerateGRTWrapper && UsingMalloc))
  %if GenRTModel
    %assign offsetStr = FcnSampleTimeOffsetString(tid)
    %if SLibClockTickIsUnit32Pair(tid)
      %assign ct = RTMDispatchToAccessFcn("ClockTick%<tid>", "get", ...
    "", "", GetSimStructExpr(system, ::tSimStruct))
      %assign cth = RTMDispatchToAccessFcn("ClockTickH%<tid>", "get", ...
    "", "", GetSimStructExpr(system, ::tSimStruct))
      %assign ss = RTMDispatchToAccessFcn("StepSize%<tid>", "get", ...
    "", "", GetSimStructExpr(system, ::tSimStruct))
      %assign tt = "%<LibGetTaskTime(tid)>"
      %assign updStr = "if(!(++%<ct>)) {/n ++%<cth>; /n}"
     
      %% No need to update the task time if it's a modelref coder target
      %% and the tid is continuous
      %if !IsModelReferenceRTWTarget() || !LibIsContinuous(tid)
        %if PurelyIntegerCode
      %% Extmode mode require floating point absolute time, in this
      %% case, PurelyIntegerCode need provide floating point time.
      %%
          /* Integer time limited to single word timer. */
      %assign updStr = "%<updStr> %<tt> = %<ct>;"
    %elseif updateRealTimeFromSolverInfo
          %assign updStr = "%<updStr> %<tt> = rtsiGetSolverStopTime(%<RTMGetSolverInfo()>);"
        %else
          %assign updStr = "%<updStr> %<tt> = %<ct> * %<ss> + %<cth> * %<ss> * 4294967296.0"
      %assign updStr = updStr + offsetStr+";"
    %endif
      %endif
    %else
      %assign ct = RTMDispatchToAccessFcn("ClockTick%<tid>", "get", ...
    "", "", GetSimStructExpr(system, ::tSimStruct))
      %assign ssFieldName = "StepSize%<tid>"
      %assign ss = RTMDispatchToAccessFcn(ssFieldName, "get", ...
    "", "", GetSimStructExpr(system, ::tSimStruct))
      %assign rtRecs = RTMGetRTModelRecShell()
      %assign ssField = rtRecs.%<ssFieldName>
      %assign ssDType = FcnGetDtypeName(ssField.DataType)
      %assign tt = "%<LibGetTaskTime(tid)>"
     
      %% No need to update the task time if it's a model ref target
      %% and the tid is continuous
      %if IsModelReferenceRTWTarget() && LibIsContinuous(tid)
        %assign updStr = "%<ct>++;"
      %else
        %if PurelyIntegerCode
          %assign updStr = "%<tt> = /n (++%<ct>);"
        %elseif updateRealTimeFromSolverInfo
          %assign updStr = "++%<ct>; /n %<tt> = rtsiGetSolverStopTime(%<RTMGetSolverInfo()>);"
        %else
          %assign updStr = "%<tt> = /n ((%<ssDType>)(++%<ct>)) * %<ss>"
          %assign updStr = updStr + offsetStr + ";"
        %endif
      %endif
    %endif
  %else
    %assign updStr = "ssUpdateRealAbsoluteTimeForTID(%<SLibGetSimStruct()>, %<tid>);"
  %endif
  %return updStr
%endfunction %% RTMUpdateRealAbsoluteTimeForTID
 
%%Function:RTMUpdateIntegerAbsoluteTimeForTID===================================
%%Abstract:
%%UsedcurrentlybyERTtoupdatetimeforTID.ItisnotarealSimStrucmacro.
%%
%function RTMsUpdateIntegerAbsoluteTimeForTID(system, tid) void
  %if GenRTModel
      %if SLibClockTickIsUnit32Pair(tid)
    %assign ct = RTMDispatchToAccessFcn("ClockTick%<tid>", "get", ...
      "", "", GetSimStructExpr(system, ::tSimStruct))
        %assign cth = RTMDispatchToAccessFcn("ClockTickH%<tid>", "get", ...
      "", "", GetSimStructExpr(system, ::tSimStruct))
    %assign updStr = "%<ct>++;"
    %assign updStr = "%<updStr>/n if (!%<ct>) {/n %<cth>++; /n}"
      %else
    %assign ct = RTMDispatchToAccessFcn("ClockTick%<tid>", "get", ...
      "", "", GetSimStructExpr(system, ::tSimStruct))
    %assign updStr = "%<ct>++;"
      %endif
  %else
    %assign updStr = "ssUpdateIntegerAbsoluteTimeForTID(%<SLibGetSimStruct()>, %<tid>);"
  %endif
  %return updStr
%endfunction %% RTMUpdateIntegerAbsoluteTimeForTID
 
%%Function:RTMUpdateSubrateTaskTime==========================================
%%Abstract:
%%UsedcurrentlybyERTtoupdatetime.ItisnotarealSimStrucmacro.
%%
%function RTMsUpdateSubrateTaskTime(system, subRateIdx) void
  %if GenRTModel
    %assign updStr = FcnGenSpecialAccess(system, "UpdateSubrateTaskTime", ...
      "other", 1, ["%<subRateIdx>"], "", ::tSimStruct)
  %else
    %assign updStr = "ssUpdateSubrateTaskTime(%<SLibGetSimStruct()>, %<subRateIdx>)"
  %endif
  %return updStr
%endfunction %% RTMUpdateSubrateTaskTime
 
 
%%Function:RTMTaskRunsThisBaseStep============================================
%%Abstract:
%%UsedcurrentlybyERTtodetermineifthereisasubratehit.
%%
%function RTMsTaskRunsThisBaseStep(system, subRateIdx) void
  %if GenRTModel
    %assign updStr = FcnGenSpecialAccess(system, "StepTask", ...
      "other", 1, ["%<subRateIdx>"], "", ::tSimStruct)
  %else
    %assign updStr = "ssStepTask(%<SLibGetSimStruct()>, %<subRateIdx>)"
  %endif
  %return updStr
%endfunction %% RTMTaskRunsThisBaseStep
 
%function RTMsUpdateTaskCounter(system, subRateIdx) void
  %assert GenRTModel
  %assign getStr = FcnGenSpecialAccess(system, "TaskCounter", ...
    "other", 1, ["%<subRateIdx>"], "", ::tSimStruct)
  %assign retStr = "if (++%<getStr> == %<FcnComputeTaskTickLimit(subRateIdx)>) %<getStr> = 0;"
   
  %return retStr
%endfunction %% RTMsUpdateTaskCounter
 
%%Function:RTMGetStopRequested===============================================
%%Abstract:
%%Returncodefordoinga"get"onStopRequestedfieldinthertModel
%%
%function RTMsGetStopRequested(system) void
  %if IsModelReferenceForASimstructBasedTarget()
    %assign simS = RTMsGet(system, "MdlRefSfcnS")
    %return "ssGetStopRequested(%<simS>)"
  %endif
  %return RTMsGet(system, "StopRequested")
%endfunction %% RTMGetStopRequested
 
 
%%Function:RTMSetStopRequested===============================================
%%Abstract:
%%Returncodeforsettingthestoprequestedflag
%%
%function RTMsSetStopRequested(system, srq) void
  %if IsModelReferenceForASimstructBasedTarget()
    %assign simS = RTMsGet(system, "MdlRefSfcnS")
    %return "ssSetStopRequested(%<simS>, %<srq>)"
  %endif
  %% In partition grouping we always use the top rtm,
  %% not the partition-wise rtm, to detect stop
  %if SLibPartitionGroupingSystem(system) && ...
    EXISTS(::SavedtSS) && ...
    !ISEMPTY(::SavedtSS)
    %assign savedSS = ::tSimStruct
    %assign ::tSimStruct = ::SavedtSS
  %endif
  %assign ret = RTMsSet(system, "StopRequested", srq)
  %if SLibPartitionGroupingSystem(system) && ...
    EXISTS(::SavedtSS) && ...
    !ISEMPTY(::SavedtSS)
    %assign ::tSimStruct = savedSS
  %endif
  %return ret
%endfunction %% RTMSetStopRequested
 
 
%%Function:RTMStopReqAccessed================================================
%%Abstract:
%%Wasstoprequestedflagaccessed?
%%
%function RTMsStopReqAccessed(system) void
  %assign srq = "StopRequested"
  %assign srqp = "StopRequestedPtr"
  %assign rtRecs = RTMGetRTModelRecShell()
  %assign theRec = rtRecs.%<srq>
  %assign theRecp = rtRecs.%<srqp>
  %assign accessed = (theRec.NumSet > 0) || (theRec.NumGet > 0) || ...
    (theRecp.NumGet > 0) || (theRecp.NumSet > 0)
  %%
  %% The StopRequestedFlag is required for the SolverInfo record, so we also
  %% need to check for continuous states and non-inlined s-functions
  %%
  %return (accessed || NumContStates || NumChildSFunctions)
%endfunction %% RTMStopReqAccessed
 
%%Function:RTMRegisterDataType===============================================
%%Abstract:
%%Returncodefordoingadatatyperegistration
%%
%function RTMsRegisterDataType(system, dtypeName) void
  %% Used only for simstruc.h
  %assert !GenRTModel
 
  %assign regStr = "ssRegisterDataType(%<SLibGetSimStruct()>, %<dtypeName>)"
   
  %return regStr
%endfunction %% RTMRegisterDataType
 
%%------------------------------------------------------------------------------
%%rtModelcreationSECTION:
%%------------------------------------------------------------------------------
%%Thissectionisdevotedtomethodsthatarecalledtocreateatype
%%defintionforthertModelstructure.Therearealsomethodsforgenerating
%%accessmacrosforsomeofthefieldswhennecessary.
%%------------------------------------------------------------------------------
 
 
%%Function:FcnGetQualifier===================================================
%%Abstract:
%%Generatethequalifier
%%
%function FcnGetQualifier(qual) void
  %assign retStr = ""
  %switch qual
    %case "CONST"
      %assign retStr = "const "
      %break
    %default
      %assign retStr = qual
      %break
  %endswitch
  %return retStr
%endfunction %% FcnGetQualifier
 
 
%%Function:FcnGetDtypeName===================================================
%%Abstract:
%%Generatethedatatypename.
%%
%function FcnGetDtypeName(dTypeId)
  %switch dTypeId
    %case "CHAR"
      %assign retStr = "char_T"
      %break
    %case "UINT32"
    %case "uint32"
      %assign retStr = "uint32_T"
      %break
    %case "UINT16"
    %case "uint16"
      %assign retStr = "uint16_T"
      %break
    %case "UINT8"
    %case "uint8"
      %assign retStr = "uint8_T"
      %break
    %case "INT"
      %assign retStr = "int_T"
      %break
    %case "REAL"
    %case "real_T"
    %case "DOUBLE"
    %case "double"
      %assign retStr = "real_T"
      %break
    %case "VOID"
      %assign retStr = "void"
      %break
    %case "VOID_PTR"
      %assign retStr = "void *"
      %break
    %case "SIMSTRUCT"
      %assign retStr = "struct SimStruct_tag"
      %break
    %case "SIMSTRUCT_PTR"
      %assign retStr = "struct SimStruct_tag *"
      %break
    %case "SS_SIMMODE"
      %assign retStr = "SS_SimMode"
      %break
    %case "TIME"
      %if SLibIsERTCodeFormat() && PurelyIntegerCode
    %assign retStr = "uint32_T"
      %else
    %assign retStr = "time_T"
      %endif
      %break
    %case "SOLVER_MODE"
      %assign retStr = "SolverMode"
      %break
    %case "ZC_SIG_STATE"
      %assign retStr = FcnGetPrevZCSigStateType()
      %break
    %case "ZC_SIG_STATE_CLASSIC"
      %assign retStr = "ZCSigState"
      %break
    %case "BOOLEAN"
      %assign retStr = "boolean_T"
      %break
    %case "DWORK"
      %assign retStr = ::tDWorkType
      %break
    %case "BLOCKIO"
      %assign retStr = ::tBlockIOType
      %break
    %case "INPUTS"
      %assign retStr = ::tInputType
      %break
    %case "OUTPUTS"
      %assign retStr = tOutputType
      %break
    %case "PARAMETER"
      %assign retStr = ::tParametersType
      %break
    %case "CONT_STATES"
      %assign retStr = ::tContStateType
      %break
    %case "RTW_LOG_INFO"
      %assign retStr = "RTWLogInfo"
      %break
    %case "EXT_MODE_INFO"
      %assign retStr = "RTWExtModeInfo"
      %break
    %case "SOLVER_INFO"
      %assign retStr = "RTWSolverInfo"
      %break
    %case "NONINLINED_SFCS"
      %assign retStr = SLibIsERTCodeFormat() ? ...
        SLibGenERTNonInlinedSFcnsSubStruct() : ""
      %break
    %case "MODEL_METHODS_INFO"
      %assign retStr = "RTWRTModelMethodsInfo"
      %break
    %case "SIM_TIME_STEP"
      %assign retStr = "SimTimeStep"
      %break
    %case "INTG"
      %assign retStr = "%<upperSolver>_IntgData"
      %break
    %case "LOG_SIG_PTR"
      %assign retStr = "LogSignalPtrsType"
      %break
    %case "DATA_MAP_INFO"
      %assign retStr = RTWCAPI ? SLibGenDataMapInfoSubstruct() : ""
      %break
    %case "RATE_INTERACTION"
      %assign retStr = SLibIsERTCodeFormat() ? ...
    SLibGenERTRateInteractionSubStruct() : ""
      %break
    %case "TASK_COUNTERS"
      %assign retStr = SLibIsERTCodeFormat() ? ...
    SLibGenERTTaskCountersSubStruct() : ""
      %break
    %case "CTRLRATE_TIMING"
      %assign retStr = "rtCtrlRateMdlRefTiming"
      %break
    %case "NONCONT_SIGS"
      %assign retStr = "ssNonContDerivSigInfo"
      %break
    %case "NONCONT_DERIV_SIGS_MEMORY"
      %assign retStr = RTMNeedsNonContDerivSigs() ? SLibGenNoncontDerivSigStruct() : ""
      %break
    %case "TIMING_BRIDGE"
      %assign retStr = "rtTimingBridge"
      %break
    %case "Rte_Instance"
      %assign retStr = "Rte_Instance"
      %break
    %default
      %% Can get here for Coder Data Groups
      %assign retStr = dTypeId
  %endswitch
  %return retStr
%endfunction %% FcnGetDtypeName
 
 
%%Function:FcnGetStorageKeys=================================================
%%Abstract:
%%Generatetheprefixandpostfixkeysforthegivenstorageclass
%%
%function FcnGetStorageKeys(storage, arrayDims) void
  %switch storage
    %case "SCALAR"
      %assign prefix = ""
      %assign postfix = ""
      %break
    %case "POINTER"
      %assign prefix = "*"
      %assign postfix = ""
      %break
    %case "VOLATILEPOINTER"
      %assign prefix = "* volatile "
      %assign postfix = ""
      %break
    %case "POINTERPOINTER"
      %assign prefix = "**"
      %assign postfix = ""
      %break
    %case "ARRAY"
      %assign prefix = ""
      %assign nDims = SIZE(arrayDims)[1]
       
      %assign postfix = ""
      %foreach dimIdx = nDims
    %assign postfix = postfix + "[%]"
      %endforeach
      %break
    %default
      %assign prefix = "BOGUS_PREFIX"
      %assign postfix = "BOGUS_POSTFIX"
      %break
  %endswitch
  %assign retVal = ["%<prefix>", "%<postfix>"]
  %return retVal
%endfunction %% FcnGetStorageKeys
 
 
%%Function:FcnGenFieldTypeDef================================================
%%Abstract:
%%GeneratesthetypedefinitionforoneofthefieldsinthertModel
%%
%function FcnGenFieldTypeDef(theField) void
  %assign qual =FcnGetQualifier(theField.Qualifier)
   
  %assign dType =FcnGetDtypeName(theField.DataType)
  %assign stKeys=FcnGetStorageKeys(theField.StorageType,theField.ArrayDims)
  %assign retStr="%<qual>%<dType> %%<theField.VarName>%;"
  %return retStr
%endfunction %% FcnGenFieldTypeDef
 
 
%%Function:FcnGenTypeStrForRTMFields=========================================
%%Abstract:
%%GeneratesthetypedefforthertModelbasedontheusageofvarious
%%fieldsinthertModelrecord.
%%
%function FcnGenTypeStrForRTMFields(rtRecs) void
  %assign rootFields = FIELDNAMES(rtRecs)
  %assign numFields = SIZE(rootFields)[1]
 
  %foreach fldIdx = numFields
    %assign thisfld = rtRecs.%
    %if thisfld.RecType != "Variable"
      %continue
    %endif
     
    %assign thisfld.TypeStr = FcnGenFieldTypeDef(thisfld)
  %endforeach
   
%endfunction %% FcnGenTypeStrForRTMFields
 
 
%%FcnRTMFieldIsRequired=======================================================
%%Abstract:
%%IsafieldinthertModelrequired?
%%
%function FcnRTMFieldIsRequired(fld) void
  %%
  %% Currently we also make fields which have at least one Get required.
  %% This is because the field could be potentially updated in a location
  %% within rtw/c/src/
  %%
  %assign reqFcn = "%<fld.IsRequiredFcn>"
  %assign req = %<reqFcn>
  %return req
%endfunction %% FcnRTMFieldIsRequired
 
 
%%Function:FcnGenHStructFromRTMRecs==========================================
%%Abstract:
%%GenerateahierarchicalstructurefromthertModelrecords.
%%
%function FcnGenHStructFromRTMRecs(rtRecs) void
  %assign rootFields = FIELDNAMES(rtRecs)
  %assign numFields = SIZE(rootFields)[1]
  %assign empArray = []
   
  %createrecord Root {}
  %addtorecord Root FieldNames %<empArray>
  %addtorecord Root FieldNums %<empArray>
  %addtorecord Root TotalNumFields 0
   
  %foreach fldIdx = numFields
    %assign thisfld = GETFIELD(rtRecs, rootFields[fldIdx])
    %if thisfld.RecType != "Variable"
      %continue
    %endif
     
    %%
    %% We only deal here with parents that are 1-level deep.
    %% More work needs to be done here if we need deeper
    %% Root structures.
    %%
     
    %if FcnRTMFieldIsRequired(thisfld)
      %assign fldParent = thisfld.Parent
      %assign rootField = (fldParent == "")
      %if !rootField
    %if !ISFIELD(Root, fldParent)
      %addtorecord Root %<fldParent> ...
      { ...
        FieldNames %<empArray>; ...
        FieldNums %<empArray> ...
      }
    %endif
    %assign parentRec = GETFIELD(Root, fldParent)
      %else
    %assign parentRec = Root
      %endif
 
      %assign Root.TotalNumFields = Root.TotalNumFields + 1
      %assign parentRec.FieldNames = parentRec.FieldNames + rootFields[fldIdx]
      %assign parentRec.FieldNums = parentRec.FieldNums + thisfld.VarRecNumber
    %endif
  %endforeach
  %return Root
%endfunction %% FcnGenHStructFromRTMRecs
 
 
%%Function:FcnGenSubstructFlatFields=========================================
%%Abstract:
%%GenerateflatsubstructureforRTModelrecfields
%%
%function FcnGenSubstructFlatFields(name, fldNums, fields) void
  %assign rtRecs = RTMGetRTModelRecShell()
  %assign numFields = SIZE(fldNums)[1]
  %openfile tmpBuff
  %foreach fldIdx = numFields
    %if numFields > 1
      %assign thisfld = rtRecs.%
    %else
      %assign thisfld = rtRecs.%<fields>
    %endif
    %<thisfld.TypeStr>
  %endforeach
  %closefile tmpBuff
  %return tmpBuff
%endfunction %% FcnGenSubstructFlatFields
 
%%Function:FcnGenTypeDefFromHStruct_Fields
%%Abstract:
%%Generateatypedeffromthehierarchicalstructbutonly
%%returnsthefieldsinsidethetype,notthestructheadandtail.
%%e.g.struct{inta;intb;}myStructType;
%%^^^^^^^^^^^^
%%returnthis
%function FcnGenTypeDefFromHStruct_Fields(structName, hstruct) void
  %assign fldNames = hstruct.FieldNames
  %assign fldNums = hstruct.FieldNums
  %assign flatFields = ""
   
  %if SIZE(fldNums)[0] > 0 && SIZE(fldNums)[1] > 0
    %assign sortNames = FEVAL("rtmdlsortflds", fldNames, fldNums)
    %assign flatFields = FcnGenSubstructFlatFields(structName, fldNums, ...
      sortNames)
  %endif
   
  %assign childFlds = FIELDNAMES(hstruct)
  %assign numChildFlds = SIZE(childFlds)[1]
   
  %openfile fieldsBuffer
    %<flatFields>
    %foreach fldIdx = numChildFlds
      %if childFlds[fldIdx] == "FieldNames" || ...
        childFlds[fldIdx] == "FieldNums" || ...
        childFlds[fldIdx] == "TotalNumFields"
        %continue
      %endif
      %%
      %assign hss = hstruct.%
      %<FcnGenTypeDefFromHStruct(childFlds[fldIdx],hss,"")>
    %endforeach
 
  %closefile fieldsBuffer
  %return fieldsBuffer
%endfunction
 
%%Function:FcnGenTypeDefFromHStruct==========================================
%%Abstract:
%%Generateatypedeffromthehierarchicalstruct
%%
%function FcnGenTypeDefFromHStruct(structName, hstruct, tag) void
  %assign structFields = FcnGenTypeDefFromHStruct_Fields(structName, hstruct)
  %assign structTail = " %<structName>"
  %if (structName == ::tSimStructType)
    %assign structTail = ""
  %endif
 
  %assign commentStr = SLibGetRTMSubStructCommentStr(structName)
   
  %openfile structTypeDef
  %if !WHITE_SPACE(commentStr)
    %<commentStr> /
  %endif
 
  struct %<tag> {
    %<structFields>
  }%<structTail>;
  %closefile structTypeDef
   
  %return structTypeDef
%endfunction %% FcnGenTypeDefFromHStruct
 
 
%%Function:RTMGenOpaqueTypedef===============================================
%%Abstract:
%%GenerateanopaquetypedefofthertModel
%%
%function RTMsGenOpaqueTypedef(system) void
  %if SLibCanInlineRTMIntoSelf() && !SLibSynthesizedRTM()
    %return
  %endif
   
  %if !EmptyRealTimeObject && !SLibIsModelTypesModelClassNamespace()
    %openfile rtmTypedef
      /* Forward declaration for rtModel */
      %if SLibIsSelfUserDefinedAndStructured()
        %assign legacyRTMTypeName = ::CompiledModel.GlobalScope.tSimStructType
        typedef struct %<::tSimStructTypeTag> %<legacyRTMTypeName>;
      %else
        typedef struct %<::tSimStructTypeTag> %<::tSimStructType>;
      %endif
    %closefile rtmTypedef
  %else
    %assign rtmTypedef = ""
  %endif
  %return rtmTypedef
%endfunction %% RTMGenOpaqueTypedef
 
 
%function RTMTypeIsNeeded() void
  %if ::isRAccel || Accelerator || ::isRSim || IsModelReferenceSimTarget()
    %return TLC_TRUE
  %endif
   
  %if EXISTS(::RootRTMdlRecs)
    %assign rtRecs = RTMGetRTModelRecShell()
    %assign hStruct = FcnGenHStructFromRTMRecs(rtRecs)
    %assign defaultSelfMaybeNeeded = ::CompiledModel.ModelRefSimpInterface == "1" && ...
      !SLibIsSelfUserDefinedAndStructured()
 
    %assign forceRTMCreation = MultiInstanceERTCode && !GenerateClassInterface && ...
      !SLibUseBackwardCompatibleReusableInterface() && !SLibIsSelfUserDefinedAndStructured()
     
    %if (hStruct.TotalNumFields > 0) || defaultSelfMaybeNeeded || forceRTMCreation
      %return TLC_TRUE
    %endif
  %endif
  %return TLC_FALSE
%endfunction
 
%%Function:RTMGenRtMdlTypedef================================================
%%Abstract:
%%GeneratesthetypedefforthertModelbasedontheusageofvarious
%%fieldsinthertModelrecord.
%%
%function RTMsGenRtMdlTypedef(system) void
  %assign rtRecs = RTMGetRTModelRecShell()
   
  %if RTMModelPtrsToInstanceDataIsReqFcn()
    %if !SLibGetUseRTMcgType()
      %assign rtRecs.BlockIO.DataType = "VOID"
      %assign rtRecs.DefaultParam.DataType = "VOID"
      %assign rtRecs.U.DataType = "VOID"
      %assign rtRecs.Y.DataType = "VOID"
      %assign rtRecs.RootDWork.DataType = "VOID"
      %assign rtRecs.PrevZCSigState.DataType = "ZC_SIG_STATE_CLASSIC"
    %endif
    %assign rtRecs.ContStates.DataType = "REAL"
  %endif
 
  %if !::CompiledModel.SuppressSelf && !SLibSynthesizedRTM()
    %assign baseIdx = GetBaseSystemIdx()
    %foreach idx = ::CompiledModel.NumCoderDataGroups
      %if idx == SLibGetSelfCoderDataGroupIndex()
        %continue
      %endif
      %assign group = ::CompiledModel.CoderDataGroup[idx]
      %if SLibStandAloneSingleInstance(group)
        %continue
      %elseif !SLibAllocatesCoderDataGroup(group) || LibCoderDataGroupStructIsEmpty(group) || !SLibHaveRootDataGroupVarGroup(group)
        %continue
      %endif
      %assign typeToken = "CoderDataGroup" + group.Name
      %assign type = FcnSysVarGroupType(::CompiledModel.System[baseIdx], typeToken)
      %assign fieldName = SLibCoderDataGroupRTMFieldName(group)
      %assign rtRecs.%<fieldName>.DataType = type
      %assign rtRecs.%<fieldName>.Qualifier = SLibTypeQualifierForGroup(group)
    %endforeach
  %endif
   
  %%
  %% Generate the type strings for each field
  %%
  %<FcnGenTypeStrForRTMFields(rtRecs)>/
  %%
  %% Generate a hierarhical TLC structure from the rtModel records
  %%
  %assign hStruct = FcnGenHStructFromRTMRecs(rtRecs)
 
  %if FcnShouldGenerateRTM(hStruct)
    %assign tag = "%<::tSimStructTypeTag>"
    %openfile typeBuf
 
    %assign cgTypeHasElements = TLC_FALSE
    %if SLibSynthesizedRTM() && (IsModelReferenceTarget() || SLibGetUseRTMcgType())
      %assign vargroup = ::CompiledModel.VarGroups.VarGroup[SLibGetSelfVarGroupIndex()]
      %if vargroup.CGTypeIdx > -1
        %foreach mIdx = LibCGTypeNumMembers(vargroup.CGTypeIdx)
          %assign vargroupElem = vargroup.VarGroupElements[mIdx]
          %assign idnum = IDNUM(vargroupElem)
          %assign recType = idnum[0]
          %if recType != "DUM" %% Dummy field
            %assign cgTypeHasElements = TLC_TRUE
            %break
          %endif
        %endforeach
        %% Check to see if Context structure contains parameter vargroup. If so, map the cgType
        %% to the type generated by the Parameter table
        %assign varGroupIdx = ...
          FcnSysVarGroupIndex(System[GetBaseSystemIdx()], "Parameter", 0)
        %foreach mIdx = LibCGTypeNumMembers(vargroup.CGTypeIdx)
          %if varGroupIdx >= 0 && ...
            vargroup.VarGroupElements[mIdx] == "RVG" + STRING(varGroupIdx)
            %assign paramType = tParametersType + "_"
            %assign memberCGTypeIdx = LibCGTypeMemberCGTypeIdx(vargroup.CGTypeIdx, mIdx)
            %assign cgPtrType = ::CompiledModel.CGTypes.CGType[memberCGTypeIdx]
            %if LibCGTypeIsPointer(memberCGTypeIdx)
              %assign cgBaseType = ::CompiledModel.CGTypes.CGType[LibCGTypeBaseIndex(memberCGTypeIdx)]
            %else
              %assign cgBaseType = cgPtrType
            %endif
            %if tParametersType != cgBaseType.Name
              typedef struct %<paramType> %<cgBaseType.Name>;/
            %endif
          %endif
        %endforeach
      %endif
    %endif
 
    %% Add a dummy field to RTM if empty
    %if hStruct.TotalNumFields==0 && !SLibIsSelfUserDefinedAndStructured() && !cgTypeHasElements
      %assign NO_PARENT = ""
      %assign NO_QUALIFIER = ""
      %assign FORCE_NO_MACRO = [-1, -1, -1, -1]
      %<RTMAddRecSclr(...
        "UNUSED", ...
        "rt_unused", ...
        NO_PARENT, ...
        "CHAR", ...
        NO_QUALIFIER, ...
        FORCE_NO_MACRO, ...
        "RTMAlwaysReqIsReqFcn()")>
      %% Re-generate the type strings for each field
      %<FcnGenTypeStrForRTMFields(rtRecs)>/
      %assign hStruct = FcnGenHStructFromRTMRecs(rtRecs)
    %endif
 
    %if !SLibCanInlineRTMIntoSelf()
      %assign rtmType = SLibIsModelTypesModelClassNamespace() ? ::tSimStructType : tag
      /* Real-time Model Data Structure */
      %<FcnGenTypeDefFromHStruct(::tSimStructType, hStruct, ...
        "%<rtmType>")>/
    %else
      %assign rtmTypeFields = FcnGenTypeDefFromHStruct_Fields(::tSimStructType, hStruct)
      %<LibAddToCompiledModel("RTMTypeFields", rtmTypeFields)>
    %endif
    %closefile typeBuf
  %else
    %assign ::CompiledModel.EmptyRealTimeObject = 1
    %assign typeBuf = ""
  %endif
  %return typeBuf
%endfunction %% RTMGenRtMdlTypedef
 
 
%%FcnRTMFieldNeedsMacro=======================================================
%%Abstract:
%%IsamacroneededRTMfield?
%%
%function FcnRTMFieldNeedsMacro(fld) void
  %assign retVal = TLC_FALSE %% assume
   
  %if SLibIsERTCodeFormat() && !GenerateGRTWrapper
    %if ISFIELD(fld,"ERTMacro") && ...
      (fld.RecType != "Variable" || FcnRTMFieldIsRequired(fld))
      %assign numAccesses = SIZE(fld.ERTMacro)[1]
      %foreach aIdx = numAccesses
    %if fld.ERTMacro[aIdx] > 0
      %assign retVal = TLC_TRUE
      %break
    %endif
      %endforeach
    %endif
  %else
    %assign retVal = TLC_TRUE
  %endif
       
  %return retVal
%endfunction %% FcnRTMFieldNeedsMacro
 
 
%function FcnRTMAccessNeedsMacro(fld, accessType, macroLoc)
  %assign retVal = TLC_FALSE
  %assign accessCode = 0
   
  %if ISFIELD(fld,"ERTMacro")
    %switch accessType
      %case "Set"
    %assign accessCode = fld.ERTMacro[0]
    %break
      %case "Get"
    %assign accessCode = fld.ERTMacro[1]
    %break
      %case "Is"
    %assign accessCode = fld.ERTMacro[2]
    %break
      %case "Other"
    %assign accessCode = fld.ERTMacro[3]
    %break
    %endswitch
  %endif
   
  %if SLibIsERTCodeFormat()
    %assign macLocCode = 0
    %switch macroLoc
      %case "PUBLIC"
    %assign macLocCode = 1
    %break
      %case "PRIVATE"
    %assign macLocCode = 2
    %break
    %endswitch
    %if !GenerateGRTWrapper
      %if ISFIELD(fld,"ERTMacro")
    %assign retVal = (macLocCode == accessCode)
      %endif
    %else
      %% If grtInterface is required,
      %% Always generate macro in public
      %%
      %if accessCode == -1 %% FORCE_NO_MACRO
    %assign retVal = TLC_FALSE
      %else
    %assign retVal = (macLocCode == 1)
      %endif
    %endif
  %else
    %assign retVal = TLC_TRUE
  %endif
  %return retVal
%endfunction %% FcnRTMAccessNeedsMacro
 
 
%%Function:FcnGenVariableMacro===============================================
%%Abstract:
%%Generatemacrosforasimplevariablefield
%%
%function FcnGenVariableMacro(fldName, fld, macroLoc) void
  %assign macros = ""
 
  %if FcnRTMAccessNeedsMacro(fld, "Get", macroLoc)
    %assign macName = "rtmGet" + fldName
    %assign macros = macros + "#ifndef %<macName>/n"
    %assign macros = macros + "# define %<macName>(rtm) "
    %assign accStr = FcnGenFieldAccessString(fld, "get", "", "", "(rtm)")
    %assign macros = macros + "(%<accStr>)/n"
    %assign macros = macros + "#endif/n/n"
  %endif
   
  %if FcnRTMAccessNeedsMacro(fld, "Set", macroLoc)
    %assign macName = "rtmSet" + fldName
    %assign macros = macros + "#ifndef %<macName>/n"
    %assign macros = macros + "# define %<macName>(rtm, val) "
    %assign accStr = FcnGenFieldAccessString(fld, "set", "", "val", "(rtm)")
    %assign macros = macros + "(%<accStr>)/n"
    %assign macros = macros + "#endif/n/n"
  %endif
   
  %return macros
   
%endfunction %% FcnGenVariableMacro
 
 
%%Function:FcnGenIndexedAccessMacro==========================================
%%Abstract:
%%Generatemacrosforasimplevariablefield
%%
%function FcnGenIndexedAccessMacro(fldName, fld, idxFld, macroLoc) void
  %assign macros = ""
 
  %if FcnRTMAccessNeedsMacro(fld, "Get", macroLoc)
    %assign macName = "rtmGet" + fldName
    %assign macros = macros + "#ifndef %<macName>/n"
    %assign macros = macros + "# define %<macName>(rtm, idx) "
    %assign accStr = FcnGenFieldAccessString(idxFld, "get", "idx", "", "(rtm)")
    %assign macros = macros + "(%<accStr>)/n"
    %assign macros = macros + "#endif/n/n"
  %endif
 
  %if FcnRTMAccessNeedsMacro(fld, "Set", macroLoc)
    %assign macName = "rtmSet" + fldName
    %assign macros = macros + "#ifndef %<macName>/n"
    %assign macros = macros + "# define %<macName>(rtm, idx, val) "
    %assign accStr = FcnGenFieldAccessString(idxFld, "set", "idx", "val", "(rtm)")
    %assign macros = macros + "(%<accStr>)/n"
    %assign macros = macros + "#endif/n/n"
  %endif
   
  %return macros
   
%endfunction %% FcnGenIndexedAccessMacro
 
 
%%Function:FcnGenSpecialAccessMacro==========================================
%%Abstract:
%%Generatemacrosforasimplevariablefield
%%
%function FcnGenSpecialAccessMacro(fldName, fld, rtRecs, macroLoc) void
  %assign macros = ""
   
  %% Generate the list of args
  %assign comma = ""
  %if FcnNeedRTMInMacroArg(fld)
    %assign argStr = "rtm"
    %assign comma = ", "
  %else
    %assign argStr = ""
  %endif
  %assign args = fld.Args
  %foreach argIdx = fld.NumArgs
    %assign argStr = argStr + comma
    %assign argStr = argStr + args[argIdx]
    %assign comma = ", "
  %endforeach
   
  %if fld.GetFcn != "" && FcnRTMAccessNeedsMacro(fld, "Get", macroLoc)
    %assign accStr = %<fld.GetFcn>(fld, "(rtm)")
    %if !WHITE_SPACE(accStr)
      %assign macName = "rtmGet" + fldName
      %assign macros = macros + "#ifndef %<macName>/n"
      %assign macros = macros + "# define %<macName>(%<argStr>) "
      %assign macros = macros + "%<accStr>/n"
      %assign macros = macros + "#endif/n/n"
    %endif
  %endif
   
  %if fld.SetFcn != "" && FcnRTMAccessNeedsMacro(fld, "Set", macroLoc)
    %if fld.SetHasValArg
      %assign accStr = %<fld.SetFcn>(fld, "(rtm)", "val")
    %else
      %assign accStr = %<fld.SetFcn>(fld, "(rtm)")
    %endif
    %if !WHITE_SPACE(accStr)
      %assign macName = "rtmSet" + fldName
      %assign valArg = fld.SetHasValArg ? comma + "val" : ""
      %assign macros = macros + "#ifndef %<macName>/n"
      %assign macros = macros + "# define %<macName>(%<argStr>%<valArg>) "
      %assign macros = macros + "%<accStr>/n"
      %assign macros = macros + "#endif/n/n"
    %endif
  %endif
     
  %if fld.IsFcn != "" && FcnRTMAccessNeedsMacro(fld, "Is", macroLoc)
    %assign accStr = %<fld.IsFcn>(fld, "(rtm)")
    %if !WHITE_SPACE(accStr)
      %assign macName = "rtmIs" + fldName
      %assign macros = macros + "#ifndef %<macName>/n"
      %assign macros = macros + "# define %<macName>(%<argStr>) "
      %assign macros = macros + "%<accStr>/n"
      %assign macros = macros + "#endif/n/n"
    %endif
  %endif
     
  %if fld.OtherFcn != "" && FcnRTMAccessNeedsMacro(fld, "Other", macroLoc)
    %assign accStr = %<fld.OtherFcn>(fld, "(rtm)")
    %if !WHITE_SPACE(accStr)
      %assign macName = "rtm" + fldName
      %assign macros = macros + "#ifndef %<macName>/n"
      %assign macros = macros + "# define %<macName>(%<argStr>) "
      %assign macros = macros + "%<accStr>/n"
      %assign macros = macros + "#endif/n/n"
    %endif
  %endif
     
  %return macros
   
%endfunction %% FcnGenSpecialAccessMacro
 
 
%%Function:RTMGenMacroDefines================================================
%%Abstract:
%%GeneratesmacrosforthefieldsofthertModelthatareunderuse.
%%
%function RTMsGenMacroDefines(system, macroLoc) void
  %assign rtRecs = RTMGetRTModelRecShell()
  %assign rootFields = FIELDNAMES(rtRecs)
  %assign numFields = SIZE(rootFields)[1]
   
  %assign vMacs = ""
  %assign iMacs = ""
  %assign sMacs = ""
   
  %foreach fldIdx = numFields
    %assign thisfld = rtRecs.%
    %if FcnRTMFieldNeedsMacro(thisfld)
      %switch(thisfld.RecType)
    %case "Variable"
      %assign vMacs = vMacs + ...
        FcnGenVariableMacro(rootFields[fldIdx], thisfld, macroLoc)
      %break
    %case "IndexedAccess"
      %assign iMacs = iMacs + ...
        FcnGenIndexedAccessMacro(rootFields[fldIdx], thisfld, ...
        rtRecs.%<thisfld.AccessedRec>, macroLoc)
      %break
    %case "SpecialAccess"
      %assign sMacs = sMacs + ...
        FcnGenSpecialAccessMacro(rootFields[fldIdx], thisfld, ...
        rtRecs, macroLoc)
      %break
      %endswitch
    %endif
  %endforeach
   
  %openfile macBuf
  %if !WHITE_SPACE(vMacs)
    %<vMacs>
  %endif
 
  %if !WHITE_SPACE(iMacs)
    %<iMacs>
  %endif
 
  %if !WHITE_SPACE(sMacs)
    %<sMacs>
  %endif
  %<RTMGenMacroDefinesForGRTWrapper(rtRecs, macroLoc)>
  %closefile macBuf
  %return macBuf
%endfunction %% RTMGenMacroDefines
 
%%Function:RTMGenMacroDefinesForGRTWrapper
%%Abstract:
%%Thisfunctionwillgeneratmacrosthatareusedingrt_main.c
%%butnotneededforertcodeformat.Tocompilegrt_main.c,
%%whenGenerateGRTWrapperistrue,needgeneratethesemacros.
%%ThesemacroswillaccessaGRTTimingEngineTmpiffielddoesnotexist.
%%Pleasenotethatthereturnvaluesofthesemacrosisnotreally
%%usedingrt_main.cwhenGenerateGRTWrapperistrue.
%%
%function RTMGenMacroDefinesForGRTWrapper(rtRecs, macroLoc)
  %assign macros = ""
  %if GenerateGRTWrapper && macroLoc == "PUBLIC"
 
    %if !UsingMalloc
      %% rtwsolverinfo is special
      %assign fld = rtRecs.RTWSolverInfo
      %assign macName = "rtmGetRTWSolverInfo"
      %assign macros = macros + "#ifdef %<macName>/n"
      %assign macros = macros + "#undef %<macName>/n"
      %assign macros = macros + "#endif/n"
      %assign macros = macros + "#define %<macName>(rtm) "
      %assign accStr = FcnGenFieldAccessString(fld, "get", "", "", "(rtm)")
      %assign macros = macros + "&(%<accStr>)/n"
    %endif %% !isGRTMallocOnERT()
  %endif
   
  %return macros
%endfunction
 
%%Function:RTMAddExternRTModelDecl===========================================
%%Abstract:
%%CreateanexterndeclarationofrtModel.UsedintheDSPblockset.
%%
%function RTMsAddExternRTModelDecl(system) Output
  %if GenRTModel
    #include "%<::CompiledModel.Name>.h"
     
    extern %<SLibGetQualifiedRTMType()> *const %<::tSimStruct>;
  %else
    #include "simstruc.h"
     
    extern SimStruct *const %<::tSimStruct>;
  %endif
%endfunction
 
%%Function:FcnGetContStateType==============================================
%%Abstract:
%%GettypeofcontStatesinReal-timemodeldatastructure
%%
%function FcnGetContStateType() void
  %if GRTInterface || isGRTMalloc || !GenRTModel
    %return "real_T"
  %else
    %return ::tContStateType
  %endif
%endfunction
 
%%Function:FcnGetPrevZCSigStateType==========================================
%%Abstract:
%%GettypeofprevZCSigStateinReal-timemodeldatastructure
%%
%function FcnGetPrevZCSigStateType() void
  %if GRTInterface || isGRTMalloc || !GenRTModel
    %return "ZCSigState"
  %else
    %return ::tPrevZCStateType
  %endif
%endfunction
 
%%Function:GetSimStructExpr=================================================
%%Abstrct:
%%RTMpointerisremovedfromcppclassdeclaration,placesthatusethis
%%pointernowneedtouseRTMobject'saddressinstead.Weneedtoadd"&"
%%tortmNamewheneveritisneeded.
%function GetSimStructExpr(system, rtmName)
  %if SLibGetDoesSelfHasCoderDataGroup() && SLibIsSelfStructured() && !SLibCanInlineRTMIntoSelf() && !GenerateClassInterface
    %assign rtmName = rtmName + "->" + SLibGetRTMPointerVariableNameInsideSelfStructure()
  %endif
   
  %if GenerateClassInterface && (IsBaseSystem(System[system.ReusedParentSystemIdx]) || SLibGenSubsysFcnAsClassMemFcn(system)) && ...
    ::BlockFcn != "Rate_Scheduler" && ::BlockFcn != "InitializeDataMapInfo" && rtmName != "getRTM()"
    %assign rtmName = "(&" + rtmName + ")"
  %elseif SLibIsSelfStructured() && IsModelRefScalableBuild() && !GenerateClassInterface
    %if IsModelReferenceSimTarget()
      %assign rtmName = "(&" + FcnGetSFcnDWorkRTM() + ")"
    %else
      %assign rtmName = "(&" + ::CompiledModel.GlobalScope.tRTM + ")"
    %endif
  %endif
  %return rtmName
%endfunction
 
%function LibSetNumTicksToNextHitForCtrlRate(stIdx, numTicks) void
  %if IsModelReferenceTarget()
    %return "%<RTMSetIdxed("NumTicksToNextHitForCtrlRateInMdlRef", "%<stIdx>", "%<numTicks>")>"
     
  %elseif GenRTModel && SLibIsERTCodeFormat()
    %return "%<RTMSetIdxed("CtrlRateNumTicksToNextHit", "%<stIdx>", "%<numTicks>")>"
     
  %else
    %assign comma = ", "
    %return "ssSetNumTicksToNextHitForControllableSampleTime(" + ...
      "%<SLibGetSimStruct()>" + comma + ...
      "%<stIdx>" + comma + ...
      "%<numTicks>" + ");"
  %endif
%endfunction %% RTMSetNumTicksToNextHit
 
%%Function:RTMSetNumTicksToNextHitForCtrlRate===================
%%Abstract:
%%Generatescodetosetthenumberoftickstothenextcontrollableratehit
%%time.Blockswithcontrollablesampletimemustcallthisfunctionintheir
%%outputfunctions.
%%
%function RTMSetNumTicksToNextHitForCtrlRate(block, st_index, numTicks) void
  %assert GenRTModel && SLibIsERTCodeFormat()
  %return LibSetNumTicksToNextHitForCtrlRate(%<SLibGetBlockCtrlRateIndex(block, 0)>, numTicks)
%endfunction %% RTMSetNumTicksToNextHitForCtrlRate
%%[EOF]rtmdllib.tlc