%%Abstract:
%%Librarytosupportthevariousformsofmodelregistration.
 
%%Copyright1994-2019TheMathWorks,Inc.
 
%if EXISTS("_REGLIB_") == 0
%assign _REGLIB_ = 1
 
 
%%=============================================================================
%%CreateglobalcachevariabletoholdS-functionregistrationcode
%%=============================================================================
 
%<LibAddToCompiledModel("SFunctionRegistration", 0)>
 
 
%%Function:FcnDynamicLog================================================
%%Abstract:
%%Arewelogginginthefaceofcodevariants?
%%
%function FcnDynamicLog() void
  %return ::CompiledModel.HasVariants
%endfunction
   
%%Function:FcnSuitableForMemset==============================================
%%TopTester:test/toolbox/simulink/blocks/tenable.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmvs_muxdemux_basics_VC1.m
%%TopTester:test/toolbox/simulink/blocks/lib_Discrete/DiscreteTimeIntegrator/rtw/tNumerics_dintegrt_fixpt_e.m
%%TopTester:test/toolbox/simulink/variants/tvss_simplified_ic.m
%%
%function FcnSuitableForMemset(valueToSet, dataTypeId, storageClass) void
  %%
  %if storageClass == "Custom"
    %%
    %% don't use memset for custom storage class
    %%
    %return 0
  %endif
  %if LibIsDataTypeCGClassOrContainClass(dataTypeId)
    %return 0
  %endif
   
  %%
  %if LibIsEnumDataType(dataTypeId)
    %%
    %% We don't want to use memset for enumerated data
    %%
    %return 0
  %endif
  %if !ISEMPTY(SLibDataTypeConstructFcnName(dataTypeId))
    %%
    %% We don't want to use memset for classes with constructors
    %%
    %return 0
  %endif
  %%
  %assign storageDataType = ...
    LibGetDataTypeStorageIdFromId(...
    LibGetDataTypeIdAliasedThruToFromId(dataTypeId))
  %%
  %switch storageDataType
    %%
    %case tSS_DOUBLE
    %case tSS_SINGLE
      %%
      %% For a given chip, the bit encoding of floating point numbers might or
      %% might NOT represent 0.0 as the all zero bit pattern. For this reason,
      %% memset is not trusted when dealing with floating point.
      %%
      %if InitFltsAndDblsToZero || ...
          !SLibValueIsAllZeroBitsCrudeCheck(dataTypeId, valueToSet)
        %%
        %return 0
        %%
      %else
        %%
        %return 1
        %%
      %endif
      %break
    %case tSS_UINT8
    %case tSS_UINT16
    %case tSS_UINT32
    %case tSS_INT8
    %case tSS_INT16
    %case tSS_INT32
    %case tSS_BOOLEAN
      %%
      %% Data type is OK for memset, provide
      %% value is suitable
      %%
      %break
    %default
      %% Handle half precision
      %if LibIsHalfDataType(LibGetDataTypeIdAliasedThruToFromId(dataTypeId))
        %if InitFltsAndDblsToZero || ...
          !SLibValueIsAllZeroBitsCrudeCheck(dataTypeId, valueToSet)
          %%
          %return 0
          %%
        %else
          %%
          %return 1
          %%
        %endif
      %endif
      %%
      %% Data type not recognized
      %% use memset only if the value is zero
      %%
      %if SLibValueIsAllZeroBitsCrudeCheck(dataTypeId, valueToSet)
        %return 1
      %else
        %return 0
      %endif
      %%break
  %endswitch
  %%
  %% Check suitability of value
  %%
  %% memset takes an int value, but writes out an unsigned char.
  %% there is a potential for lost information. If the data
  %% type is bigger than a char, then memset actually writes
  %% the bit pattern multiple times into the wider memory
  %% slot. For wider data, not many values will be comprised
  %% of the same char bit pattern repeated multiple times.
  %% The all zero bit pattern is an important value that
  %% does meet that criteria. A key goal of this code
  %% is for the all zero case to be handled by memset.
  %%
  %% For most other values, memset will not be suitable.
  %%
  %if SLibValueIsAllZeroBitsCrudeCheck(dataTypeId, valueToSet)
    %%
    %return 1
    %%
  %elseif ( TYPE(valueToSet) == "Number" ) || ( TYPE(valueToSet) == "Unsigned" )
    %%
    %switch storageDataType
        %%
      %case tSS_UINT8
      %case tSS_INT8
        %%
        %if IntegerSizes.CharNumBits < 8
          %%
          %% multiple chars make up data type
          %%
          %return 0
          %%
        %endif
        %break
        %%
      %case tSS_UINT16
      %case tSS_INT16
        %%
        %if IntegerSizes.CharNumBits < 16
          %%
          %% multiple chars make up 16 bit data type
          %%
          %return 0
          %%
        %endif
        %break
        %%
      %case tSS_UINT32
      %case tSS_INT32
        %%
        %if IntegerSizes.CharNumBits < 32
          %%
          %% multiple chars make up 32 bit data type
          %%
          %return 0
          %%
        %endif
        %break
        %%
      %case tSS_BOOLEAN
      %default
        %%
        %% don't try memset for boolean and non-zero value.
        %%
        %return 0
        %%break
        %%
    %endswitch
    %%
    %% memset takes an int value, but writes out an unsigned char.
    %% there is a potential for lost information. Not clear what
    %% happens with negative values, so avoid that case.
    %%
    %if valueToSet >= 0
      %return 1
    %else
      %return 0
    %endif
  %endif
  %%
  %return 0
  %%
%endfunction
 
%%Function:FcnPreferMemsetToAssignment=======================================
%%
%function FcnPreferMemsetToAssignment(width, dataTypeId) void
  %%
  %if LibIsEnumDataType(dataTypeId)
    %%
    %% We don't want to use memset for enumerated data
    %%
    %return 0
  %elseif !ISEQUAL(width,1)
    %%
    %% if not scalar, assume memset perferrable
    %%
    %return 1
  %else
    %%
    %assign storageDataType = ...
      LibGetDataTypeStorageIdFromId(...
      LibGetDataTypeIdAliasedThruToFromId(dataTypeId))
    %%
    %switch storageDataType
        %%
      %case tSS_DOUBLE
      %case tSS_SINGLE
      %case tSS_UINT8
      %case tSS_UINT16
      %case tSS_UINT32
      %case tSS_INT8
      %case tSS_INT16
      %case tSS_INT32
      %case tSS_BOOLEAN
        %%
        %% For known builtin data types, assume
        %% scalar assignment is preferrable to memset
        %%
        %return 0
        %%break
      %default
        %if LibIsHalfDataType(LibGetDataTypeIdAliasedThruToFromId(dataTypeId))
          %% same as built in
          %return 0
        %endif
        %%
        %% unrecognized data type,
        %% assume memset perferrable.
        %return 1
        %%break
    %endswitch
  %endif
%endfunction
 
%%Function:FcnMemsetToZeroInitSuffice========================================
%%
%%WhensettingachunkofmemoryofgivendatatypeIDtoits
%%defaultinitialvalue,determineifamemsetto0issufficient.
%%
%%TopTester:test/toolbox/simulink/blocks/tenable.m
%%
%function FcnMemsetToZeroInitSuffice(dataTypeId) void
  %%
  %assign retValue = 0
  %%
  %assign dataTypeThruId = LibGetDataTypeIdAliasedThruToFromId(dataTypeId)
  %%
  %if SLibDefaultInitialValueIsAllZeroBits(dataTypeThruId) && ...
    ISEMPTY(SLibDataTypeConstructFcnName(dataTypeThruId))
    %%
    %% hard code 0 as the init value below for speed
    %%
    %if FcnSuitableForMemset(0, dataTypeThruId, "")
      %%
      %assign retValue = 1
    %endif
  %endif
  %%
  %return retValue
%endfunction
 
%%Function:FcnCastValueForMemsetUse==========================================
%%
%%Thesecondinputargumenttomemsetisdatatypeint.
%%Somecompilerscomplainabouttrivialconversionslike
%%memset(ptr,0.0,40)
%%Thisfunctioncleansupthesecondinputargumentin
%%atrivialwaysothecompilerdoesn'tcomplain.
%%memset(ptr,0,40)
%%TopTester:test/toolbox/simulink/blocks/tenable.m
%function FcnCastValueForMemsetUse(dTypeId, valueToSet) void
  %%
  %if SLibValueIsAllZeroBitsCrudeCheck(dTypeId, valueToSet)
    %assign retValue = 0
  %else
    %assign retValue = valueToSet
  %endif
  %%
  %return retValue
%endfunction
 
%%Function:FcnSkipDataInitialValueInReg======================================
%%
%%Whenasignalordworkrecordhasnon-emptyInitialValue,determine
%%whetheritneedstoappearinRegFcncode(forexampleifthesame
%%InitialValuealreadybeenassignedincustomstorageclassStatic
%%init,itnolongerneedstoappearinRegFcncode)
%%
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmFunctionCallSplitBlock_hidden_VC1.m
%%
%function FcnSkipDataInitialValueInReg(datarec) void
  %assert !ISEMPTY(datarec.InitialValue)
  %assert (datarec.StorageClass != "ImportedExtern" && ...
       datarec.StorageClass != "ImportedExternPointer")
  %%
  %assign retValue = TLC_FALSE
  %%
  %if (datarec.StorageClass == "Custom")
    %assign cscDefn = SLibGetCSCDefForData(datarec)
    %assign dataInit = SLibGetDataInitForData(cscDefn, datarec)
    %if (dataInit == "Static" || dataInit == "None")
      %assign retValue = TLC_TRUE
    %endif
  %endif
   
  %if LibIsDataTypeCGClassType(LibGetRecordDataTypeId(datarec))
    %assign retValue = TLC_TRUE
  %endif
   
  %if (EXISTS("SigObjWithICMapsFullyToOutportsWithIC") && ...
    datarec.SigObjWithICMapsFullyToOutportsWithIC == "yes")
    %assign retValue = TLC_TRUE
  %endif
  %%
  %return retValue
%endfunction
 
%%Function:SLibEmitForLoopCounterCode=======================================
%%Abstract:
%%Helperfunctiontoemititeratordefinitionandfor-loopstmt,where
%%theiteratortype,forthetarget,dependsonthenumberofiterations
%%TopTester:test/toolbox/simulink/blocks/tenable.m
%%
%function SLibEmitForLoopCounterCode(loopCount, idx) void
  %% put out the iterator definition
  %assert TYPE(loopCount) == "String" || TYPE(loopCount) == "Number"
  %assign indexDecl = "%<LibCGTypeName(::CompiledModel.CGTypes.IndexType)>" + " " + idx + ";"
  %% then put out the for-loop stmt
  %assign forEntry = "for (%<idx> = 0; %<idx> < %<loopCount>; %<idx>++)"
  %return ["%<indexDecl>", "%<forEntry>"]
%endfunction
 
 
%%Function:SLibEmitLibCustomInitCode=========================================
%%Abstract:
%%HelperfunctiontoemitinitializationcodeforCustomData.Takeinto
%%accountwidth(1isasimpleassignment),complexity(mightrequire
%%realandimaginaryfieldassignments)andRollThreshold(canweusea
%%forloop,ordoweemitoneinitialization"foreach"element?
%%
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants2.m
%%
%function SLibEmitLibCustomInitCode(name, initCount, isComplex) Output
  %assert TYPE(initCount) == "String"
 
  %assign twoParts = IDNUM(initCount)
  %assign isSymbolic = !ISEMPTY(twoParts[0])
 
  %if "%<initCount>" == "1"
    %% scalar case
    %if isComplex
      %<LibCustomData(name,"initialize","",tRealPart)>
      %<LibCustomData(name,"initialize","",tImagPart)>
    %else
      %<LibCustomData(name,"initialize","","")>
    %endif
  %elseif isSymbolic || %<initCount> >= RollThreshold
    %assign sigIndexer = SLibGet1DArrayIndexer(initCount, "i", "", 0)
    %% guard against empty for-loop if removing zero initialization
    %openfile customLoopBuffer
    %if isComplex
      %<LibCustomData(name,"initialize",sigIndexer,tRealPart)>
      %<LibCustomData(name,"initialize",sigIndexer,tImagPart)>
    %else
      %<LibCustomData(name,"initialize",sigIndexer,"")>
    %endif
    %closefile customLoopBuffer
    %if !WHITE_SPACE(customLoopBuffer)
      %assign loopCode = SLibEmitForLoopCounterCode(initCount, "i")
      {
        %
        % {
          %<customLoopBuffer>/
        }
      }
    %endif
  %else
    %% %<initCount> is an integer
    %foreach initIdx = %<initCount>
      %assign sigIndexer = SLibGet1DArrayIndexer(%<initCount>, "%<initIdx>", "", 0)
      %if isComplex
        %<LibCustomData(name,"initialize",sigIndexer,tRealPart)>
        %<LibCustomData(name,"initialize",sigIndexer,tImagPart)>
      %else
        %<LibCustomData(name,"initialize",sigIndexer,"")>
      %endif
    %endforeach
  %endif
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:SLibShouldSkipInitForRecord
%%Abstract:
%%Returnstrueifthegivendatarecordshouldbeskippedforinitialization.
%function SLibShouldSkipInitForRecord(rec) void
  %% We never know the initial "value" of a class or if assignment may work
  %% So always skip init for class
  %return LibIsDataTypeCGClassType(LibGetRecordDataTypeId(rec))
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:SLibShouldForbidMemsetToZeroForRecord
%%Abstract:
%%Returnstrueifmemsettozeroshouldbeforbiddenforthegivendatarecord.
%function SLibShouldForbidMemsetToZeroForRecord(rec) void
  %return LibIsDataTypeCGClassOrContainClass(LibGetRecordDataTypeId(rec))
%endfunction
 
%%Function:SLibRemoveZeroInitForData=========================================
%%Abstract:
%%Returntrueifagiveninitvalueshouldnotbeemittedintocode
%%becausethatZeroExternalMemoryAtStartup/ZeroInternalMemoryAtStartup
%%optionisfalse,andthatthevalueisofzero-representation
%%
%%Noteonhowthetwooptionsarechecked:
%%"ExternalInput":checksZeroExternalMemoryAtStartup
%%"ExternalOutput":checksZeroExternalMemoryAtStartup
%%"BlockOutput"withexternalstorageclassanddrivesrootoutport:
%%checksZeroExternalMemoryAtStartup
%%Anyother:checksZeroInternalMemoryAtStartup
%%
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%TopTester:test/toolbox/simulink/blocks/lib_SignalAttributes/Width/rtw/tNumerics_width_single.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tvss_code_variants.m
%%
%function SLibRemoveZeroInitForData(datarec, valueToInit) void
 
  %assign retVal = TLC_TRUE
   
  %if SLibShouldSkipInitForRecord(datarec)
    %return TLC_TRUE
  %endif
   
  %if (datarec.RecordType == "ExternalInput") || ...
      (datarec.RecordType == "ExternalOutput") || ...
      ( (datarec.RecordType == "BlockOutput") && ...
        (datarec.StorageClass != "Auto") && ...
        (datarec.DrivesRootOutport == "yes") )
    %if ZeroExternalMemoryAtStartup
      %assign retVal = TLC_FALSE
    %endif
  %else
    %if ZeroInternalMemoryAtStartup
      %assign retVal = TLC_FALSE
    %endif
  %endif
 
  %if retVal
    %assign dTypeId = SLibGetRecordDataTypeId(datarec)
    %assign isZero = SLibValueIsAllZeroBitsCrudeCheck(dTypeId, valueToInit)
     
    %assign retVal = isZero
  %endif
   
  %if ::GenerateInitCodeRemoved
     %assign retVal = !retVal
  %endif
   
  %return retVal
%endfunction
 
 
%function SLibGenCodeForResetWithInit()
  %assign rootSystem = System[NumSystems-1]
  %assign currentTid = rootSystem.CurrentTID
  %return TYPE(currentTid) == "Number" && currentTid >= 0 && ...
    ISFIELD(SampleTime[currentTid],"EventSourceName") && ...
    SampleTime[currentTid].EventSourceType == "ResetWithInitEvent"
%endfunction
 
 
%%Function:SLibRemoveZeroInitForDataDefault==================================
%%Abstract:
%%SimilartoSLibRemoveZeroInitForData,butchecksthedefaultinitial
%%value.WouldnottriggertheGroundUsedflagforstructdatatype.
%%
%%
%%TopTester:test/toolbox/simulink/variants/codevariants/tvss_code_variants.m
%%
%function SLibRemoveZeroInitForDataDefault(datarec) void
  %assign retVal = TLC_TRUE
   
  %if SLibShouldSkipInitForRecord(datarec)
    %return TLC_TRUE
  %endif
   
  %if (datarec.RecordType == "ExternalInput") || ...
      (datarec.RecordType == "ExternalOutput") || ...
      ( (datarec.RecordType == "BlockOutput") && ...
        (datarec.StorageClass != "Auto") && ...
        (datarec.DrivesRootOutport == "yes") )
    %if ZeroExternalMemoryAtStartup
      %assign retVal = TLC_FALSE
    %endif
  %else
    %if ZeroInternalMemoryAtStartup || SLibGenCodeForResetWithInit()
      %assign retVal = TLC_FALSE
    %endif
  %endif
 
  %if retVal
    %if (datarec.RecordType=="ExternalOutput")
      %assign dTypeId = LibBlockInputSignalDataTypeId(0)
    %else
      %assign dTypeId = SLibGetRecordDataTypeId(datarec)
    %endif
     
    %assign retVal = SLibDataTypeRequiresZeroInit(dTypeId, TLC_FALSE)
  %endif
   
  %if ::GenerateInitCodeRemoved
    %assign retVal = !retVal
  %endif
   
  %return retVal
%endfunction
 
%%Function:SLibZeroMemory====================================================
%%Abstract:
%%ProvidefilteredaccesstoZeroInternalMemoryAtStartupand
%%ZeroExternalMemoryAtStartup.Thisallowsustorecover
%%memoryzeroingroutineinS-functionwrapperwhenneeded
%%
%%TopTester:test/toolbox/simulink/variants/codevariants/tvss_code_variants.m
%%
%function SLibZeroMemory(recordType) void
  %assign retVal = TLC_FALSE
 
  %if (recordType=="RTM") && (SLibHasSelfWithStaticInit() || (::GenCPP == 1 && !SLibIsRTMZeroInitCppEnabled()))
    %assign retVal = TLC_FALSE
  %elseif (recordType=="ExternalInput") || ...
    (recordType=="ExternalOutput")
    %if ZeroExternalMemoryAtStartup
      %assign retVal = TLC_TRUE
    %endif
  %else
    %if ZeroInternalMemoryAtStartup || SLibGenCodeForResetWithInit()
      %assign retVal = TLC_TRUE
    %endif
  %endif
 
  %if ::GenerateInitCodeRemoved
    %assign retVal = !retVal
  %endif
   
  %return retVal
   
%endfunction
 
%%Function:LibDumpModelInitializeSizes=======================================
%%Abstract:
%%DumpsthedeclarationstatementsrequiredforMdlInitializeSizes.
%%Supportsthesecodeformats
%%oRealTime
%%oRealTimeMalloc
%%
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants3.m
%%TopTester:test/toolbox/simulink/blocks/tlookuptabledynamic_blkSimstate.m
%%
%function LibDumpModelInitializeSizes() Output
  %<RTMSet("NumContStates", NumContStates)>; /* Number of continuous states */
  %if NumContStates > 0
    %<RTMSet("NumPeriodicContStates", NumPeriodicContStates)>; /* Number of periodic continuous states */
  %endif
  %<RTMSet("NumY", NumModelOutputs)>; /* Number of model outputs */
  %<RTMSet("NumU", NumModelInputs)>; /* Number of model inputs */
  %if DirectFeedthrough == "yes"
    %<RTMSet("DirectFeedThrough", 1)>; /* The model is direct feedthrough */
  %else
    %<RTMSet("DirectFeedThrough", 0)>; /* The model is not direct feedthrough */
  %endif
  %<RTMSet("NumSampleTimes", NumRuntimeExportedRates)>; /* Number of sample times */
  %<RTMSet("NumBlocks", NumNonVirtBlocksInModel)>; /* Number of blocks */
  %if NumBlockSignals > 0
    %<RTMSet("NumBlockIO", BlockOutputs.NumGlobalBlockOutputs)>; ...
      /* Number of block outputs */
  %endif
  %if !LibParametersStructIsEmpty()
    %assign nPrms = ::CompiledModel.NumPrmStructElements
    %<RTMSet("NumBlockParams", nPrms)>; /* Sum of parameter "widths" */
  %endif
%endfunction
 
 
%%Function:LibDumpModelInitializeSampleTimes=================================
%%Abstract:
%%Dumpsthecoderequiredtoregisterthemodelssampletimes
%%TopTester:test/toolbox/simulink/variants/string/tStringSupport.m
%%
%function LibDumpModelInitializeSampleTimes() Output
  %if CodeFormat == "S-Function" && AllSampleTimesInherited == "yes"
    %<RTMSetIdxed("SampleTime", 0, "INHERITED_SAMPLE_TIME")>;
    %<RTMSetIdxed("OffsetTime", 0, "0.0")>;
  %else
    /* task periods */
    %foreach tidIdx = NumRuntimeExportedRates
      %assign period = SampleTime[tidIdx].PeriodAndOffset[0]
      %<RTMSetIdxed("SampleTime", tidIdx, period)>;
    %endforeach
 
    /* task offsets */
    %foreach tidIdx = NumRuntimeExportedRates
      %assign offset = SampleTime[tidIdx].PeriodAndOffset[1]
      %<RTMSetIdxed("OffsetTime", tidIdx, offset)>;
    %endforeach
  %endif
%endfunction
 
 
%%FunctionSLibBooleanZCTest==================================================
%%Abstract:
%%Generatestheappropriatezero-crossingtestforbooleantriggersignals.
%%
%function SLibBooleanZCTest(zcDir, trigSignal, prevZC,castRequired) void
  %assign cast = castRequired ? "(ZCEventType) " : ""
  %switch zcDir
    %case "RISING_ZERO_CROSSING"
      %return "%<cast>(%<trigSignal> && (%<prevZC> != POS_ZCSIG))"
    %case "FALLING_ZERO_CROSSING"
      %return "%<cast>(!%<trigSignal> && (%<prevZC> != ZERO_ZCSIG))"
    %case "ANY_ZERO_CROSSING"
      %return "%<cast>((%<trigSignal> != (%<prevZC> == POS_ZCSIG)) &&/n(%<prevZC> != UNINITIALIZED_ZCSIG))"
  %endswitch
 
%endfunction
 
 
%%FunctionSLibUnsignedZCTest=================================================
%%Abstract:
%%Generatestheappropriatezero-crossingtestforunsignedtriggersignals.
%%
%function SLibUnsignedZCTest(zcDir, trigSignal, prevZC, castRequired) void
 
  %assign cast = castRequired ? "(ZCEventType) " : ""
  %switch zcDir
    %case "RISING_ZERO_CROSSING"
      %return "%<cast>((%<trigSignal> > 0) && (%<prevZC> != POS_ZCSIG))"
    %case "FALLING_ZERO_CROSSING"
      %return "%<cast>((%<trigSignal> == 0) && (%<prevZC> != ZERO_ZCSIG ))"
    %case "ANY_ZERO_CROSSING"
      %return "%<cast>(((%<trigSignal> > 0) != (%<prevZC> == POS_ZCSIG)) &&/n(%<prevZC> != UNINITIALIZED_ZCSIG))"
  %endswitch
 
%endfunction
 
%%Function:SLibGetSystemConstructionCode========================================
%%Abstract:
%%Returnsthesystemconstructioncodeagivensystem.
%%TopTester:test/toolbox/simulink/variants/codevariants/tmg1672961.m
%%
%function SLibGetSystemConstructionCode(aSystem) void
  %assign fcnType = "ModelConstructor"
  %assign prevActiveFcn = FcnGetActiveFcnForDecl()
  %assign ::BlockFcn = fcnType
  %assign codeFragment = SLibFcnGenCodeFragment(aSystem, fcnType)
  %assign retVal = ""
  %if !WHITE_SPACE(codeFragment)
    %openfile retVal
    %assign localVars = ...
      FcnDeclareAccessedLocalVariables(aSystem) + ...
      LibGetSystemLocalVars(aSystem, fcnType, "") + ...
      SLibGetFcnLocalVars(aSystem, fcnType, "")
    %if !WHITE_SPACE(localVars)
      %if !GenerateClassInterface
      {
      %endif
      %<localVars>
      %<codeFragment>
      %if !GenerateClassInterface
      }
      %endif
    %else
      %<codeFragment>
    %endif
    %closefile retVal
  %endif
  %assign ::BlockFcn = prevActiveFcn
  %return retVal
%endfunction %% SLibGetPrevZCStateInitCode
 
%%Function:SLibGetPrevZCStateInitCode========================================
%%Abstract:
%%Returnsthepreviouszerocrossingsignalinitializationforagivenroot
%%orstandalonesystem.
%%
%function SLibGetPrevZCStateInitCode(aSystem) void
  %return SLibDumpInitializationCodeForFcn(aSystem, "ModelPrevZCStateInit")
%endfunction %% SLibGetPrevZCStateInitCode
 
%%FunctionSLibDumpOpaqueTypeConstructCode=============================
%%Abstract:
%%ThisfunctiongetstheopaquetypeconstructioncodefromOpaqueTypeConstruct.tlc
%%
%function SLibDumpOpaqueTypeConstructCode(aSystem) void
  %assign fcnType = "OpaqueTypeConstruct"
  %assign codeFragment = SLibFcnGenCodeFragment(aSystem, fcnType)
  %assign buffer = ""
  %openfile buffer
  %if !WHITE_SPACE(codeFragment)
    %assign localVars = SLibGetFcnLocalVars(aSystem, fcnType, "")
    %if !WHITE_SPACE(localVars)
      %if !GenerateClassInterface
      {
      %endif
      %<localVars>
      %<codeFragment>
      %if !GenerateClassInterface
      }
      %endif
    %else
      %<codeFragment>
    %endif
  %endif
  %foreach dtIdx = ::CompiledModel.DataTypes.NumDataTypes
    %if !ISEMPTY(SLibDataTypeConstructFcnName(dtIdx)) && ...
      SLibGetDataTypeGroundReqInMemory(dtIdx)
      %assign fcnName = SLibDataTypeConstructFcnName(dtIdx)
      %assign grdName = SLibGetDtGroundName(dtIdx, TLC_FALSE, "")
      %<fcnName>(&%<grdName>);
    %endif
  %endforeach
  %closefile buffer
  %return buffer
%endfunction %% SLibDumpOpaqueTypeConstructCode
 
%%FunctionSLibDumpOpaqueTypeDestructCode=============================
%%Abstract:
%%ThisfunctiongetstheopaquetypedestructioncodefromOpaqueTypeDestruct.tlc
%%
%function SLibDumpOpaqueTypeDestructCode(aSystem, aFcnType, needGround) void
  %assign codeFragment = SLibFcnGenCodeFragment(aSystem, aFcnType)
  %assign buffer = ""
  %openfile buffer
  %if !WHITE_SPACE(codeFragment)
    %assign localVars = SLibGetFcnLocalVars(aSystem, aFcnType, "")
    %if !WHITE_SPACE(localVars)
      %if !GenerateClassInterface
      {
      %endif
      %<localVars>
      %<codeFragment>
      %if !GenerateClassInterface
      }
      %endif
    %else
      %<codeFragment>
    %endif
  %endif
  %if needGround
    %foreach dtIdx = ::CompiledModel.DataTypes.NumDataTypes
    %if !ISEMPTY(SLibDataTypeDestructFcnName(dtIdx)) && ...
      SLibGetDataTypeGroundReqInMemory(dtIdx)
      %assign fcnName = SLibDataTypeDestructFcnName(dtIdx)
      %assign grdName = SLibGetDtGroundName(dtIdx, TLC_FALSE, "")
      %<fcnName>(&%<grdName>);
    %endif
    %endforeach
  %endif
  %closefile buffer
  %return buffer
%endfunction %% SLibDumpOpaqueTypeDestructCode
 
%%FunctionSLibDumpExternalInputsInitializationCode=============================
%%Abstract:
%%Thisfunctiongetstheroot/externalinputscodefromModelExternalInputInit.tlc
%%
%function SLibDumpExternalInputsInitializationCode(aSystem) void
  %return SLibDumpInitializationCodeForFcn(aSystem, "ModelExternalInputInit")
%endfunction %% SLibDumpExternalInputsInitializationCode
 
%%FunctionSLibDumpExternalOutputsInitializationCode=============================
%%Abstract:
%%Thisfunctiongetstheroot/externaloutputscodefromModelExternalOutputInit.tlc
%%
%function SLibDumpExternalOutputsInitializationCode(aSystem) void
  %return SLibDumpInitializationCodeForFcn(aSystem, "ModelExternalOutputInit")
%endfunction %% SLibDumpExternalOutputsInitializationCode
 
%%FunctionSLibDumpInitializationCodeForFcn=====================
%%Abstract:
%%Givenasystemandasystemfunctiontype,thisfunctionreturns
%%thecodefragmentofthatfunctionfromtherespective.tlcfile.
%function SLibDumpInitializationCodeForFcn(aSystem, aFcnType) void
  %assign codeFragment = SLibFcnGenCodeFragment(aSystem, aFcnType)
  %assign retVal = ""
  %if !WHITE_SPACE(codeFragment)
    %openfile retVal
    %assign localVars = ...
      LibGetSystemLocalVars(aSystem, aFcnType, "") + ...
      SLibGetFcnLocalVars(aSystem, aFcnType, "")
    %if !WHITE_SPACE(localVars)
      {
        %<localVars>
        %<codeFragment>
      }
    %else
      %<codeFragment>
    %endif
    %closefile retVal
  %endif
  %return retVal
%endfunction
 
%%FunctionSLibInitPrevZCSignalState==========================================
%%Abstract:
%%Initializethepreviouszero-crossingstateforablock.Notethatit
%%isinitializedtoavaluethatguaranteesthatthetriggerisnevertrue
%%attimezero.Sincetheregistrationcodesetspreviouszc'sto
%%UNINITIALIZED_ZCSIG,onlyoverwritewhennecessary(i.e.,rising/falling
%%triggersforunsignedandbooleandatatypes).
%%
%function SLibInitPrevZCSignalStates() void
  %assign baseSystem = ::CompiledModel.System[GetBaseSystemIdx()]
  %return SLibGetPrevZCStateInitCode(baseSystem)
%endfunction
%%adzc
 
%%Function:LibDumpModelRegPrevZCStates================================
%%Abstract:
%%Dumpsthecoderequiredtoinitializethepreviouszerocrossingevents
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortHighlight.m
%%
%function SLibDumpModelRegPrevZCStates() Output
  %if SLibGetUseRTMcgType()
    %return
  %endif
  %assign prevZCStatesInRTM = FcnGetPrevZCSigStateType()
  /* previous zero-crossing states */
  {
    %if UsingMalloc
      %<prevZCStatesInRTM> *zc = (%<prevZCStatesInRTM> *) malloc(sizeof(%<::tPrevZCStateType>));
      %<RTMChkMemAndReturnIfErr("zc")>;
    %else
      %assign addr = MultiInstanceERTCode ? "" : "&"
      %<prevZCStatesInRTM> *zc = (%<prevZCStatesInRTM> *) %<addr>%<LibGetPreviousZCStruct()>;
      %<SLibAccessArgHelper(rootSystem.Interface.ZCEventArgDef,"",rootSystem.CurrentTID)>
    %endif
    %<RTMSet("PrevZCSigState", "zc")>;
  }
%endfunction
 
 
%%Function:LibDumpModelInitPrevZCStates================================
%%Abstract:
%%Dumpsthecoderequiredtoinitializethepreviouszerocrossingevents
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortHighlight.m
%%
%function SLibDumpModelInitPrevZCStates() Output
  /* previous zero-crossing states */
  {
    %if UsingMalloc && ::CompiledModel.HasSimStructVars == 0 && !SLibIsERTCodeFormat()
      {
         
        %<::tPrevZCStateType> *%<LibGetPreviousZCStruct()> = /
        (%<::tPrevZCStateType> *) %<RTMGet("PrevZCSigState")>;
        %<SLibInitPrevZCSignalStates()>/
         
      }
    %else
      %<SLibInitPrevZCSignalStates()>/
    %endif
  }
%endfunction
 
 
%%Function:LibDumpModelInitializePrevZCStates================================
%%Abstract:
%%Dumpsthecoderequiredtoinitializethepreviouszerocrossingevents
%function LibDumpModelInitializePrevZCStates(bEmitReg, bEmitInit) Output
    %if bEmitReg
      %<SLibDumpModelRegPrevZCStates()>
    %endif
    %if bEmitInit
      %<SLibDumpModelInitPrevZCStates()>
    %endif %%
%endfunction
 
 
%%Function:FcnDisableStateLogging============================================
%%Abstract:
%function FcnDisableStateLogging(dlo) void
  %assign dlo.StateSaveName = ""
  %assign dlo.FinalStateName = ""
  %return
%endfunction
 
%%Function:FcnIsStateLoggingEnabled==========================================
%%Abstract:
%function FcnIsStateLoggingEnabled(dlo) void
  %return (dlo.StateSaveName != "" || dlo.FinalStateName != "")
%endfunction
 
%%Function:InitLogDataTypeConvertStructure
%%Abstract:
%%InitializetheRTWLogDataTypeConvertstructureusedbylogging.
%%
%%Returns:
%%Structwiththefollowingfields:
%%0.needConvert
%%1.dTypeEnum
%%2.dTypeStorageEnum
%%3.bitsPerChunk
%%4.numOfChunk
%%5.isSigned
%%6.fSlope
%%7.fixExp
%%8.bias
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/tStringSupport.m
%%
%function InitLogDataTypeConvertStructure(dTypeId) void
  %if LibIsBuiltInDataType(dTypeId)
    %%
    %assign needConvert = 0
    %assign dTypeEnum = LibGetDataTypeEnumFromId(dTypeId)
    %assign dTypeStorageEnum = dTypeEnum
    %% These next three members are not used in this case
    %assign bitsPerChunk = 0
    %assign numOfChunk = 0
    %assign isSigned = 0
    %assign fSlope = 1.0
    %assign fixExp = 0
    %assign bias = 0.0
  %else
    %assign needConvert = 1
    %assign curDT = FixPt_GetDataTypeFromIndex(dTypeId)
    %assign dTypeEnum = LibGetDataTypeEnumFromId(tSS_DOUBLE)
    %assign dTypeStorageEnum = LibGetDataTypeEnumFromId(curDT.StorageId)
    %if !FixPt_DataTypeIsFloat(curDT)
      %assign bitsPerChunk = LargestIntegerNumBits
      %assign numOfChunk = FixPt_NumChunks(curDT.RequiredBits)
      %assign isSigned = curDT.IsSigned
    %else
      %% floating point and scaled doubles
      %% These next three members are not used in this case
      %assign bitsPerChunk = 0
      %assign numOfChunk = 0
      %assign isSigned = 0
    %endif
    %assign fSlope = curDT.FracSlope
    %assign fixExp = curDT.FixedExp
    %assign bias = curDT.Bias
  %endif
  %assign retVectStr = ["%<needConvert>", "%<dTypeEnum>", "%<dTypeStorageEnum>", "%<bitsPerChunk>", "%<numOfChunk>", "%<isSigned>", "%<fSlope>", "%<fixExp>", "%<bias>" ]
  %return retVectStr
  %%
%endfunction %%InitLogDataTypeConvertStructure
   
%%Function:FcnLogStateSetup==================================================
%%Abstract:
%%Setupstatesforstructurelogging
%%
%%TopTester:test/toolbox/simulink/variants/codevariants/tvss_code_variants.m
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/tStringSupport.m
%%TopTester:test/toolbox/simulink/variants/tvss_masked_linked_change_active_variant.m
%%
%function FcnLogStateSetup(bEmitReg, bEmitInit, dlo) Output
  %assign cr = ""
  %assign qt = "/""
  %assign comma = ""
  %assign sigPtrsStr = ""
  %assign widthStr = ""
  %assign dimsStr = ""
  %assign isVarDimsStr = ""
  %assign numDimsStr = ""
  %assign dTypeStr = ""
  %assign cmplxStr = ""
  %assign preprocessingFcnPtrsStr = ""
  %assign labelStr = ""
  %assign labelLenStr = ""
  %assign blkNameStr = ""
  %assign crossMdlStr = ""
  %assign blkNameLenStr= ""
  %assign stateNameStr = ""
  %assign dataTypeConvertInitStr = ""
 
  %assign numLoggedStates = 0
   
  %assign cr = "/n"
  %assign nSig = "rt_LoggedStateSignalInfo.numSignals"
  %assign nSigpp = "rt_LoggedStateSignalInfo.numSignals++"
   
  %assign numLoggedRecords = 0
  %foreach i = ::CompiledModel.ContStates.NumContStates
    %assign cs = ::CompiledModel.ContStates.ContState[i]
    %if cs.DataLoggingOn
      %assign numLoggedRecords = numLoggedRecords + cs.Partitions.NumPartitions
    %endif
  %endforeach
  %foreach i = ::CompiledModel.DWorks.NumDWorks
    %assign dwRec = ::CompiledModel.DWorks.DWork[i]
    %if (dwRec.UsedAs == "DSTATE" && dwRec.DataLoggingOn)
      %if SLibIsGlobalDataRecWithNoExternalLinkage(dwRec)
        %continue
      %endif
      %assign numLoggedRecords = numLoggedRecords + 1
    %endif
  %endforeach
  %assign loggedRecordIdx = 0
  %with ::CompiledModel.ContStates
    %assign dTypeId = tSS_DOUBLE
    %assign cmpxSig = 0
    %assign label = "CSTATE"
    %%
    %assign dtConvertParams = InitLogDataTypeConvertStructure(dTypeId)
    %%
    %foreach i = NumContStates
      %if (loggedRecordIdx < (numLoggedRecords-1)) || FcnDynamicLog()
        %assign comma = ","
      %else
        %assign comma = ""
      %endif
      %assign cs = ContState[i]
      %if !cs.DataLoggingOn
        %continue
      %endif
      %assign offset = 0
      %foreach recIdx = cs.Partitions.NumPartitions
        %assign sigAddr = "&" + SLibContinuousState(cs, "", "", offset,NumSystems-1, TLC_FALSE)
        %assign width = cs.Partitions.Partition[recIdx].Width
        %assign stateName = cs.Partitions.Partition[recIdx].Name
        %if cs.Partitions.Partition[recIdx].PathAlias == ""
          %assign blkName = SLibGrBlockPath(cs.GrSrc)
        %else
          %assign blkName = cs.Partitions.Partition[recIdx].PathAlias
        %endif
        %if UsingMalloc
          %assign lhs_eq = "((void **) %<RTMLoggingGet("LogXSignalPtrs")>)[%<numLoggedStates>] = "
        %else
          %if FcnDynamicLog()
            %assign lhs_eq = "rt_LoggedStateSignalPtrs[%<nSig>] = "
          %else
            %assign lhs_eq = "rt_LoggedStateSignalPtrs[%<numLoggedStates>] = "
          %endif
        %endif
        %%
    %assign sigPtrsStr = sigPtrsStr + cr + lhs_eq + "(void*)" + sigAddr + ";/n"
        %if FcnDynamicLog()
          %assign sigPtrsStr = sigPtrsStr + nSigpp + ";/n"
        %endif
        %assign sigPtrsStr = sigPtrsStr + cr
        %assign widthStr = widthStr + cr + "%<width>%<comma>" + cr + cr
        %assign numDimsStr = numDimsStr + cr + "1%<comma>" + cr + cr
        %assign dimsStr = dimsStr + cr + "%<width>%<comma>" + cr + cr
        %assign isVarDimsStr = isVarDimsStr + cr + "0%<comma>" + cr + cr
        %assign dTypeStr = dTypeStr + cr + "%%<comma>" + cr + cr
        %assign cmplxStr = cmplxStr + cr + "%<cmpxSig>%<comma>" + cr + cr
        %assign labelStr = labelStr + cr + qt + label + qt + "%<comma>" + cr + cr
        %assign blkNameStr = blkNameStr + cr + qt + STRING(blkName) + qt + "%<comma>" + cr + cr
        %assign stateNameStr = stateNameStr + cr + qt + stateName + qt + "%<comma>" + cr + cr
        %assign crossMdlStr = crossMdlStr + cr + "0%<comma>" + cr + cr
        %assign preprocessingFcnPtrsStr = preprocessingFcnPtrsStr + cr + "%<SLibGetNullDefinitionFromTfl()>%<comma>" + cr + cr
        %assign dataTypeConvertInitStr = dataTypeConvertInitStr + cr + ...
          "{ %, %, %," + ...
          " %, %, %," + ...
          " %, %, %}%<comma>" + cr + cr
        %%
        %assign numLoggedStates = numLoggedStates+1
        %assign loggedRecordIdx = loggedRecordIdx + 1
        %assign offset = offset + cs.Partitions.Partition[recIdx].Width
      %endforeach
    %endforeach
  %endwith
 
  %with ::CompiledModel.DWorks
    %foreach i = NumDWorks
      %if (DWork[i].UsedAs == "DSTATE" && DWork[i].DataLoggingOn)
        %if SLibIsGlobalDataRecWithNoExternalLinkage(DWork[i])
          %continue
        %endif
        %if (loggedRecordIdx < (numLoggedRecords-1)) || FcnDynamicLog()
          %assign comma = ","
        %else
          %assign comma = ""
        %endif
        %assign label = "DSTATE"
        %if DWork[i].Name != ""
          %assign label = DWork[i].Name
        %endif
    %assign ds = DWork[i]
        %assign vcRecord = SLibGetDataInlineVariantNetConditions(ds)
        %assign ifCond = vcRecord.ifCond
        %assign ifEndCond = vcRecord.endIfCond
        %assign sigAddr = SLibGetGlobalDWorkAddr(i,TLC_FALSE)
        %assign width = LibGetRecordSymbolicWidth(ds)
        %assign stateName = ds.LogStateName
    %assign dTypeId = LibGetDataTypeIdAliasedThruToFromId(...
      LibGetRecordDataTypeId(ds))
    %assign cmpxSig = SLibDWorkIsComplex(ds)
        %%
        %if (!LibIsDataTypeLogSupported(dTypeId, TLC_FALSE))
          %if FcnIsStateLoggingEnabled(dlo)
            %assign warnTxt = "MAT-File logging is not supported for " ...
              "states with data type '%<LibGetDataTypeNameFromId(dTypeId)>'."
            %<LibReportWarning(warnTxt)>
          %endif
          %continue
        %endif
        %%
        %assign dtConvertParams = InitLogDataTypeConvertStructure(dTypeId)
        %%
    %%% ============================================================
    %assign blkName = ...
          ISFIELD(ds, "GrSrc") ? SLibGrBlockPath(ds.GrSrc) : "synthesized block"
        %if UsingMalloc
            %assign lhs_eq = "((void **) %<RTMLoggingGet("LogXSignalPtrs")>)[%<numLoggedStates>] = "
        %else
          %if FcnDynamicLog()
            %assign lhs_eq = "rt_LoggedStateSignalPtrs[%<nSig>] = "
          %else
            %assign lhs_eq = "rt_LoggedStateSignalPtrs[%<numLoggedStates>] = "
          %endif
        %endif
    %%
    %assign sigPtrsStr = sigPtrsStr + ifCond + cr + lhs_eq + "(void*)" + sigAddr + ";/n"
        %if FcnDynamicLog()
          %assign sigPtrsStr = sigPtrsStr + nSigpp + ";/n"
        %endif
        %assign sigPtrsStr = sigPtrsStr + ifEndCond + cr
    %assign widthStr = widthStr + ifCond + cr + "%<width>%<comma>" + cr + ifEndCond + cr
        %assign isVarDimsStr = isVarDimsStr + ifCond + cr + "0%<comma>" + cr + ifEndCond + cr
    %assign numDimsStr = numDimsStr + ifCond + cr + "1%<comma>" + cr + ifEndCond + cr
    %assign dimsStr = dimsStr + ifCond + cr + "%<width>%<comma>" + cr + ifEndCond + cr
    %assign dTypeStr = dTypeStr + ifCond + cr + "%%<comma>" + cr + ifEndCond + cr
    %assign cmplxStr = cmplxStr + ifCond + cr + "%<cmpxSig>%<comma>" + cr + ifEndCond + cr
    %assign labelStr = labelStr + ifCond + cr + qt + label + qt + "%<comma>" + cr + ifEndCond + cr
    %assign blkNameStr = blkNameStr + ifCond + cr + qt + STRING(blkName) + qt + "%<comma>" + cr + ifEndCond + cr
    %assign stateNameStr = stateNameStr + ifCond + cr + qt + STRING(stateName) + qt + "%<comma>" + cr + ifEndCond + cr
    %assign crossMdlStr = crossMdlStr + ifCond + cr + "0%<comma>" + cr + ifEndCond + cr
        %assign preprocessingFcnPtrsStr = preprocessingFcnPtrsStr + ifCond + cr + "%<LibGetRecordPreprocessingFcnPtr(DWork[i])>%<comma>" + cr + ifEndCond + cr
        %%
        %assign dataTypeConvertInitStr = dataTypeConvertInitStr + ifCond + cr + ...
          "{ %, %, %," + ...
          " %, %, %," + ...
        " %, %, %}%<comma>" + cr + ifEndCond + cr
        %%
        %assign numLoggedStates = numLoggedStates+1
        %assign loggedRecordIdx = loggedRecordIdx + 1
      %endif
    %endforeach
    %if FcnDynamicLog()
      %assign widthStr = widthStr + "0" + cr
      %assign numDimsStr = numDimsStr + "0" + cr
      %assign dimsStr = dimsStr + "0" + cr
      %assign isVarDimsStr = isVarDimsStr + "0" + cr
      %assign dTypeStr = dTypeStr + "SS_DOUBLE" + cr
      %assign cmplxStr = cmplxStr + "0" + cr
      %assign labelStr = labelStr + qt + qt + cr
      %assign blkNameStr = blkNameStr + qt + qt + cr
      %assign stateNameStr = stateNameStr + qt + qt + cr
      %assign crossMdlStr = crossMdlStr + "0" + cr
      %assign preprocessingFcnPtrsStr = preprocessingFcnPtrsStr + "%<SLibGetNullDefinitionFromTfl()>" + cr + cr
      %assign dataTypeConvertInitStr = dataTypeConvertInitStr + ...
        "{ 0, SS_DOUBLE, SS_DOUBLE, 0, 0, 0, 0, 0, 0 }" + cr
    %endif
  %endwith
 
  %if (numLoggedStates == 0)
    %<FcnDisableStateLogging(dlo)>
    %return
  %endif
  {
  %if bEmitInit
  %assign typeQ = "static "
    %<typeQ> int_T rt_LoggedStateWidths[] =/
    {
      %<widthStr>
    };
 
    %<typeQ> int_T rt_LoggedStateNumDimensions[] =/
    {
      %<numDimsStr>
    };
 
    %<typeQ> int_T rt_LoggedStateDimensions[] =/
    {
      %<dimsStr>
    };
     
    %<typeQ> boolean_T rt_LoggedStateIsVarDims[] =/
    {
      %<isVarDimsStr>
    };
     
    %<typeQ> BuiltInDTypeId rt_LoggedStateDataTypeIds[] =/
    {
      %<dTypeStr>
    };
 
    %<typeQ> int_T rt_LoggedStateComplexSignals[] =/
    {
      %<cmplxStr>
    };
     
    %<typeQ> RTWPreprocessingFcnPtr rt_LoggingStatePreprocessingFcnPtrs[] =/
    {
      %<preprocessingFcnPtrsStr>
    };
 
    %<typeQ> const char_T *rt_LoggedStateLabels[] = {
    %<labelStr>};
 
    %<typeQ> const char_T *rt_LoggedStateBlockNames[] = {
    %<blkNameStr>};
       
    %<typeQ> const char_T *rt_LoggedStateNames[] = {
    %<stateNameStr>};
 
    %<typeQ> boolean_T rt_LoggedStateCrossMdlRef[] =/
    {
      %<crossMdlStr>
    };
 
    %<typeQ> RTWLogDataTypeConvert rt_RTWLogDataTypeConvert[] =/
    {
      %<dataTypeConvertInitStr>
    };
 
    %<typeQ> RTWLogSignalInfo rt_LoggedStateSignalInfo =/
    {
      %if FcnDynamicLog()
        0,
      %else
        %<numLoggedStates>,
      %endif
      rt_LoggedStateWidths,
      rt_LoggedStateNumDimensions,
      rt_LoggedStateDimensions,
      %% isVarDims field is useless for state logging
      %% So we set it to all 0's
      rt_LoggedStateIsVarDims, %% isVarDims
      %% currSigDims field is useless for state logging
      %% Just set it to NULL
      %<SLibGetNullDefinitionFromTfl()>, %% currSigDims
      %<SLibGetNullDefinitionFromTfl()>, %% currSigDimsSize
      rt_LoggedStateDataTypeIds,
      rt_LoggedStateComplexSignals,
      %<SLibGetNullDefinitionFromTfl()>, %% FrameData
      rt_LoggingStatePreprocessingFcnPtrs,
      {rt_LoggedStateLabels},
      %<SLibGetNullDefinitionFromTfl()>,
      %<SLibGetNullDefinitionFromTfl()>,
      %<SLibGetNullDefinitionFromTfl()>,
      {rt_LoggedStateBlockNames},
      {rt_LoggedStateNames},
      rt_LoggedStateCrossMdlRef,
      rt_RTWLogDataTypeConvert
    };
  %endif %% bEmitInit
    
  %if bEmitReg
    %if UsingMalloc
      void **rt_LoggedStateSignalPtrs = ...
        (void **)malloc(sizeof(void *) * %<numLoggedStates>);
    %else
      static void * rt_LoggedStateSignalPtrs[%<numLoggedStates>];
    %endif
  %endif
   
  %if bEmitReg
    %if UsingMalloc
      %<RTMChkMemAndReturnIfErr("rt_LoggedStateSignalPtrs")>;
    %endif
    %<RTMLoggingSet("LogXSignalPtrs", ...
      "(LogSignalPtrsType) rt_LoggedStateSignalPtrs")>
  %endif %% bEmitReg
   
  %if bEmitInit
    %<RTMLoggingSet("LogXSignalInfo", "&rt_LoggedStateSignalInfo")>
    %<sigPtrsStr>/
  %endif
  }
%endfunction %% FcnLogStateSetup
 
 
%%Function:FcnDisableOutputLogging===========================================
%%Abstract:
%function FcnDisableOutputLogging(dlo) void
  %assign dlo.OutputSaveName = ""
  %return
%endfunction
 
%%Function:FcnIsOutputLoggingEnabled=========================================
%%Abstract:
%function FcnIsOutputLoggingEnabled(dlo) void
  %return (dlo.OutputSaveName != "")
%endfunction
 
%%Function:LibGetRecordPreprocessingFcnPtr=================================================
%%Abstract:
%%Forarecord,returnthepreprocessingfcnptrvalueifitexists
%%returnsnullforrecordswithoutapreprocessingfunctionnamed
%%
%function LibGetRecordPreprocessingFcnPtr(record) void
  %assign returnString = "%<SLibGetNullDefinitionFromTfl()>"
  %if !ISEMPTY(record) && ISFIELD(record, "PreprocessingFcnPtr") ...
    && record.PreprocessingFcnPtr != ""
    %assign returnString = "&" + record.PreprocessingFcnPtr
  %endif
  %return returnString
%endfunction
 
%%Function:ExtOutUnLoggable==================================================
%%Abstract:
%%Isexternaloutputloggable?
%function FcnExtOutLoggable(extOut) void
  %assign sysIdx = extOut.Block[0]
  %assign blkIdx = extOut.Block[1]
  %assign outportBlock = System[sysIdx].Block[blkIdx]
  %with outportBlock
    %assign dTypeId = LibGetDataTypeIdAliasedThruToFromId(...
      LibBlockInputSignalDataTypeId(0))
  %endwith
  %return LibIsDataTypeLogSupported(dTypeId, TLC_FALSE) && ...
    !(ISFIELD(extOut, "UseAccessFunctions") && extOut.UseAccessFunctions == 1) && ...
    !(ISFIELD(extOut, "IsMessage") && extOut.IsMessage == 1)
%endfunction
 
%%Function:FcnLogOutputSetup=================================================
%%Abstract:
%%Setupoutputsforstructurelogging
%%
%%TopTester:test/toolbox/simulink/variants/string/tStringSupport.m
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/tStringSupport.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmSrcAZVCLoggingCheck_VC1.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants3.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSink/tmVarSinkRateTransBlk_VC1.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmMatlabFcnBlkFcnCall_VC1.m
 
%function FcnLogOutputSetup(bEmitReg, bEmitInit, dlo) Output
   
  %%
  %assign typeQ = "static "
  %assign nOutportBlks = ExternalOutputs.NumExternalOutputs
  %assign comma = ","
  %assign sigPtrsStr = ""
  %assign nOutputsLogged = 0
  %assign allVariantCondition = ""
  %assign isAnyOutportUnconditional = TLC_FALSE
  %assign nLoggableOutports = 0
 
  %% If configured for Conditional MAT File Logging,
  %% we need a separate index variable to index the
  %% output ports when generating Malloc or MultiInstance ERT code
   
  %if (IsConfiguredForConditionalMATFileCode())
    %assign indexInit = "int_T index = 0;"
    %assign indexUpdate = "index = index + 1;"
    %assign replaceIdx = TLC_TRUE
  %else
    %assign indexInit = ""
    %assign indexUpdate = ""
    %assign replaceIdx = TLC_FALSE
  %endif
 
 
  %%Precheck the number of loggable outports.
  %%This is needed to determine where to place the comma
 
  %foreach idx = nOutportBlks
    %assign extOut = ExternalOutputs.ExternalOutput[idx]
    %if FcnExtOutLoggable(extOut)
      %assign nLoggableOutports = nLoggableOutports + 1
    %endif
  %endforeach
 
  %if (nLoggableOutports == 1 && nOutportBlks == 1)
      %assign comma = ""
      %assign indexUpdate = ""
  %endif
   
  %% We write out vector of all unique variant conditions including any
  %% simplified net variant conditions as a vector: CGVCEList to the model rtw
  %% file. Each output also writes out its variant condition in the form of an index
  %% into this vector: LocalCGVCEIdx.
   
  %% TopTester: matlab/test/toolbox/simulink/variants/inlineVariants/variantSource/tg1272884.m
  %if ISFIELD(VariantConditions, "CGVCEList")
    %assign cgvceList = VariantConditions.CGVCEList
  %else
    %assign cgvceList = ""
  %endif
   
  %foreach idx = nOutportBlks
    %assign extOut = ExternalOutputs.ExternalOutput[idx]
    %assign sysIdx = extOut.Block[0]
    %assign blkIdx = extOut.Block[1]
    %assign outportBlock = System[sysIdx].Block[blkIdx]
    %if ISFIELD(extOut, "LocalCGVCEIdx") && (extOut.LocalCGVCEIdx != -1)
     %assign variantCondition = cgvceList[extOut.LocalCGVCEIdx]
    %else
     %assign variantCondition = ""
    %endif
    %assign ifCond = ""
    %assign ifEndCond = ""
    %if ISFIELD(outportBlock, "Inactive")
        %continue
    %endif
    %%
    %with outportBlock
      %assign dTypeId = LibGetDataTypeIdAliasedThruToFromId(...
    LibBlockInputSignalDataTypeId(0))
      %if !FcnExtOutLoggable(extOut)
        %% Signal cannot be logged
        %% ==> Initialize data pointer to NULL so that the logging
        %% infrastructure knows to skip this signal.
        %% ==> Lower down in this function we will skip adding info
        %% for this signal to the other logging structures.
    %assign sigAddr = SLibGetNullDefinitionFromTfl()
        %assign dTypeName = LibGetDataTypeNameFromId(dTypeId)
        %if (ISFIELD(extOut, "UseAccessFunctions") && extOut.UseAccessFunctions == 1)
          %assign warnTxt = "Unable to log signal driving this block " ...
            "because MAT-File logging is not supported for " ...
            "Access Functions."
        %elseif (ISFIELD(extOut, "IsMessage") && extOut.IsMessage == 1)
          %assign warnTxt = "Unable to log signal driving this block " ...
            "because MAT-File logging is not supported for external message outputs."
        %else
          %assign warnTxt = "Unable to log signal driving this block " ...
            "because MAT-File logging is not supported for " ...
            "data type '%<dTypeName>'."
        %endif
        %if !isRAccel
          %<LibBlockReportWarning(outportBlock, warnTxt)>
        %else
          %% all built-in datatypes are supported by dataset logging
          %if !(::CompiledModel.DataLoggingOpts.CompiledLoggingSaveFormat == "Dataset")
            %assign blockName = LibGetFormattedBlockPath(outportBlock)
            %assign warnArgs = ["%<blockName>", "%<dTypeName>"]
            %<SLibReportWarningWithIdAndArgs("RTW:tlc:RapidAcceleratorUnsupportedLoggingFormat", ...
              warnArgs)>
          %endif
        %endif
      %else
        %assign width = LibGetRecordSymbolicWidth(extOut)
        %if extOut.StorageClass == "Auto" && !SLibIsLegacyStorageClassForDataRecord(extOut)
          %assign sigLoc = LibBlockDstSignalLocation("outportblk","","",0)
          %assign sigAddr = "&%<sigLoc>"
          %assign groupIdx = SLibGetCoderGroupIdForDataRecord(extOut)
          %if (SLibIsCoderGroupInVolatileMemory(groupIdx))
              %assign dtName = LibGetRecordIsComplex(extOut) ? LibGetDataTypeComplexNameFromId(dTypeId) : LibGetDataTypeNameFromId(dTypeId)
              %assign cast = "(%<dtName> *)"
              %assign sigAddr = cast + sigAddr
          %endif
        %elseif (extOut.StorageClass == "Custom" || SLibIsLegacyStorageClassForDataRecord(extOut))
          %if !LibCustomDataIsAddressable(extOut)
            %assign sigAddr = SLibGetNullDefinitionFromTfl()
            %assign warnTxt = "Unable to log signal driving this block" + ...
                              " because the custom storage class is not addressable."
            %<LibBlockReportWarning(outportBlock, warnTxt)>
          %else
            %assign sigAddr = SLibCG_EO_CSCAddr(idx, width, "", -1, "", 0)
          %endif
        %elseif extOut.StorageClass == "ImportedExternPointer"
          %% This is due to C language limitation. We cannot initialize
          %% rt_LoggedOutputSignalPtrs with the pointer. This will produce
          %% "Initializer element is not constant" error
          %assign sigAddr = SLibGetNullDefinitionFromTfl()
          %assign warnTxt = "Unable to log signal driving this block" + ...
                            " because of unsupported storage class ImportedExternPointer."
          %<LibBlockReportWarning(outportBlock, warnTxt)>
        %else
          %assign varName = LibGetRecordIdentifier(extOut)
          %if width != "1"
            %assign varName = varName+"[0]"
          %endif
          %assign sigAddr = "&%<varName>"
        %endif
        %assign nOutputsLogged = nOutputsLogged+1
        %if !ISEMPTY(variantCondition)
          %assign ifCond = SLibIfVariantConditionForm(variantCondition)
          %assign ifEndCond = SLibEndIfVariantConditionForm(variantCondition)
        %else
          %assign isAnyOutportUnconditional = TLC_TRUE
        %endif
      %endif
    %endwith %% outportBlock
    %%
    %if UsingMalloc || MultiInstanceERTCode
      %if UsingMalloc
        %assign lhs_eq = "((void **) %<RTMLoggingGet("LogYSignalPtrs")>)[%<idx>] = "
        %if replaceIdx
         %assign lhs_eq = "((void **) %<RTMLoggingGet("LogYSignalPtrs")>)[index] = "
        %endif
      %else
        %assign lhs_eq = "rt_LoggedOutputSignalPtrs[%<idx>] = "
        %if replaceIdx
         %assign lhs_eq = "rt_LoggedOutputSignalPtrs[index] = "
      %endif
      %endif
      %assign sigPtrsStr = sigPtrsStr + "/n" + indexInit + ifCond + "/n" + lhs_eq + sigAddr + ";/n" + indexUpdate + ifEndCond
      %assign indexInit = ""
    %else
      %if(sigAddr == SLibGetNullDefinitionFromTfl() && IsConfiguredForConditionalMATFileCode())
        %%SIGADDR can be NULL only when the data type is not supported for logging.
        %continue
      %else
        %assign sigPtrsStr = sigPtrsStr + "/n" + ifCond + "/n" + sigAddr + comma + "/n" + ifEndCond
    %endif
    %endif
    %if (nOutportBlks == nOutputsLogged + 1)
      %assign comma = ""
      %assign indexUpdate = ""
    %endif
  %endforeach
   
  %if (nLoggableOutports == 0)
    %<FcnDisableOutputLogging(dlo)>
    %return
  %endif
 
  %% Get the system code-generation variant condition which corresponds to the OR
  %% of all individual logged outport conditions.
  %if !ISEMPTY(cgvceList) && ISFIELD(ExternalOutputs,"SystemCGVCEIdx") && (ExternalOutputs.SystemCGVCEIdx != -1)
    %assign allVariantCondition = cgvceList[ExternalOutputs.SystemCGVCEIdx]
  %endif
   
  %assign allIfCond = SLibIfVariantConditionForm(allVariantCondition)
  %assign allIfEndCond = SLibEndIfVariantConditionForm(allVariantCondition)
  %if (!isAnyOutportUnconditional)
      %<allIfCond>
  %endif
    
  {
    %if UsingMalloc
      %if bEmitReg
      void **rt_LoggedOutputSignalPtrs = (void **)malloc(%<nOutportBlks>*sizeof(void*));
 
      %<RTMChkMemAndReturnIfErr("rt_LoggedOutputSignalPtrs")>;
      %endif %% bEmitReg
 
      %if bEmitInit
      %<sigPtrsStr>/
      %endif %% bEmitInit
    %elseif MultiInstanceERTCode
      %if bEmitReg
      static void * rt_LoggedOutputSignalPtrs[%<nOutportBlks>];
      %endif %% bEmitReg
 
      %if bEmitInit
      %<sigPtrsStr>
      %endif %% bEmitInit
    %else
      %if bEmitReg && bEmitInit
      static void * rt_LoggedOutputSignalPtrs[] = /
      {/
    %<sigPtrsStr>
      };
      %else
        %% All legacy cases intertwine malloc and init
        %assert 0
      %endif %% bEmitReg && bEmitInit
    %endif
 
    %if !ISEMPTY(sigPtrsStr) && !WHITE_SPACE(sigPtrsStr)
      %assign groupId = SLibGetCoderGroupIdForDataRecord(extOut)
      %if (groupId >= 0)
        %assign group = ::CompiledModel.CoderDataGroup[groupId]
        %assign groupArgDefFieldName = "CoderDataGroup" + group.Name + "ArgDef"
        %assign groupArgDef = rootSystem.Interface.%<groupArgDefFieldName>
        %<SLibAccessArgHelper(groupArgDef, "", rootSystem.CurrentTID)>
      %endif
    %endif
     
    %if bEmitReg
    %<RTMLoggingSet("LogYSignalPtrs", ...
      "((LogSignalPtrsType)rt_LoggedOutputSignalPtrs)")>
    %endif %% bEmitReg
  }
  %assign cr = ""
  %assign qt = "/""
  %assign comma = ""
  %assign newcomma = ","
  %assign widthStr = ""
  %assign numDimsStr = ""
  %assign dimsStr = ""
  %assign isVarDimsStr = ""
  %assign currSigDimsStr = ""
  %assign currSigDimsInitStr = ""
  %assign currSigDimsSetStr = ""
  %assign currSigDimsSizeStr = ""
  %assign dTypeStr = ""
  %assign cmplxStr = ""
  %assign preprocessingFcnPtrsStr = ""
  %assign labelStr = ""
  %assign labelLenStr = ""
  %assign blkNameStr = ""
  %assign blkNameLenStr= ""
  %assign logSigInfoInitStr = ""
  %assign logSigInfoVarsStr = ""
  %%
  %assign dataTypeConvertInitStr = ""
  %%
  %assign widthVar = "rt_LoggedOutputWidths"
  %assign numDimsVar = "rt_LoggedOutputNumDimensions"
  %assign dimsVar = "rt_LoggedOutputDimensions"
  %assign isVarDimsVar = "rt_LoggedOutputIsVarDims"
  %assign currSigDimsVar = "rt_LoggedCurrentSignalDimensions"
  %assign currSigDimsSizeVar = "rt_LoggedCurrentSignalDimensionsSize"
  %assign dTypeVar = "rt_LoggedOutputDataTypeIds"
  %assign cmplxVar = "rt_LoggedOutputComplexSignals"
  %assign preprocessingFcnPtrsVar = "rt_LoggingPreprocessingFcnPtrs"
  %assign labelVar = "rt_LoggedOutputLabels"
  %assign labelLenVar = "rt_LoggedOutputLabelLengths"
  %assign blkNameVar = "rt_LoggedOutputBlockNames"
  %assign blkNameLenVar = "rt_LoggedOutputBlockNameLengths"
  %assign rt_RTWLogDataTypeConvertVar = "rt_RTWLogDataTypeConvert"
  %%
  %assign nSignalInfos = 0
  %if bEmitInit
{
  %endif %% bEmitInit
  %assign numDimsRunningCount = 0
  %assign numOutportsLoggedIdx = 0
  %assign numCurrSigDims = 0
  %assign currSigDimsSize = ConfigSet.TargetBitPerInt/8
  %%
  %foreach idx = nOutportBlks
    %assign extOut = ExternalOutputs.ExternalOutput[idx]
    %assign sysIdx = extOut.Block[0]
    %assign blkIdx = extOut.Block[1]
    %assign outportBlock = System[sysIdx].Block[blkIdx]
    %if ISFIELD(extOut, "LocalCGVCEIdx") && (extOut.LocalCGVCEIdx != -1)
     %assign variantCondition = cgvceList[extOut.LocalCGVCEIdx]
    %else
     %assign variantCondition = ""
    %endif
 
    %assign ifCond = ""
    %assign ifEndCond = ""
    %if ISFIELD(outportBlock, "Inactive")
        %continue
    %endif
    %if !ISEMPTY(variantCondition)
       %assign ifCond = SLibIfVariantConditionForm(variantCondition)
       %assign ifEndCond = SLibEndIfVariantConditionForm(variantCondition)
    %endif
      
    %%
    %with System[sysIdx]
      %with outportBlock
        %assign dTypeId = LibGetDataTypeIdAliasedThruToFromId(...
          LibBlockInputSignalDataTypeId(0))
        %%
        %if !FcnExtOutLoggable(extOut)
      %% Cannot log signals that don't have data type convert
           %% between functions
        %continue
        %endif
        %assign width = LibBlockInputSignalSymbolicWidth(0)
        %assign numDims = LibBlockInputSignalNumDimensions(0)
        %assign dims = LibBlockInputSignalSymbolicDimensions(0)
        %assign preprocessingFcnPtrs = LibGetRecordPreprocessingFcnPtr(extOut)
        %assign isVarDims = ISFIELD(extOut, "HasVarDims")
        %assign cmpxSig = LibBlockInputSignalIsComplex(0)
        %assign label = extOut.SigLabel
        %assign blkName = LibGetBlockPath(outportBlock)
        %%
        %assign dtConvertParams = InitLogDataTypeConvertStructure(dTypeId)
        %%
      %endwith %% outportBlock
    %endwith %% System[sysIdx]
    %%
    %% count the signals that are actually handled
    %%
    %assign nSignalInfos = nSignalInfos + 1
    %%
    %assign widthStr = widthStr + comma + cr + width
    %assign numDimsStr = numDimsStr + comma + cr + "%<numDims>"
    %assign dimsStr = dimsStr + comma + cr
    %assign preprocessingFcnPtrsStr = preprocessingFcnPtrsStr + comma + cr + "%<preprocessingFcnPtrs>"
    %assign currSigDimsInitStr = currSigDimsInitStr + comma + cr
    %assign currSigDimsSizeStr = currSigDimsSizeStr + comma + cr
     
    %foreach dimsIdx = numDims
      %assign dimsStr = dimsStr + "%"
      %assign currSigDimsInitStr = currSigDimsInitStr + SLibGetNullDefinitionFromTfl()
      %if isVarDims
        %with System[sysIdx]
          %with outportBlock
            %assign currSigDims = SLibGetOutportSize(idx, numDims, "", -1, "", dimsIdx)
          %endwith %% outportBlock
        %endwith %% System[sysIdx]
        %assign currSigDimsStr = currSigDimsStr + "&%<currSigDims>"
        %assign currSigDimsSizeStr = currSigDimsSizeStr + "%<currSigDimsSize>"
      %else
        %assign currSigDims = widthVar
        %assign currSigDimsStr = currSigDimsStr + ...
                                               "&%<currSigDims>[%]"
        %assign currSigDimsSizeStr = currSigDimsSizeStr + "%<currSigDimsSize>"
      %endif
       
      %if dimsIdx != numDims-1
        %assign dimsStr = dimsStr + ", "
        %assign currSigDimsInitStr = currSigDimsInitStr + ", "
        %assign currSigDimsSizeStr = currSigDimsSizeStr + ", "
      %endif
       
      %assign currSigDimsStr = "%<currSigDimsVar>[%<numCurrSigDims>] " + ...
                  "= %<currSigDimsStr>; /n"
      %assign currSigDimsSetStr = currSigDimsSetStr + currSigDimsStr
      %assign currSigDimsStr = ""
     
      %assign numCurrSigDims = numCurrSigDims + 1
    %endforeach
     
    %assign isVarDimsStr = isVarDimsStr + comma + cr + "%<isVarDims>"
    %assign dTypeStr = dTypeStr + comma + cr + "%"
    %assign cmplxStr = cmplxStr + comma + cr + "%<cmpxSig>"
    %%
    %assign dataTypeConvertInitStr = dataTypeConvertInitStr + comma + cr + ...
      "{ %, %, %," + ...
      " %, %, %," + ...
      " %, %, %}"
    %%
    %assign labelStr = labelStr + comma + cr + qt + STRING(label) + qt
    %assign blkNameStr = blkNameStr + comma + cr + qt + STRING(blkName) + qt
    %%
    %if dlo.NumOutputSaveNames != 1
      %if nSignalInfos == 1
        %assign pointerMathAddition = ""
        %assign pointerMathAdditionDims = ""
      %else
        %assign pointerMathAddition = "+%<numOutportsLoggedIdx>"
        %assign pointerMathAdditionDims = "+%<numDimsRunningCount>"
      %endif
      %assign numOutportsLoggedIdx = numOutportsLoggedIdx + 1
      %assign numDimsRunningCount = numDimsRunningCount + numDims
      %%
      %openfile tempBuffer
      %<typeQ> const char_T *%<labelVar>_%<idx>[] = {"%<STRING(label)>"};
      %<typeQ> const char_T *%<blkNameVar>_%<idx>[] = {"%<STRING(blkName)>"};
     
      %closefile tempBuffer
      %assign logSigInfoVarsStr = logSigInfoVarsStr + tempBuffer
       
      %openfile tempBuffer
        {
          1,
          %<widthVar>%<pointerMathAddition>,
          %<numDimsVar>%<pointerMathAddition>,
          %<dimsVar>%<pointerMathAdditionDims>,
          %<isVarDimsVar>%<pointerMathAddition>,
          %<currSigDimsVar>%<pointerMathAdditionDims>,
          %<currSigDimsSizeVar>%<pointerMathAdditionDims>,
          %<dTypeVar>%<pointerMathAddition>,
          %<cmplxVar>%<pointerMathAddition>,
          %<SLibGetNullDefinitionFromTfl()>,
          %<preprocessingFcnPtrsVar>%<pointerMathAddition>,
      {%<labelVar>_%<idx>},
          %<SLibGetNullDefinitionFromTfl()>,
          %<SLibGetNullDefinitionFromTfl()>,
          %<SLibGetNullDefinitionFromTfl()>,
      {%<blkNameVar>_%<idx>},
          {%<SLibGetNullDefinitionFromTfl()>},
      %<SLibGetNullDefinitionFromTfl()>,
          %<rt_RTWLogDataTypeConvertVar>%<pointerMathAddition>
        }/
      %closefile tempBuffer
      %%
      %assign logSigInfoInitStr = logSigInfoInitStr + "/n" + ifCond + tempBuffer + newcomma + ifEndCond
      %if (nSignalInfos + 1 == nLoggableOutports)
      %assign newcomma = ""
      %endif
      %%
    %endif
    %%
    %assign comma = ","
    %assign cr = "/n"
    %%
  %endforeach
  %%
  %if bEmitInit
  %if nSignalInfos > 0
 
    %<typeQ> int_T %<widthVar>[] =/
    {
      %<widthStr>
    };
 
    %<typeQ> int_T %<numDimsVar>[] =/
    {
      %<numDimsStr>
    };
 
    %<typeQ> int_T %<dimsVar>[] =/
    {
      %<dimsStr>
    };
 
    %<typeQ> boolean_T %<isVarDimsVar>[] =/
    {
      %<isVarDimsStr>
    };
     
    %<typeQ> void* %<currSigDimsVar>[] =/
    {
      %<currSigDimsInitStr>
    };
    
    %<typeQ> int_T %<currSigDimsSizeVar>[] =/
    {
      %<currSigDimsSizeStr>
    };
 
    %<typeQ> BuiltInDTypeId %<dTypeVar>[] =/
    {
      %<dTypeStr>
    };
 
    %<typeQ> int_T %<cmplxVar>[] =/
    {
      %<cmplxStr>
    };
     
    %<typeQ> RTWPreprocessingFcnPtr %<preprocessingFcnPtrsVar>[] =/
    {
      %<preprocessingFcnPtrsStr>
    };
 
    %if dlo.NumOutputSaveNames == 1
       
      %<typeQ> const char_T *%<labelVar>[] = {
        %<labelStr>};
       
      %<typeQ> const char_T *%<blkNameVar>[] = {
        %<blkNameStr>};
 
    %else
    %<logSigInfoVarsStr>
    %endif
 
    %<typeQ> RTWLogDataTypeConvert %<rt_RTWLogDataTypeConvertVar>[] =/
    {
      %<dataTypeConvertInitStr>
    };
 
  %else
    %assign widthVar = SLibGetNullDefinitionFromTfl()
    %assign numDimsVar = SLibGetNullDefinitionFromTfl()
    %assign dimsVar = SLibGetNullDefinitionFromTfl()
    %assign isVarDimsVar = SLibGetNullDefinitionFromTfl()
    %assign currSigDimsVar = SLibGetNullDefinitionFromTfl()
    %assign currSigDimsSizeVar = SLibGetNullDefinitionFromTfl()
    %assign dTypeVar = SLibGetNullDefinitionFromTfl()
    %assign cmplxVar = SLibGetNullDefinitionFromTfl()
    %assign preprocessingFcnPtrsVar = SLibGetNullDefinitionFromTfl()
    %assign labelVar = SLibGetNullDefinitionFromTfl()
    %assign labelLenVar = SLibGetNullDefinitionFromTfl()
    %assign blkNameVar = SLibGetNullDefinitionFromTfl()
    %assign blkNameLenVar = SLibGetNullDefinitionFromTfl()
    %assign rt_RTWLogDataTypeConvertVar = SLibGetNullDefinitionFromTfl()
  %endif
 
  %if dlo.NumOutputSaveNames == 1
    %assign numberOfSignalInfosInEachStruct = nSignalInfos
  %else
    %assign numberOfSignalInfosInEachStruct = 1
  %endif
 
  %<typeQ> RTWLogSignalInfo rt_LoggedOutputSignalInfo[] =/
  {
    %if dlo.NumOutputSaveNames == 1
      %% Single output name
      {
        %<nSignalInfos>,
    %<widthVar>,
    %<numDimsVar>,
    %<dimsVar>,
        %<isVarDimsVar>,
        %<currSigDimsVar>,
        %<currSigDimsSizeVar>,
    %<dTypeVar>,
    %<cmplxVar>,
    %<SLibGetNullDefinitionFromTfl()>,
        %<preprocessingFcnPtrsVar>,
    {%<labelVar>},
    %<SLibGetNullDefinitionFromTfl()>,
    %<SLibGetNullDefinitionFromTfl()>,
    %<SLibGetNullDefinitionFromTfl()>,
    {%<blkNameVar>},
        {%<SLibGetNullDefinitionFromTfl()>},
    %<SLibGetNullDefinitionFromTfl()>,
        %<rt_RTWLogDataTypeConvertVar>
      }
    %else
      %% Multiple output names
      %<logSigInfoInitStr>
    %endif
  };
  %endif %% bEmitInit
   
  %if bEmitInit
  %<RTMLoggingSet("LogYSignalInfo", "rt_LoggedOutputSignalInfo")>
  /* set currSigDims field */
  %<currSigDimsSetStr>
}
  %endif %% bEmitInit
 
%if (!isAnyOutportUnconditional)
      %<allIfEndCond>
%endif
 
   
 
 
%endfunction %% FcnLogOutputSetup
 
 
%%Function:SLibDumpModelRegDataLoggingSetup==================================
%%Abstract:
%%WritesthestatementsneedtoinitializeforMATfiledatalogging.
%%Note,wealwaysdothisevenifMATfiledataloggingisturned
%%offintheeventthatanotherformofdataloggingexistswhich
%%needstomakeuseofthisinformation.
%%
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortEnable.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSink/tmVarSinkRateTransBlk_VC1.m
%%toptester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmSrcAZVCLoggingCheck_VC1.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants10.m
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/tStringSupport.m
%%TopTester:test/toolbox/simulink/blocks/lib_MathOperations/Gain/rtw/tNumerics_Gainblk_blas.m
%%TopTester:test/toolbox/simulink/variants/variantBus/vss/tVSSVariantBusGecks.m
%%
%function SLibDumpModelRegDataLoggingSetup(bEmitReg, bEmitInit) Output
  %assert(!IsModelReferenceTarget())
   
  %if bEmitReg
  /* Setup for data logging */
  {
    %if UsingMalloc
      RTWLogInfo *rt_DataLoggingInfo = ...
    (RTWLogInfo *) malloc(sizeof(RTWLogInfo));
      %<RTMChkMemAndReturnIfErr("rt_DataLoggingInfo")>;
      rt_DataLoggingInfo->loggingInterval = NULL;
    %else
      static RTWLogInfo rt_DataLoggingInfo;
      rt_DataLoggingInfo.loggingInterval = NULL;
    %endif
 
    %assign amps = UsingMalloc ? "" : "&"
    %<RTMLoggingSet("RTWLogInfo", "%<amps>rt_DataLoggingInfo")>
  }
  %endif %% bEmitReg
 
 
  /* Setup for data logging */
  {
    %assign dlo = ::CompiledModel.DataLoggingOpts
 
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% Setup for Data being logged as "state". This includes continuous and %%
    %% discretes states which live in the dwork vector. %%
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %assign needsMMI = 0
    %if FcnIsStateLoggingEnabled(dlo) || ::isRAccel
      /*
       * Set pointers to the data and signal info each state
       */
       %if ::CompiledModel.RTWStatesLogging == 0
        %<FcnLogStateSetup(bEmitReg, bEmitInit, dlo)>/
      %else
        %% If we're using the CAPI then everything is setup in the
        %% startDataLogging call
    %% Need to set the pointer to the mmi in the RTWLogInfo
        %assign needsMMI = 1
      %endif
    %else
      %if bEmitReg
      %<RTMLoggingSet("LogXSignalInfo", SLibGetNullDefinitionFromTfl())>
      %<RTMLoggingSet("LogXSignalPtrs", SLibGetNullDefinitionFromTfl())>
      %endif %% bEmitReg
    %endif %% Logging state
 
    %if bEmitInit
    %%
    %% Logging names and other attributes (format, max rows, etc.)
    %%
    %% *** NOTE ***
    %% Names must be set AFTER setting up state logging because if none of
    %% the states can be logged then the save names will be cleared
    %% ************
    %%
    %<RTMLoggingSet("LogT", "/"%<dlo.TimeSaveName>/"")>
    %<RTMLoggingSet("LogX", "/"%<dlo.StateSaveName>/"")>
    %<RTMLoggingSet("LogXFinal", "/"%<dlo.FinalStateName>/"")>
    %% add dlo.SigLogSaveName
    %<RTMLoggingSet("LogVarNameModifier", "/"%<LogVarNameModifier>/"")>
    %<RTMLoggingSet("LogFormat", dlo.SaveFormat)>
    %<RTMLoggingSet("LogMaxRows", dlo.MaxRows)>
    %<RTMLoggingSet("LogDecimation", dlo.Decimation)>
 
    %% Set the pointer to the mmi in the RTWLogInfo
    %if needsMMI
          %if isRSim && !IsModelReferenceTarget()
      %<RTMLoggingSet("MMI", "&(%<RSimRTWCAPIVarPtr>->mmi)")>
    %else
      %<RTMLoggingSet("MMI", "&(%<RTMGet("DataMapInfo")>.mmi)")>
    %endif
    %endif
    %endif %% bEmitInit
     
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% Setup for logging outputs %%
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %%
    %% NOTE:
    %% FcnLogOutputSetup will disable output logging if no outputs can be logged
    %% so we need to call this before setting up the logging structures.
    %if FcnIsOutputLoggingEnabled(dlo)
      /*
       * Set pointers to the data and signal info for each output
       */
      %<FcnLogOutputSetup(bEmitReg, bEmitInit, dlo)>/
    %endif
       
    %% ANSI C compiler option restricts string length to 509 characters
    %% Hence, we need to special case for the case of malloc/Multi instance ert and normal code gen
    %% when the string length is more than 509
    %if bEmitInit
       %assign maxLength = 509
        %assign nOutportBlks = ExternalOutputs.NumExternalOutputs
        %assign isConditionalLogCodeNeeded = IsConfiguredForConditionalMATFileCode()
 
        %if (isConditionalLogCodeNeeded == TLC_TRUE)
         /*
          * Create conditional output log variable
          */
         {
         %if UsingMalloc
          %if (SIZE(dlo.OutputSaveName,1) <= maxLength)
            static char_T *rt_LogVarNames;
            rt_LogVarNames = malloc(sizeof(char_T)*sizeof("%<dlo.OutputSaveName>,"));
          %else
            %assign len = SIZE(dlo.OutputSaveName,1)
            static char_T *rt_LogVarNames;
            rt_LogVarNames = malloc(sizeof(char_T)*%);
          %endif
         %else
          %if (SIZE(dlo.OutputSaveName,1) <= maxLength)
           static char_T rt_LogVarNames[sizeof("%<dlo.OutputSaveName>,")];
          %else
           %assign len = SIZE(dlo.OutputSaveName,1)
           static char_T rt_LogVarNames[%];
          %endif
         %endif
          %% TopTester: test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tVariantSource3.m -testspec:g1302923
          %% We use memset from the string.h library when we perform conditional MAT File logging
          %% However, some optimizations like 'Remove internal data initialization' etc result in non-addition
          %% of 'string.h' library and hence lead to build warnings stating that memset is used without
          %% the string.h library .
          %% The fix is to make sure that whenever we perform a conditional logging, we call the 'LibGenMemFcnCall'
          %% function, that ensures that the necessary headers are added for conditional logging.
 
          %assign condLoggingLibInclCall = LibGenMemFcnCall("memset", "rt_LogVarNames"," '//0'", "sizeof(rt_LogVarNames)")
 
          %% the condLoggingLibInclCall expression would have the expression
          %% 'memset(rt_LogVarNames, '/0',
          %% sizeof(rt_LogVarNames))
          %% We can use this expression instead of the expression below, but note that this will force
          %% us to update all the inlinevariants baselines(notice the new line). Hence, keeping the older call
     
          (void)memset(rt_LogVarNames, '/0',sizeof(rt_LogVarNames));
 
         %% Block[0] is the sysIdx
         %% Block[1] is the blockIdx of the output port
         %% refer rtwgen_extio.cpp
         %foreach idx = nOutportBlks
             %assign extOut = ExternalOutputs.ExternalOutput[idx]
             %assign sysIdx = extOut.Block[0]
             %assign blkIdx = extOut.Block[1]
             %assign outportBlock = System[sysIdx].Block[blkIdx]
             %if !FcnExtOutLoggable(extOut)
               %continue
             %endif
              
             %% Get the table of unique variant conditions.
             %if ISFIELD(VariantConditions, "CGVCEList")
               %assign cgvceList = VariantConditions.CGVCEList
             %else
               %assign cgvceList = ""
             %endif
              
             %% Get the variant condition for each output.
             %if ISFIELD(extOut, "LocalCGVCEIdx") && (extOut.LocalCGVCEIdx != -1)
               %assign variantCondition = cgvceList[extOut.LocalCGVCEIdx]
             %else
               %assign variantCondition = ""
             %endif
     
             %assign outputPortVarName = extOut.OutputSaveNameOnPort
             %assign ifCond = ""
             %assign ifEndCond = ""
             %if ISFIELD(outportBlock, "Inactive")
               %continue
             %else
                %assign ifCond = SLibIfVariantConditionForm(variantCondition)
                %assign ifEndCond = SLibEndIfVariantConditionForm(variantCondition)
                %assign funcCall = "strcat" + "(rt_LogVarNames" + "," + "/"%<outputPortVarName>,/"" + ");"
                %<ifCond>
                   %<funcCall>
                %<ifEndCond>
             %endif
           %endforeach
          
         if (strlen(rt_LogVarNames) > 0) {
             rt_LogVarNames[strlen(rt_LogVarNames) - 1] = '/0';
          }
          %<RTMLoggingSet("LogY", "rt_LogVarNames")>
        }
 
        %elseif ((SIZE(dlo.OutputSaveName,1) <= maxLength) && (isConditionalLogCodeNeeded == TLC_FALSE))
         %<RTMLoggingSet("LogY", "/"%<dlo.OutputSaveName>/"")>
       %else
         %assign len = SIZE(dlo.OutputSaveName,1)
         %assign times = len/maxLength + 1
         {
            static char_T temp_str [%];
     
            %foreach idx = times
              %assign str = ""
              %foreach idx2 = maxLength
                %assign lenSoFar = idx*maxLength + idx2
                %if lenSoFar >= len
                  %break
                %endif
                %assign str = str + dlo.OutputSaveName[lenSoFar]
              %endforeach
              (void) %<LibGenStringFcnCall2Args("strcpy",...
              "&temp_str[%]", "/"%<str>/"")>;
            %endforeach
            %<RTMLoggingSet("LogY", "temp_str")>
          }
       %endif
    %endif %% bEmitInit
 
    %if (FcnIsOutputLoggingEnabled(dlo) == TLC_FALSE)
      %if bEmitReg
      %<RTMLoggingSet("LogYSignalInfo", SLibGetNullDefinitionFromTfl())>
      %<RTMLoggingSet("LogYSignalPtrs", SLibGetNullDefinitionFromTfl())>
      %endif %% bEmitReg
    %endif
  }
 
%endfunction %% SLibDumpModelRegDataLoggingSetup
 
%%Function:SLibInitDataInitialValue========================================
%%Abstract:
%%Thisfunctionwrapsassignmentformultiwordandsignalword.InMultiword,
%%directvalueassignmentisnotallowed.Atempvarwillbecreatedtohold
%%Multiwordvalueandthenassigntempvartothedestinationvariable.
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%
%function SLibInitDataInitialValue(dTypeId, var, val) Output
  %if !ISEMPTY(SLibDataTypeConstructFcnName(dTypeId))
    %% CGIR will generate the initialization code
  %elseif LibIsStructDataType(dTypeId) %% includes LibIsDataTypeMultiWordFixpt
    %assign dTypeName = LibGetDataTypeNameFromId(dTypeId)
    %assign tmpVar = "temp"
    %if !LibIsDataTypeMultiWordFixpt(dTypeId)
      %% Multi-word types are already padded, we need padding only
      %% for struct/bus parameters
      %assign val = "{" + val + "}"
    %endif
    %%multiword and bus case
    {
      %<dTypeName> %<tmpVar> = %<val>;
      %<var> = %<tmpVar>;
    }
  %else
    %%single word case
    %<var> = %<val>;
  %endif
  %return
%endfunction %%SLibInitDataInitialValue
 
%%Function:FcnInitDataElementInitialValue===================================
%%Abstract:
%%Thisfunctionemitsthecodetoinitializeasingleelementofadata
%%vectorusingthepassedinitialvalue.
%%
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmFunctionCallSplitBlock_hidden_VC1.m
%%TopTester:test/toolbox/simulink/blocks/lib_MathOperations/Gain/rtw/tNumerics_Gainblk_blas_misc.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%
%function FcnInitDataElementInitialValue(datarec, storageClass, dTypeId, ...
  symWidth, isComplex, initValue, optionalDeref, dataId, idxExpr, elementIdx) Output
  %%
  %assign vectIdxExpr = SLibGet1DArrayIndexer(symWidth, idxExpr, "", elementIdx)
   
  %switch storageClass
    %case "Auto"
    %case "ExportedGlobal"
    %case "ImportedExtern"
    %case "ImportedExternPointer"
      %%
      %if isComplex
        %if LibIsNonBuiltInTypeNeededForFixpt(dTypeId)
          %assign initRe = FcnGetNonBuiltInRe(initValue[elementIdx])
          %assign initIm = FcnGetNonBuiltInIm(initValue[elementIdx])
        %else
          %assign initRe = REAL(initValue[elementIdx])
          %assign initIm = IMAG(initValue[elementIdx])
        %endif
         
        %assign rval = SLibGetFormattedValue(datarec, initRe)
        %if !SLibRemoveZeroInitForData(datarec, rval)
          %assign var = optionalDeref + STRING(dataId) + vectIdxExpr+ "." +tRealPart
          %<SLibInitDataInitialValue(dTypeId, var, rval)>/
        %endif
        %assign ival = SLibGetFormattedValue(datarec, initIm)
        %if !SLibRemoveZeroInitForData(datarec, ival)
          %assign var = optionalDeref + STRING(dataId) + vectIdxExpr +"." + tImagPart
          %<SLibInitDataInitialValue(dTypeId, var, ival)>/
        %endif
      %else
        %assign val = ""
        %if ISEMPTY(SLibDataTypeConstructFcnName(dTypeId))
          %assign val = SLibGetFormattedValue(datarec, initValue[elementIdx])
        %endif
        %if !SLibRemoveZeroInitForData(datarec, val)
          %assign var = optionalDeref + STRING(dataId) + vectIdxExpr
          %<SLibInitDataInitialValue(dTypeId, var, val)>/
        %endif
      %endif
      %break
      %%
    %case "Custom"
      %%
      %if isComplex
        %if LibIsNonBuiltInTypeNeededForFixpt(dTypeId)
          %assign initRe = FcnGetNonBuiltInRe(initValue[elementIdx])
          %assign initIm = FcnGetNonBuiltInIm(initValue[elementIdx])
        %else
          %assign initRe = REAL(initValue[elementIdx])
          %assign initIm = IMAG(initValue[elementIdx])
        %endif
        %assign rval = SLibGetFormattedValue(datarec, initRe)
        %assign ival = SLibGetFormattedValue(datarec, initIm)
      %else
        %assign val = SLibGetFormattedValue(datarec, initValue[elementIdx])
      %endif
      %if (datarec.CustomStorageClassVersion > 1)
        %% GetSet
        %if isComplex
          %if !SLibRemoveZeroInitForData(datarec, rval)
            %<LibAccessCustomData(datarec,"set",vectIdxExpr,tRealPart,rval)>
          %endif
          %if !SLibRemoveZeroInitForData(datarec, ival)
            %<LibAccessCustomData(datarec,"set",vectIdxExpr,tImagPart,ival)>
          %endif
        %else
          %if !SLibRemoveZeroInitForData(datarec, val)
            %<LibAccessCustomData(datarec,"set",vectIdxExpr,"",val)>
          %endif
        %endif
        %%
      %else
        %% non-GetSet
        %if isComplex
          %if !SLibRemoveZeroInitForData(datarec, rval)
            %assign var = LibCustomData(datarec,"contents",vectIdxExpr,tRealPart)
            %<SLibInitDataInitialValue(dTypeId, var, rval)>/
          %endif
          %if !SLibRemoveZeroInitForData(datarec, ival)
            %assign var = LibCustomData(datarec,"contents",vectIdxExpr,tImagPart)
            %<SLibInitDataInitialValue(dTypeId, var, ival)>/
          %endif
        %else
          %if !SLibRemoveZeroInitForData(datarec, val)
            %assign var = LibCustomData(datarec,"contents",vectIdxExpr,"")
            %<SLibInitDataInitialValue(dTypeId, var, val)>/
          %endif
        %endif
      %endif
      %break
      %%
    %default
      %assert TLC_FALSE
  %endswitch
%endfunction %% FcnInitDataElementInitialValue
 
%%TopTester:test/toolbox/simulink/blocks/tconcat_misc.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%
%function GetInitDataInitialValue(datarec, dataId) void
  %assign storageClass = datarec.StorageClass
  %assign dTypeId = LibGetRecordDataTypeId(datarec)
  %assign symWidth = LibGetRecordSymbolicWidth(datarec)
  %assign isComplex = SLibGetRecordIsComplex(datarec)
  %assign initValue = datarec.InitialValue
  %if ((ISEQUAL(storageClass, "ImportedExternPointer")) && ...
       (ISEQUAL(symWidth, "1")))
    %assign optionalDeref = "*"
  %else
    %assign optionalDeref = ""
  %endif
  %assign retVal = ""
 
  %% The storage class should be ImportedExtern or ImportedExternPointer
  %% only when the source block for the signal is a Model Reference block
  %assert( (! (ISEQUAL(storageClass, "ImportedExtern") ||...
    ISEQUAL(storageClass, "ImportedExternPointer"))) ||...
    ISEQUAL(System[datarec.SigSrc[0]].Block[datarec.SigSrc[2]].Type, "ModelReference"))
 
  %if LibRecordHasSymbolicWidth(datarec)
    %% for symbolic signals, only scalar expansion is allowed. It is impossible
    %% that dataInit == "Static"
    %assert SLibAllValuesMatch(initValue)
    %assign loopCode = SLibEmitForLoopCounterCode(symWidth, "i")
    %openfile retVal
    %<FcnInitDataElementInitialValue(datarec, storageClass, dTypeId, ...
      symWidth, isComplex, initValue, optionalDeref, dataId, "i", 0)>
    %closefile retVal
    %return ["%<retVal>", "%", "%"]
  %elseif %<symWidth> > 1 && %<symWidth> >= RollThreshold && SLibAllValuesMatch(initValue)
    %assign loopCode = SLibEmitForLoopCounterCode(symWidth, "i")
    %openfile retVal
    %<FcnInitDataElementInitialValue(datarec, storageClass, dTypeId, ...
      symWidth, isComplex, initValue, optionalDeref, dataId, "i", 0)>
    %closefile retVal
    %return ["%<retVal>", "%", "%"]
  %else
    %%
    %openfile retVal
    %foreach elementIdx = %<symWidth>
      %<FcnInitDataElementInitialValue(datarec, storageClass, dTypeId, symWidth, ...
        isComplex, initValue, optionalDeref, dataId, "", elementIdx)>
    %endforeach
    %closefile retVal
    %return ["%<retVal>", "", ""]
  %endif
%endfunction
 
%%Function:FcnInitDataInitialValue===========================================
%%Abstract:
%%ThisfunctionemitscodetoinitializedatausingInitialValueindatarec.
%%Itchecksremovezeroinitializationoption.Thedatareccouldbeablock
%%IOorDWork.TheInitialValueindatarecshouldalreadyhaveproperdata
%%type,widthandcomplexitythatmatchtheblockIOorDWork.Thereisno
%%needforusingmemsetonwhichisonlybeconsideredforinternal
%%structureswithdefaultzeroinitialvalues.
%%
%%Note:argumentdataIdisignoredwhendatarec.StorageClassis"Custom"
%%
%%TopTester:test/toolbox/simulink/variants/codevariants/tvss_code_variants.m
%%
%function FcnInitDataInitialValue(datarec, dataId) void
  %assign retVal = ""
  %assign initCode = GetInitDataInitialValue(datarec, dataId)
  %openfile retVal
  %if !ISEMPTY(initCode[1])
    {
      % %% loop index declaration
      % {
        %
      }
    }
  %else
    %
  %endif
  %closefile retVal
  %return retVal
%endfunction %% FcnInitDataInitialValue
 
%%Function:FcnIsImportedScopeCustomStorageCheck==============================
%%Abstract:
%%Returnstrueifagivedatarecordisassociatedwithanimportedscoped
%%customstorageclass.
%%
%function FcnIsImportedScopeCustomStorageCheck(dataRec) void
  %if dataRec.StorageClass == "Custom"
    %assign dataScope = SLibGetDataScope(dataRec.CSCDefn, dataRec)
    %return dataScope == "Imported"
  %endif
  %return TLC_FALSE
%endfunction
 
%%Function:FcnIsFileScopeCustomStorageCheck==================================
%%Abstract:
%%Returnstrueifagivedatarecordisassociatedwithafilescopedcustom
%%storageclass.
%%
%function FcnIsFileScopeCustomStorageCheck(dataRec) void
  %if dataRec.StorageClass == "Custom"
    %assign dataScope = SLibGetDataScope(dataRec.CSCDefn, dataRec)
    %return (dataScope == "File") || ISFIELD(dataRec, "isFileScoped")
  %endif
  %return TLC_FALSE
%endfunction
 
%%Function:FcnIsNotInterfaceableStorageClassCheck============================
%%Abstract:
%%TheERTS-functionsetsitblockfunctiontypeto"Initialize"when
%%itisgeneratingitszerointializationcode.TheERTs-fuctioninitializes
%%allinternalmemorytozeroatstartuptoensureaconsistentsimulation
%%result.Wereportawarningifitattemptstoinializeafilescoped
%%customstorageobject.
%%
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%
%function FcnIsNotInterfaceableStorageClassCheck(dataRec) void
  %% Reset functions with implicit initialization end up here as Output or
  %% OutputUpdate functions. Don't need to check these. g1424398
  %if ::BlockFcn == "Output" || ::BlockFcn == "OutputUpdate"
    %return TLC_FALSE
  %endif
  %assert ::BlockFcn == "Initialize" || ::BlockFcn == "Registration"
  %if ::BlockFcn == "Initialize" && FcnIsFileScopeCustomStorageCheck(dataRec)
    %assert !ZeroInternalMemoryAtStartup
    %assign errTxt = "The auto-generated SIL block will be unable to " ...
      "initialize '%<LibGetRecordIdentifier(dataRec)>' since its storage " ...
      "class prohibits an external interface. This can cause a " ...
      "simulation behaviour mismatch of the SIL block with its " ...
      "source model or subsystem. " ...
      "Please disable the 'Remove internal data zero initialization' " ...
      "option in the Optimization pane of the models Configuration " ...
      "Parameters dialog to addess this warning."
    %<LibReportWarning(errTxt)>
    %return TLC_TRUE
  %endif
  %return TLC_FALSE
%endfunction
 
%%Function:FcnGetNonRootFileFunctionOwner====================================
%%Abstract:
%%Thisfunctionreturnsthenone-inlinedparentsystemindex,ifthe
%%datarecordownergeneratesgeneratescodeintoaseperatefile.
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants2.m
%%
%function FcnGetNonRootFileFunctionOwner(dataRec, sysIdxInitValue) void
  %assign sysIdx = sysIdxInitValue
  %assign csIdx = SLibGetSystemAndCallSideIndex(dataRec)
  %assign fcnSys = System[System[csIdx[0]].NonInlinedParentSystemIdx]
  %%
  %% RTWSystemsCode - 0 ... inlined system
  %% 1 ... function (not reusable)
  %% 2 ... reused function
  %%
  %if (fcnSys.RTWSystemCode == 1 || fcnSys.RTWSystemCode == 2) && ...
    !IsBaseSystem(::CompiledModel.System[fcnSys.FileNameOwnerIdx])
    %assert fcnSys.SystemIdx == System[csIdx[0]].NonInlinedParentSystemIdx
    %assign sysIdx = fcnSys.SystemIdx
  %endif
  %return sysIdx
%endfunction
 
%function FcnShouldSkipDataInitializationForConstant(bo, StorageClass) void
  %% If this is a custom storage class and constant TID, and IR
  %% initialized it, skip making a duplicate initialization
  %if ISFIELD(bo, "TID") && ...
  ISEQUAL(TID, "constant") && ...
  StorageClass != "Auto" && ...
  ISFIELD(bo, "InitInStart") && bo.InitInStart
    %return TLC_TRUE
  %endif
  %return TLC_FALSE
%endfunction
   
%%TopTester:test/toolbox/simulink/variants/vssSigObj/tVSSSigObj.m
%%
%function FcnCacheStandaloneSubsyInitFromTempBuffers(comment) void
  %foreach sysIdx = NumSystems
    %assign sys = System[sysIdx]
    %if LibIsSystemField(sys, "TempInitBuffer")
      %assign stdSSBuffer = LibGetSystemField(sys, "TempInitBuffer")
      %if !ISEMPTY(stdSSBuffer)
        %<LibAddToSystemField(sys, "CachedInitializeDataBody", ...
          "/n" + comment + "/n" + stdSSBuffer + "/n")>
        %% Reset field for next call
        %<LibSetSystemField(sys, "TempInitBuffer", "")>
      %endif
    %endif
  %endforeach
%endfunction
 
%%FunctionFcnInitBlockIOWithExternalStorage==================================
%%Abstract:
%%Helperfunctionforinitializingblocki/o
%%
%%TopTester:test/toolbox/simulink/blocks/tconcat_misc.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tVariantSource4.m
%%TopTester:test/toolbox/simulink/variants/tVariantGecks2.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants2.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmFunctionCallSplitBlock_hidden_VC1.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/simulinkFunction/-tVariantSimulinkFunctionAutoInherit.m
%%Toptetser:test/toolbox/simulink/variants/inlineVariants/variantSink/tmSingleVarSink2_VC1.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/codeGen/localsGuarding/tmLG_forIterator.m
%%
%function FcnInitBlockIOWithExternalStorage(sc, comment, fieldsep, addressof, deref) void
  %%
  %openfile rtnBuffer
  %foreach boIdx = ::CompiledModel.BlockOutputs.NumExternalBlockOutputs
    %assign bo = ::CompiledModel.BlockOutputs.ExternalBlockOutput[boIdx]
    %if SLibOmitRecord(bo) || FcnIsNotInterfaceableStorageClassCheck(bo)
      %continue
    %endif
    %%
    %if !SLibWriteOutInstForSignalRec(bo)
      %continue
    %endif
    %%
    %assign id = LibGetRecordIdentifier(bo)
    %with bo
      %%
      %% Standalone subsystems cache separately
      %assign stdSSIdx = -1
      %assign sysIdx = StandaloneParentSysIdxOfDataRec(bo)
      %if sysIdx == -1 && FcnIsFileScopeCustomStorageCheck(bo)
        %assign sysIdx = FcnGetNonRootFileFunctionOwner(bo, sysIdx)
      %endif
      %assign vcRecord = SLibGetDataInlineVariantNetConditions(bo)
      %assign ifCond = vcRecord.ifCond
      %assign ifEndCond = vcRecord.endIfCond
   
      %if sysIdx != -1
        %assign stdSSIdx = sysIdx
        %assign stdSSBuffer = ""
      %endif
      %if StorageClass != sc
        %%
        %% Skip those records whose StorageClass not as specified in sc
        %%
        %continue
        %%
      %endif
      %assign initCount = LibGetRecordSymbolicWidth(bo)
      %assign isSymbolic = (initCount != "%<LibGetRecordWidth(bo)>")
      %assign dTypeId = LibGetRecordDataTypeId(bo)
      %%
      %% Skip those records whose datatype has a constructor
      %if !ISEMPTY(SLibDataTypeConstructFcnName(dTypeId))
        %continue
      %endif
       
      %if SLibShouldSkipInitForRecord(bo)
        %continue
      %endif
      %%
      %% Ignore initial value of string signals, use ground value instead
      %%
      %% TODO: Remove this and add proper initialization once g1584673
      %% is done
      %if ISEMPTY(InitialValue) || LibIsStringDataType(dTypeId)
        %if (StorageClass == "Custom")
 
          %%
          %% Do not initialize imported custom storage class signals
          %if FcnIsImportedScopeCustomStorageCheck(bo)
            %continue
          %endif
 
          %%
          %% If it's custom storage class without InitialValue,
          %% call "initialize" in its .tlc
          %%
          %% Note that custom storage class .tlc itself should check
          %% remove zero initialization option
          %%
          %openfile initCode
          %% For reusable CSC, if this is at root IO, initialize both auxiliary
          %% buffer and the real buffer; otherwise, just initialize the auxiliary
          %% buffer if it exists
          %if !SLibGetIsReusable(bo) || ...
            SLibHasReusableCSCWithoutReusableBuffer(bo) || ...
            ISFIELD(bo, "IsAtRootInputOrOutput")
           %<SLibEmitLibCustomInitCode(bo, initCount, LibGetRecordIsComplex(bo))>
          %endif
          %if ISFIELD(bo, "ReuseBufferName") && ...
            bo.Identifier != bo.ReuseBufferName
            %assign tempId = bo.Identifier
            %assign bo.Identifier = bo.ReuseBufferName
            %% Need to generate initialization code for the output reuse buffer
            %<SLibEmitLibCustomInitCode(bo, initCount, LibGetRecordIsComplex(bo))>
            %assign bo.Identifier = tempId
          %endif
          %closefile initCode
          %if !WHITE_SPACE(initCode)
            %if stdSSIdx != -1
              %% cache output to tmpBuffer, no %continue until %closefile
              %openfile tmpBuffer
            %endif
            %<ifCond>
            %<initCode>
            %<ifEndCond>
            %if stdSSIdx != -1
              %closefile tmpBuffer
              %assign stdSSBuffer = stdSSBuffer + tmpBuffer
            %endif
          %endif
          %%
        %else %% StorageClass not "Custom"
          %%
          %% For any other external storage without InitialValue,
          %% use its ground value
          %%
          %if SLibRemoveZeroInitForDataDefault(bo)
            %continue
          %endif
          %if stdSSIdx != -1
            %% cache output to tmpBuffer, no %continue until %closefile
            %openfile tmpBuffer
          %endif
          %<ifCond>
          %%
          %% Warning: this will trigger the GroundUsed flag for struct data type
          %assign dataTypeId = LibGetDataTypeIdAliasedThruToFromId(LibGetRecordDataTypeId(bo))
          %if LibIsDataTypeMultiWordFixpt(dataTypeId)
            %assign defaultInitialValue = SLibGetDtGroundName(dataTypeId, ...
              LibGetRecordIsComplex(bo), tRealPart)
          %else
            %assign defaultInitialValue = SLibGetDefaultInitialValue(bo, tRealPart)
          %endif
          %%
          %if initCount == "1"
            %% scalar case
            %if LibGetRecordIsComplex(bo)
              %<id>%<fieldsep>%<tRealPart> = %<defaultInitialValue>;
              %<id>%<fieldsep>%<tImagPart> = %<defaultInitialValue>;
            %else
              %<deref>%<id> = %<defaultInitialValue>;
            %endif
          %elseif isSymbolic || %<initCount> >= RollThreshold
            %% vector case
            %assign loopCode = SLibEmitForLoopCounterCode(initCount, "i")
            {
              %
              % {
                %if LibGetRecordIsComplex(bo)
                  %<id>[i]%<fieldsep>%<tRealPart> = %<defaultInitialValue>;
                  %<id>[i]%<fieldsep>%<tImagPart> = %<defaultInitialValue>;
                %else
                  %<deref>%<id>[i] = %<defaultInitialValue>;
                %endif
              }
            }
          %else
            %% %<initCount> is an integer
            %foreach initIdx = %<initCount>
              %if LibGetRecordIsComplex(bo)
                %<id>[%<initIdx>]%<fieldsep>%<tRealPart> = %<defaultInitialValue>;
                %<id>[%<initIdx>]%<fieldsep>%<tImagPart> = %<defaultInitialValue>;
              %else
                %<deref>%<id>[%<initIdx>] = %<defaultInitialValue>;
              %endif
            %endforeach
          %endif
          %<ifEndCond>
          %if stdSSIdx != -1
            %closefile tmpBuffer
            %assign stdSSBuffer = stdSSBuffer + tmpBuffer
          %endif
        %endif %% StorageClass == "Custom"
        %%
        %% If a non-empty initial value is provided for this signal then
        %% initialize it to that value. Initial values are provided for:
        %%
        %% - signals that have constant sample time but (for various reasons)
        %% could not be declared invariant and placed in the ConstBlockIO
        %% structure
        %%
        %% - or non-imported-storage-class signals that have signal object
        %% InitialValue applied on them
        %%
      %else %% InitialValue not empty
        %if !FcnSkipDataInitialValueInReg(bo)
          %%
          %% For constant sample time signals, we always generate code for
          %% InitialValue regardless of remove zero initialization option.
          %% For non-constant sample time signals, we still check the option
          %%
          %if (Invariant != "yes")
            %if SLibRemoveZeroInitForData(bo, InitialValue)
              %if stdSSIdx != -1 && !WHITE_SPACE(stdSSBuffer)
                %<LibAddToSystemField(System[stdSSIdx],"TempInitBuffer",...
                  stdSSBuffer)>
              %endif
              %continue
            %endif
          %endif
          %%
          %% Do not initialize imported custom storage class signals
          %if FcnIsImportedScopeCustomStorageCheck(bo)
            %continue
          %endif
           
          %if FcnShouldSkipDataInitializationForConstant(bo, StorageClass)
            %continue
          %endif
           
          %if stdSSIdx != -1
            %% cache output to tmpBuffer, no %continue until %closefile
            %openfile tmpBuffer
          %endif
          %assign initCode = GetInitDataInitialValue(bo, id)
          %if !ISEMPTY(initCode[1])
            %<ifCond>
            {
              %
              % {
                %
              }
            }
            %<ifEndCond>
          %else
            %<ifCond>
            %
            %<ifEndCond>
          %endif
          %if stdSSIdx != -1
            %closefile tmpBuffer
            %assign stdSSBuffer = stdSSBuffer + tmpBuffer
          %endif
        %endif
      %endif
      %if stdSSIdx != -1 && !WHITE_SPACE(stdSSBuffer)
        %<LibAddToSystemField(System[stdSSIdx],"TempInitBuffer",...
          stdSSBuffer)>
      %endif
    %endwith
  %endforeach
  %undef stdSSIdx
  %%
  %closefile rtnBuffer
  %% Cache standalone subsystem initialization
  %<FcnCacheStandaloneSubsyInitFromTempBuffers(comment)>
 
  %% Cache root model initialization
  %if !WHITE_SPACE(rtnBuffer)
    %return "/n" + comment + "/n" + rtnBuffer
  %else
    %return ""
  %endif
%endfunction %% FcnInitBlockIOWithExternalStorage
 
%%Function:SLibInitBlockIOWithExternalStorage================================
%%Abstract:
%%Initializetheblocki/owithexternalstorage
%%TopTester:test/toolbox/simulink/variants/vssSigObj/tVSSSigObj.m
%%
%function SLibInitBlockIOWithExternalStorage(usingStatic) Output
  %%
  %% Exported global signals
  %%
  %if !LibExportedGlobalSignalsInstanceIsEmpty()
    %<FcnInitBlockIOWithExternalStorage("ExportedGlobal", ...
      "/* exported global signals */", ".", "&", "")>
  %endif
  %%
  %% Custom signals
  %%
  %if CustomStorageClasses.NumCustomStorageClasses > 0
    %<FcnInitBlockIOWithExternalStorage("Custom", ...
      "/* custom signals */", ".", "&", "")>
  %endif
%endfunction %% SLibInitBlockIOWithExternalStorage
 
%%Function:SLibInitBlockIO===================================================
%%Abstract:
%%Initializetheblocki/ostructure(thosewithinternalstorage)
%%Inthisfunction,wewillcachethestandalonesubsystemblockIO
%%initializationinCachedInitializeDataBody.
%%
%%Ifthereisanystandalonesubsystem,wewillgothroughBlockOutputs
%%twotimes.Inthefirstpass,wewillcachestandalonesubsystem
%%initialization.Inthesecondpass,wewilldumpinitializationforthe
%%restofthesignals.
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants3.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmParameterStructure.m
%%
%function SLibInitBlockIO(ptrBlockIOLabel) Output
  %assign startIdx = -1
  %assign stdSSIdx = -1
  %assign needMemsetToZero = 0
  %if ::CompiledModel.HasStandaloneSubsystem
    %% Find the first signal that belongs to a standalone subsystem
    %foreach boIdx = BlockOutputs.NumGlobalBlockOutputs
      %assign bo = BlockOutputs.GlobalBlockOutput[boIdx]
      %if ISEMPTY(bo.SigSrc)
        %continue
      %endif
      %assign standParent = StandaloneParentSysIdxOfDataRec(bo)
      %if standParent != -1
        %assign startIdx = boIdx
        %assign stdSSIdx = standParent
        %break
      %endif
    %endforeach
 
    %% If any signal belongs to a standalone subsystem, cache its initialization
    %% in CachedInitializeDataBody.
    %if startIdx != -1
      %% We need to go through the BlockOutputs, and cache standalone subsystem
      %% initialization. At most we may have NumSystems-1 subsystems.
      %% SLibInitBlockIOHelper will return two indices indicating
      %% - start index of blockIO in the next standalone
      %% - next standalone subsystem index
      %foreach loopIdx = NumSystems - 1
        %% A break will terminate the loop
        %openfile ssInitBuf
        %assign retVal = SLibInitBlockIOHelper("",startIdx,stdSSIdx)
        %if retVal[2]
            %assign needMemsetToZero = 1
        %endif
        %closefile ssInitBuf
         
        %if !WHITE_SPACE(ssInitBuf)
          %<LibAddToSystemField(System[stdSSIdx],"CachedInitializeDataBody",ssInitBuf)>
        %endif
        %% -1 indicates, we are done and we reached to the end of blockIO
        %if retVal[0] == -1
          %break
        %else
          %% Initialize startIdx and stdSSIdx for the next iteration
          %assign stdSSIdx = retVal[0]
          %assign startIdx = retVal[1]
        %endif
      %endforeach
    %endif
  %endif
   
  %% If there is no root blockIO, then ptrBlockIOLabel will be empty
  %if !ISEMPTY(ptrBlockIOLabel)
    %assign retVal = SLibInitBlockIOHelper(ptrBlockIOLabel, 0, -1)
    %assign needMemsetToZero = retVal[2]
  %endif
   
  %return needMemsetToZero
%endfunction %%SLibInitBlockIO
 
%%Function:GetFinalPassAndNextTransitionIndex===============================
%%Abstract:
%%ThisfunctionisahelperfunctionforSLibInitBlockIOHelper.
%%Itreturns4integers:
%%finalPass:isthisthelastiteration
%%(Eitherwereachedtotheendofthelist,ordetecteda
%%newstandalonesubsystem.InthiscaseIfitdetectsastandalone
%%subsystemtransition,itfillsnextStdIdxandnextStartIdx)
%%
%%skipRecord:skipthisblockoutputrecordornot
%%
%%nextStdIdx:nextstandalonesubsystemindex.
%%nextStartIdx:nextblockOutputindexinthenextstandalonesubsystem
%%
%%TopTester:test/toolbox/simulink/variants/variantBus/vss/tDefaultVariants.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmParameterStructure.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmSrcAZVCLoggingCheck_VC1.m
%%TopTester:test/toolbox/simulink/blocks/lib_MathOperations/Product/rtw/tProductBlk_Codegencheck_SFcnTarget.m
%%TopTester:test/toolbox/simulink/blocks/sb2sl/tsb2slmdlref.m
%%
%function GetFinalPassAndNextTransitionIndex(boIdx, standaloneSSIdx)
  %% assume the following
  %assign nextStdIdx = -1
  %assign nextStartIdx = -1
  %assign skipRecord = TLC_FALSE
  %assign finalPass = TLC_FALSE
   
  %assert(boIdx <= BlockOutputs.NumGlobalBlockOutputs)
  %if boIdx == BlockOutputs.NumGlobalBlockOutputs
    %assign finalPass = TLC_TRUE
  %else
    %assign bo = BlockOutputs.GlobalBlockOutput[boIdx]
    %if bo.RequiredInBlockIO[0] != 1 || bo.RequiredInBlockIO[1] != 0 || ...
      !ISFIELD(bo, "VarGroupIdx") || ...
      (ISFIELD(bo, "UseAccessFunctions") && bo.UseAccessFunctions == 1) || ...
      SLibDataRecordIsInCoderGroup(bo)
      %assign skipRecord = TLC_TRUE
    %elseif StandaloneParentSysIdxOfDataRec(bo) != standaloneSSIdx
      %% We detected a transition.
      %if standaloneSSIdx == -1
        %% We need to dump
        %% initialization of all signals in non-standalone subsystems
        %% into model registration. Since these signals may not be contiguous,
        %% we will skip standalone subsystems, and continue to find more
        %% to find all signals.
        %assign skipRecord = TLC_TRUE
      %else
        %% A new transition. Find the next standalone subsystem transition.
        %assign finalPass = TLC_TRUE
        %assign nextStdIdx = StandaloneParentSysIdxOfDataRec(bo)
        %if nextStdIdx != -1
          %assign nextStartIdx = boIdx
        %else
          %assign nextStartIdx = -1
          %% This function should return the start of next transition.
          %% Find the start of next standalone subsystem section by
          %% going through the rest of blockIO
          %assign numLeft = BlockOutputs.NumGlobalBlockOutputs - (boIdx+1)
          %foreach localIdx = numLeft
            %assign lIdx = (boIdx+1) + localIdx
            %assign lb = BlockOutputs.GlobalBlockOutput[lIdx]
            %if ISEMPTY(lb.SigSrc)
              %continue
            %endif
            %assign standParent = StandaloneParentSysIdxOfDataRec(lb)
            %if standParent != -1
              %% a new standalone subsystem
              %assign nextStdIdx = standParent
              %assign nextStartIdx = lIdx
              %break
            %endif
          %endforeach
        %endif
      %endif
    %endif
  %endif
  %%
  %return [%<finalPass>, %<skipRecord>, %<nextStdIdx>, %<nextStartIdx>]
%endfunction
   
%%TopTester:test/toolbox/simulink/variants/codevariants/tvss_code_variants.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants3.m
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/tStringSupport.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSink/tmVariantSrcSink1_VC1.m
%%TopTester:test/toolbox/simulink/blocks/lib_MathOperations/Product/rtw/tProductBlk_Codegencheck_SFcnTarget.m
%%
%function SLibInitBlockIOForBufferHelper(bo, sysIdx, with_ppIf) void
  %assign ret = ["", "", "", 0, "", 0]
  %openfile csgInitBuffer %% for invariant, or signal object InitialValue
  %openfile straightInitBuffer
  %openfile useLoopVarInitBuffer
  %assign ::CurrentModuleIdx = System[sysIdx].CGIRModuleIdx
  %assign memsetToZeroNeeded = 0
  %%
  %% Ignore initial value of string signals, use ground value instead
  %%
  %% TODO: Remove this and add proper initialization once g1584673
  %% is done
  %assign dTypeId = LibGetRecordDataTypeId(bo)
  %if (!ISEMPTY(bo.InitialValue) || !ISEMPTY(SLibDataTypeConstructFcnName(dTypeId))) && ...
    !LibIsStringDataType(dTypeId)
    %if !FcnSkipDataInitialValueInReg(bo)
      %%
      %% If a non-empty initial value is provided for this block output
      %% then initialize it to that value. Initial values are provided
      %% for:
      %%
      %% - block output signals that have constant sample time but (for
      %% various reasons) could not be declared invariant and placed
      %% in the ConstBlockIO structure
      %%
      %% - non-imported-storage-class signals that have signal object
      %% InitialValue applied on them
      %%
      %% For constant sample time signals, we always generate code for
      %% InitialValue regardless of remove zero initialization option.
      %% For non-constant sample time signals, we still check the option
      %%
      %if bo.Invariant == "yes" || ...
        !SLibRemoveZeroInitForData(bo, bo.InitialValue)
        %assign id = SLibGetBlockOutputIdentifierFromRecord(bo,sysIdx)
        %selectfile csgInitBuffer
        %assign ifCond = ""
        %assign ifEndCond = ""
        %if with_ppIf
          %assign vcRecord = SLibGetDataInlineVariantNetConditions(bo)
          %if vcRecord.hasConds
            %assign ifCond = vcRecord.ifCond
            %assign ifEndCond = vcRecord.endIfCond
          %endif
        %endif
        %if with_ppIf
           %<ifCond>
        %endif
        %<FcnInitDataInitialValue(bo, id)>
        %if with_ppIf
           %<ifEndCond>
        %endif
      %endif
    %endif
  %elseif !SLibRemoveZeroInitForDataDefault(bo)
    %%
    %% InitialValue is empty. Try to use default initial value if possible.
    %%
    %assign curDataTypeId = LibGetDataTypeIdAliasedThruToFromId(LibGetRecordDataTypeId(bo))
    %assign curMemsetToZeroSuffice = FcnMemsetToZeroInitSuffice(curDataTypeId)
    %%
    %if curMemsetToZeroSuffice
      %assign memsetToZeroNeeded = 1
    %else
      %assign nterms = LibGetRecordSymbolicWidth(bo)
      %assign hasSymbolicWidth = LibRecordHasSymbolicWidth(bo)
      %if hasSymbolicWidth
        %% always do memset optimization for symbolic signals
        %assign numElemInMemoryChunk = INT16MAX
      %elseif LibGetRecordIsComplex(bo)
        %assign numElemInMemoryChunk = 2 * %<nterms>
      %else
        %assign numElemInMemoryChunk = %<nterms>
      %endif
         
      %%
      %% output code to initialize current chunk of memory
      %%
         
      %if hasSymbolicWidth || %<nterms> > 0
        %assign ifCond = ""
        %assign ifEndCond = ""
        %if with_ppIf
          %assign vcRecord = SLibGetDataInlineVariantNetConditions(bo)
          %if vcRecord.hasConds
            %assign ifCond = vcRecord.ifCond
            %assign ifEndCond = vcRecord.endIfCond
          %endif
        %endif
        %%
        %%
        %assign DataTypeDefaultInitValue = SLibGetDefaultInitialValueFromId(curDataTypeId)
        %assign DataTypeName = SLibGetRecordContainerBaseTypeName(bo)
        %%
        %if FcnSuitableForMemset(DataTypeDefaultInitValue, curDataTypeId, "") && ...
          FcnPreferMemsetToAssignment(numElemInMemoryChunk, curDataTypeId)
          %%
          %% Be aware that the act of getting the address marks BlockIO as being accessed.
          %% Based on this mark, code generation will declare a BlockIO variable.
          %% We reach this code when initializing some non-zero fixed point fields as in
          %% fixpoint/fixpt_rtw/trtw_vlogic2.m
          %%
          %assign StartAddr = SLibGetBlockOutputFromRecord(bo,sysIdx)
          %selectfile straightInitBuffer
          %assign sanitizedInitValue = ...
            FcnCastValueForMemsetUse(curDataTypeId, DataTypeDefaultInitValue)
          %if hasSymbolicWidth
            %assign memsetWidth = "(" + nterms + ")"
          %else
            %assign memsetWidth = "%<nterms>U"
          %endif
          %if LibGetRecordIsComplex(bo)
            %assign memsetWidth = "2 * %<memsetWidth>"
          %endif
          %<ifCond>
          (void) %<LibGenMemFcnCall("memset", StartAddr, sanitizedInitValue, ...
            "%<memsetWidth>*sizeof(%<DataTypeName>)")>;
          %<ifEndCond>
        %else
          %if LibIsDataTypeMultiWordFixpt(curDataTypeId)
            %assign initValue = SLibGetDtGroundName(curDataTypeId, ...
              LibGetRecordIsComplex(bo), tRealPart)
          %else
            %assign initValue = DataTypeDefaultInitValue
          %endif
          %assign id = SLibGetBlockOutputIdentifierFromRecord(bo, sysIdx)
 
          %assign blockio = id
          %if SLibIsContainerCGTypeND(bo)
            %% If multi-dimensional container type index was provided. Then
            %% we need to create a reference to the first element; e.g.,
            %% (&sigName[0][0])[i] = 0; // See g1835844 for details.
            %assign blockioNumDims = LibCGTypeNumDimensions(SLibGetRecordContainerCGTypeIdx(bo))
            %assign blockio = LibGetAddressOfFirstElement(id, blockioNumDims)
          %endif
 
          %if bo.DeclareAsPointer == "yes"
            %assign id = "(*%<id>)"
          %endif
          %if hasSymbolicWidth || (%<nterms> >= RollThreshold && %<nterms> > 1)
              %% use a loop
              %selectfile useLoopVarInitBuffer
              %<ifCond>
              for (i = 0; i < %<nterms>; i++) {
                %if LibGetRecordIsComplex(bo)
                  %<blockio>[i].%<tRealPart> = %<initValue>;
                  %<blockio>[i].%<tImagPart> = %<initValue>;
                %else
                  %<blockio>[i] = %<initValue>;
                %endif
              }
              %<ifEndCond>
          %elseif %<nterms> > 1
              %% do not use loop
              %selectfile straightInitBuffer
              %<ifCond>
              %foreach initIdx = %<nterms>
                %if LibGetRecordIsComplex(bo)
                  %<blockio>[%<initIdx>].%<tRealPart> = %<initValue>;
                  %<blockio>[%<initIdx>].%<tImagPart> = %<initValue>;
                %else
                  %<blockio>[%<initIdx>] = %<initValue>;
                %endif
              %endforeach
              %<ifEndCond>
          %else
            %selectfile straightInitBuffer
            %<ifCond>
            %if LibGetRecordIsComplex(bo)
              %<id>.%<tRealPart> = %<initValue>;
              %<id>.%<tImagPart> = %<initValue>;
            %else
              %<id> = %<initValue>;
            %endif
            %<ifEndCond>
          %endif
        %endif
      %endif
    %endif
  %endif
  %closefile csgInitBuffer
  %closefile straightInitBuffer
  %closefile useLoopVarInitBuffer
  %assign ::CurrentModuleIdx = -1
  %assign ret[0] = csgInitBuffer
  %assign ret[1] = straightInitBuffer
  %assign ret[2] = useLoopVarInitBuffer
  %assign ret[3] = memsetToZeroNeeded
  %return ret
%endfunction
 
%%Function:SLibInitBlockIOHelper=============================================
%%Abstract:
%%ThisisahelperfunctionforSLibInitBlockIO.
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortFcnCall.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants3.m
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/inlineVariants/tInlineVariants4.m
%%
%function SLibInitBlockIOHelper(ptrBlockIOLabel, startIdx, standaloneSSIdx) Output
  %assign nextStartIdx = -2
  %assign nextStdIdx = -2
  %assign memsetToZeroNeeded = 0
  %assign withSysIdx = standaloneSSIdx ? GetBaseSystemIdx() : standaloneSSIdx
  %assign ::CurrentModuleIdx = System[withSysIdx].CGIRModuleIdx
  %% Choosing this option may result in code that is not MISRA-C compliant.
  %if ForceBlockIOInitOptimize
    %assign unusedVar = SLibInitBlockIOHelperOld(ptrBlockIOLabel, startIdx, standaloneSSIdx)
    %return [%<nextStdIdx>, %<nextStartIdx>, %<memsetToZeroNeeded>]
  %endif
  %assign blkioIsEmpty = ::CompiledModel.DWorkAndBlockIOCombined ? ...
    SLibModelDWorkStructIsEmpty() : SLibModelBlockIOStructIsEmpty()
  %if !blkioIsEmpty
    %%
    %assign csgInitBuffer = "" %% for invariant, or signal object InitialValue
    %assign straightInitBuffer = ""
    %assign useLoopVarInitBuffer = ""
    %assign vecLoopVarInitBufferIfConditions = []
    %assign loopVarInitBufferEndIfCond = ""
    %assign gaurdLoopVarInitBuffer = 1
    %%
    %assign baseSystemIdx = GetBaseSystemIdx()
    %assign numOutputsPlusOne = BlockOutputs.NumGlobalBlockOutputs + 1
     
    %% forbid memset if needed (one of the members needs constructor, such as classtype)
    %assign forbidMemset = TLC_FALSE
    %foreach loopIdx = (numOutputsPlusOne - startIdx)
      %assign boIdx = loopIdx + startIdx
      %if boIdx != BlockOutputs.NumGlobalBlockOutputs && ...
        ISEMPTY(BlockOutputs.GlobalBlockOutput[boIdx].SigSrc)
         %continue
      %endif
      %%
      %assign fInfo = GetFinalPassAndNextTransitionIndex(boIdx, standaloneSSIdx)
      %assign finalPass = fInfo[0]
      %assign skipRecord = fInfo[1]
      %assign nextStdIdx = fInfo[2]
      %assign nextStartIdx = fInfo[3]
      %%
      %if skipRecord
        %continue
      %endif
      %if finalPass
        %break
      %endif
      %%
      %%
      %assign bo = BlockOutputs.GlobalBlockOutput[boIdx]
      %assign dtIdx = LibGetRecordDataTypeId(bo)
      %if LibDoesDataTypeNeedConstructor(dtIdx) || LibDoesDataTypeMemberNeedConstructor(dtIdx)
        %assign forbidMemset = TLC_TRUE
      %endif
      %%
      %assign ret = SLibInitBlockIOForBufferHelper(bo, baseSystemIdx, TLC_TRUE)
      %if !bo.InitInStart
        %% Take the init code only for buffers not initialized in start function
        %assign csgInitBuffer = csgInitBuffer + ret[0]
        %assign straightInitBuffer = straightInitBuffer + ret[1]
        %assign useLoopVarInitBuffer = useLoopVarInitBuffer + ret[2]
      %endif
      %if !WHITE_SPACE(ret[2])
          %assign vcRecord = SLibGetDataInlineVariantNetConditions(bo)
          %if !vcRecord.hasConds
            %assign gaurdLoopVarInitBuffer = 0
          %endif
          %if gaurdLoopVarInitBuffer == 0
            %assign vecLoopVarInitBufferIfConditions = []
            %assign loopVarInitBufferEndIfCond = ""
          %else
            %assign vecLoopVarInitBufferIfConditions = vecLoopVarInitBufferIfConditions + vcRecord.ifCond
            %assign loopVarInitBufferEndIfCond = vcRecord.endIfCond
          %endif
      %endif
      %if ret[3]
        %% memset flag is set for any buffer, try do memset
        %assign memsetToZeroNeeded = ret[3]
      %endif
    %%
    %endforeach %% for each boIdx
     
    %%
    %assign memsetToZeroNeeded = memsetToZeroNeeded && !forbidMemset
    %if memsetToZeroNeeded && !::CompiledModel.DWorkAndBlockIOCombined && !SLibIsSelfStructured()
      %if standaloneSSIdx == -1
        %assign blockIOType = IsModelReferenceTarget() && !GenerateClassInterface ...
          ? ...
          FcnSysVarGroupType(System[NumSystems-2],"BlockIO") : ::tBlockIOType
        %assign systemIfCond = NumSystems-2 >= 0 ? SLibIfSystemVariantCondition(System[NumSystems-2]) : ""
        %assign systemIfEndCond = NumSystems-2 >= 0 ? SLibEndIfSystemVariantCondition(System[NumSystems-2]) : ""
        %<systemIfCond>
        (void) %<LibGenMemFcnCall("memset", ptrBlockIOLabel, "0", ...
          "sizeof(%<blockIOType>)")>;
        %<systemIfEndCond>
 
        %<SLibAccessArgHelper(System[baseSystemIdx].Interface.BlockIOArgDef,"","")>
      %else
        %assign type = FcnSysVarGroupType(System[standaloneSSIdx],"BlockIO")
        %assign systemIfCond = SLibIfSystemVariantCondition(System[standaloneSSIdx])
        %assign systemIfEndCond = SLibEndIfSystemVariantCondition(System[standaloneSSIdx])
  
        %assign var = "(void *) &" + ...
          FcnSysVarGroupNonreusedName(System[standaloneSSIdx],"BlockIO")
  
        %<systemIfCond>
        (void) %<LibGenMemFcnCall("memset", var, "0", "sizeof(%<type>)")>;
        %<systemIfEndCond>
      %endif
    %endif
    %% In the case where DWorkAndBlockIOCombined and BlockIOs are the only
    %% DWorks, we should generate the memset init logics for the DWork structure.
    %if memsetToZeroNeeded && ::CompiledModel.DWorkAndBlockIOCombined && !SLibGetUseRTMcgType() &&...
        standaloneSSIdx != -1 && ISEMPTY(System[standaloneSSIdx].Interface.DWorkArgDef)
      %assign type = FcnSysVarGroupType(System[standaloneSSIdx],"DWork")
      %assign var = "(void *) &" + ...
        FcnSysVarGroupNonreusedName(System[standaloneSSIdx],"DWork")
      %assign systemIfCond = SLibIfSystemVariantCondition(System[standaloneSSIdx])
      %assign systemIfEndCond = SLibEndIfSystemVariantCondition(System[standaloneSSIdx])
       
      %<systemIfCond>
      (void) %<LibGenMemFcnCall("memset", var, "0", "sizeof(%<type>)")>;
      %<systemIfEndCond>
    %endif
    %%
 
    %if !WHITE_SPACE(csgInitBuffer) ...
      || !WHITE_SPACE(straightInitBuffer) ...
      || !WHITE_SPACE(useLoopVarInitBuffer)
      %% SLibGetBlockOutputFromRecord above took care of LibAccessArg
      {
        %if !WHITE_SPACE(useLoopVarInitBuffer)
          %assign loopVarInitBufferIfCond = SLibGetMergedIfCondition(vecLoopVarInitBufferIfConditions)
          %<SLibCreateLocalVariableWithConditions("%<LibCGTypeName(::CompiledModel.CGTypes.IndexType)> i;", loopVarInitBufferIfCond, loopVarInitBufferEndIfCond)>
          %<useLoopVarInitBuffer>/
        %endif
        %<straightInitBuffer>/
        %<csgInitBuffer>/
      }
    %endif
  %endif
  %assign needMemsetForCombinedDWorkAndBlockIO = memsetToZeroNeeded ...
                                   && ::CompiledModel.DWorkAndBlockIOCombined
  %assign ::CurrentModuleIdx = -1
  %return [%<nextStdIdx>, %<nextStartIdx>, %<needMemsetForCombinedDWorkAndBlockIO>]
%endfunction %% SLibInitBlockIOHelper
 
%%Function:SLibAtleastOneInputHasReusableCSCWithoutReuseBufferName
%%Abstract:
%%Returnstrueiffatleastoneexternalinputhasareusablestorageclassbut
%%noauxiliarybuffer.Thisispossiblewhenwedon'tneedtocreateanauxiliary
%%bufferassociatedwiththereusablestorageclassbuffer.
%function SLibAtleastOneInputHasReusableCSCWithoutReuseBufferName() void
  %foreach idx = ExternalInputs.NumExternalInputs
    %assign extInp = ExternalInputs.ExternalInput[idx]
    %if SLibHasReusableCSCWithoutReusableBuffer(extInp)
      %return TLC_TRUE
    %endif
  %endforeach
   
  %return TLC_FALSE
%endfunction
 
%%Function:SLibAtleastOneOutputHasReusableCSCWithoutReuseBufferName
%%Abstract:
%%Returnstrueiffatleastoneexternaloutputhasareusablestorageclassbut
%%noauxiliarybuffer.Thisispossiblewhenwedon'tneedtocreateanauxiliary
%%bufferassociatedwiththereusablestorageclassbuffer.
%function SLibAtleastOneOutputHasReusableCSCWithoutReuseBufferName() void
  %foreach idx = ExternalOutputs.NumExternalOutputs
    %assign extOut = ExternalOutputs.ExternalOutput[idx]
    %if SLibHasReusableCSCWithoutReusableBuffer(extOut)
      %return TLC_TRUE
    %endif
  %endforeach
   
  %return TLC_FALSE
%endfunction
 
%%Function:FcnIsInitedByExternalBlockOutput
%%Abstract:
%%FindoutthesamereusableCSCblockoutput
%%thathasbeeninitialized
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmg1293017_VC1.m
%%
%function FcnIsInitedByExternalBlockOutput(extInp) void
  %if extInp.StorageClass == "Custom" && SLibGetIsReusable(extInp)
    %foreach boIdx = ::CompiledModel.BlockOutputs.NumExternalBlockOutputs
      %assign bo = ::CompiledModel.BlockOutputs.ExternalBlockOutput[boIdx]
      %if bo.StorageClass == "Custom" && ...
        SLibGetIsReusable(bo) && ...
        SLibHasReusableCSCWithoutReusableBuffer(bo) && ...
        !SLibOmitRecord(bo) && ...
        !FcnIsNotInterfaceableStorageClassCheck(bo) && ...
        SLibWriteOutInstForSignalRec(bo) && ...
        ISEMPTY(bo.InitialValue) && ...
        !FcnIsImportedScopeCustomStorageCheck(bo)
        %return TLC_TRUE
      %endif
    %endforeach
  %endif
   
  %return TLC_FALSE
%endfunction
 
%%Function:SLibInitExternalInputRecord
%%Abstract:
%%HelperforSLibInitExternalInputsHelper(..)
%%Givenanexternalinputrecordidx,initializesit.
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmg1293017_VC1.m
%%TopTester:test/toolbox/simulink/variants/exportFcns/tExportFcnsWithInlineVariants.m
%%
%function SLibInitExternalInputRecord(localIn, fromSFcn, recIdx, useIRInitialization, forbidMemsetDueToOtherInputs) Output
  %assign memsetToZeroNeeded = TLC_FALSE
  %assign extInp = ::CompiledModel.ExternalInputs.ExternalInput[recIdx]
  %assign dataTypeId = SLibGetRecordDataTypeId(extInp)
    %% We never call memset unless it is a RootIO structure with more than
    %% one field or it's an input argument that points to a whole structure
    %assign memsetMightBeNeeded = (!localIn && ExternalInputs.NumExternalInputs > 1) ...
      && (!MultiInstanceERTCode || RootIOStructures)
 
      %% Skip initialization if we are generating initialization code through IR
      %% and the CGType is not unknown (e.g. custom type registered using S-function API)
      %if (useIRInitialization && !LibCGTypeIsUnknown(extInp.CGTypeIdx) && (extInp.StorageClass != "Custom" || SLibGetIsReusable(extInp)))
        %return memsetToZeroNeeded
      %endif
       
      %% ignore inactive port; note that the Inactive field is there that means it is inactive: no need to check its value
      %if (ISFIELD(extInp, "Inactive"))
        %return memsetToZeroNeeded
      %endif
      %% ignore external port that is accessed by an access function
      %if (ISFIELD(extInp, "UseAccessFunctions") && extInp.UseAccessFunctions == 1)
        %return memsetToZeroNeeded
      %endif
      %% ingore external port whose data type has a constructor
      %if !ISEMPTY(SLibDataTypeConstructFcnName(dataTypeId))
        %return memsetToZeroNeeded
      %endif
      %assign vcRecord = SLibGetDataInlineVariantNetConditions(extInp)
      %assign ifCond = vcRecord.ifCond
      %assign ifEndCond = vcRecord.endIfCond
      %assign dataTypeEnum = LibGetDataTypeEnumFromId(dataTypeId)
      %if dataTypeEnum == "SS_FCN_CALL" || ...
        (SLibFcnProtoCtrlActive() && extInp.RequiresGlobalAccess == "no" && !localIn)
        %return memsetToZeroNeeded
      %endif
      %%
      %if !SLibWriteOutInstForSignalRec(extInp)
        %return memsetToZeroNeeded
      %endif
      %if !ISEMPTY(SLibDataTypeConstructFcnName(dataTypeId))
        %return memsetToZeroNeeded
      %endif
      %%
      %% Streamline code based on storage class
      %if (extInp.StorageClass == "Auto" || ...
        extInp.StorageClass == "ExportedGlobal")
        %assign AutoOrExportedGlobal = TLC_TRUE
      %elseif (extInp.StorageClass == "ImportedExtern" || ...
        extInp.StorageClass == "ImportedExternPointer")
        %return memsetToZeroNeeded
      %else
        %% Must be "Custom"
        %assign AutoOrExportedGlobal = TLC_FALSE
        %%
        %% Do not initialize imported custom storage class signals
        %if FcnIsImportedScopeCustomStorageCheck(extInp)
          %return memsetToZeroNeeded
        %endif
      %endif
      %%
      %assign dTypeId = LibGetDataTypeIdAliasedThruToFromId(...
        SLibGetRecordDataTypeId(extInp))
      %assign width = LibGetRecordSymbolicWidth(extInp)
      %assign hasSymbolicWidth = LibRecordHasSymbolicWidth(extInp)
      %%
      %if localIn
        %assign varName = "localIn%<recIdx>"
      %elseif extInp.StorageClass == "Auto"
        %assign varName = "%<SLibGetExternalInputStructForRecord(extInp)>%<UQualifier>%<LibGetRecordIdentifier(extInp)>"
        %if PassExtInpByRef(extInp)
          %assign varName = "(*%<varName>)"
        %endif
      %elseif extInp.StorageClass == "ExportedGlobal"
        %assign varName = LibGetRecordIdentifier(extInp)
      %else
        %assign varName = "" %% will be ignored by "Custom" anyway
      %endif
      %%
      %if !ISEMPTY(extInp.InitialValue)
        %if !FcnSkipDataInitialValueInReg(extInp)
          %%
          %% InitialValue are provided for non-imported-storage-class
          %% signals that have signal object InitialValue applied on them
          %%
          %assign initValue = extInp.InitialValue
          %if SLibRemoveZeroInitForData(extInp, initValue)
            %return memsetToZeroNeeded
          %endif
          %%
          %if extInp.StorageClass == "Auto"
            %% Make sure the extInp is marked as accessed
            %<SLibAccessArgHelper(extInp,"","")>
            %if SLibDataRecordIsInCoderGroup(extInp)
              %assign coderGroupId = ...
                SLibGetCoderGroupIdForDataRecord(extInp)
              %<SLibCG_TrackCoderDataGroup(GetBaseSystemIdx(), ...
                coderGroupId)>
            %endif
          %endif
          %%
          %<FcnInitDataInitialValue(extInp, varName)>
        %endif
      %else
        %% InitialValue not provided. Use default initial value then.
        %%
        %if AutoOrExportedGlobal
          %%
          %% Always assign initial value for SFcn wrapper for local vars
          %% since even if we can optimize away zeros on the target, we may
          %% not be able to on the host
          %if !localIn && SLibRemoveZeroInitForDataDefault(extInp) && ...
            !(fromSFcn && SLibCPPClassNeedERTSfcnZeroIOMemory())
            %% don't return if there's a ground variable for the data type
            %% which might not be all zero
            %assign hasGroundVariable = TLC_FALSE
            %if !LibIsDataTypeMultiWordFixpt(dTypeId) && ...
                LibIsStructDataType(dataTypeId) && ...
                ISFIELD(::CompiledModel.DataTypes.DataType[dataTypeId], "GroundVariableName")
              %assign hasGroundVariable = TLC_TRUE
            %endif
            %if !hasGroundVariable
              %return memsetToZeroNeeded
            %endif
          %endif
          %if extInp.StorageClass == "Auto"
            %% Make sure the extInp is marked as accessed
            %<SLibAccessArgHelper(extInp,"","")>
            %if SLibDataRecordIsInCoderGroup(extInp)
              %assign coderGroupId = ...
                SLibGetCoderGroupIdForDataRecord(extInp)
              %<SLibCG_TrackCoderDataGroup(GetBaseSystemIdx(), ...
                coderGroupId)>
            %endif
            %%
            %% The memsetToZero optimization cannot be used for ExportedGlobals
            %% so we only check Inputs that are StorageClass Auto
            %if memsetMightBeNeeded && !forbidMemsetDueToOtherInputs
              %if FcnMemsetToZeroInitSuffice(dTypeId)
                %assign memsetToZeroNeeded = 1
                %return memsetToZeroNeeded
              %endif
            %endif
          %endif
          %%
          %% Warning: this will trigger the GroundUsed flag for struct data type
          %if LibIsDataTypeMultiWordFixpt(dTypeId)
            %assign initValue = SLibGetDtGroundName(dTypeId, ...
              LibGetRecordIsComplex(extInp), tRealPart)
          %else
            %assign initValue = SLibGetDefaultInitialValue(extInp,tRealPart)
          %endif
          %%
          %<ifCond>
          %if width == "1"
            %if LibGetRecordIsComplex(extInp)
              %<varName>.%<tRealPart> = %<initValue>;
              %<varName>.%<tImagPart> = %<initValue>;
            %else
              %<varName> = %<initValue>;
            %endif
          %else
            %% Because SLibValueIsAllZeroBitsCrudeCheck interogates a string for '0',
            %% or '0.0', it is OK to memset multiword as long as initValue is 0.
            %% To be conservative, since multiword's ground value is '{0}' at its
            %% closest, not '0', it is actually never memset.
            %assign memsetSuitable = ...
              FcnSuitableForMemset(initValue, dTypeId, extInp.StorageClass)
            %%
            %if !memsetSuitable
              %%
              %assign extInpNumDims = LibGetRecordNumDimsFromContainerCgTypeIdx(extInp)
              %assign varLhsAccess = LibGetAddressOfFirstElement(varName, extInpNumDims)
              %if hasSymbolicWidth || %<width> >= RollThreshold
                %assign loopCode = SLibEmitForLoopCounterCode(width, "i")
                {
                  %
                  % {
                    %if LibGetRecordIsComplex(extInp)
                      %<varLhsAccess>[i].%<tRealPart> = %<initValue>;
                      %<varLhsAccess>[i].%<tImagPart> = %<initValue>;
                    %else
                      %<varLhsAccess>[i] = %<initValue>;
                    %endif
                  }
                }
              %else
                %foreach initIdx = %<width>
                  %if LibGetRecordIsComplex(extInp)
                    %<varLhsAccess>[%<initIdx>].%<tRealPart> = %<initValue>;
                    %<varLhsAccess>[%<initIdx>].%<tImagPart> = %<initValue>;
                  %else
                    %<varLhsAccess>[%<initIdx>] = %<initValue>;
                  %endif
                %endforeach
              %endif
            %else
                %assign dTypeName = SLibGetRecordContainerBaseTypeName(extInp)
                %if hasSymbolicWidth
                  %assign memsetWidth = "(" + width + ")"
                %else
                  %assign memsetWidth = "%<width>U"
                %endif
                %if LibGetRecordIsComplex(extInp)
                  %assign memsetWidth = "2*%<memsetWidth>"
                %endif
                %assign sanitizedInitValue = ...
                  FcnCastValueForMemsetUse(dTypeId, initValue)
                (void) %<LibGenMemFcnCall("memset", varName, sanitizedInitValue, ...
                  "%<memsetWidth>*sizeof(%<dTypeName>)")>;
            %endif
          %endif
          %%
          %<ifEndCond>
        %else
          %% Not AutoOrExportedGlobal, must be "Custom"
          %%
          %if extInp.IsEliminated == "false"
            %openfile tmpBuf
            %if !FcnIsInitedByExternalBlockOutput(extInp)
              %<SLibEmitLibCustomInitCode(extInp, width, LibGetRecordIsComplex(extInp))>
            %endif
            %if ISFIELD(extInp, "ReuseBufferName") && ...
              extInp.Identifier != extInp.ReuseBufferName
              %assign tempId = extInp.Identifier
              %assign extInp.Identifier = extInp.ReuseBufferName
              %% Need to generate initialization code for the input reuse buffer
              %<SLibEmitLibCustomInitCode(extInp, width, LibGetRecordIsComplex(extInp))>
              %assign extInp.Identifier = tempId
            %endif
            %closefile tmpBuf
            %if !WHITE_SPACE(tmpBuf)
                %% TopTester: test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmg1281128_VC1.m
                %<ifCond>
                %<tmpBuf>
                %<ifEndCond>
            %endif
          %endif
        %endif %% AutoOrExportedGlobal or Custom, default initial value
        %%
        %if extInp.Padding > 0
          %if extInp.Padding > 1
            %assign addrOf = ""
          %else
            %assign addrOf = "&"
          %endif
            (void) %<LibGenMemFcnCall("memset", ...
              "%<addrOf>%<SLibGetExternalInputStructForRecord(extInp)>%<UQualifier>pad_%<LibGetRecordIdentifier(extInp)>", ...
              "'a'", "%<extInp.Padding>U*sizeof(char)")>;
        %endif
      %endif %% InitialValue
       
  %return memsetToZeroNeeded
%endfunction
 
%%Function:SLibInitExternalInputsHelper============================================
%%Abstract:
%%HelperforSLibInitExternalInputswhichinitializestheexternalinputs
%%structure,includingexternalstorageinputs.Thehelpertakesinanextra
%%argument"isCoderGroupInit"whichindicateswhetherwearecallingthis
%%routineaspartofcodergroupinitialization.Thishelperthenreturnsanarray
%%withtwoelements,firstonebeingtheinitializationbuffer,andthesecond
%%onetellingwhetherweshouldmemsetthestructure.
%%
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmg1293017_VC1.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/ivGeneral/tVariantsAndSubmodels.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmg1396738_inlined_VC1.m-tmreuse_across_models.m
%%
%function SLibInitExternalInputsHelper(usingStatic, localIn, fromSFcn, coderGroupVarGroupIdx) void
  %assign isCoderGroupVarGroup = (coderGroupVarGroupIdx != -1)
  %assign useIRInitialization = UseIRModelInitCode && (!fromSFcn) && ...
    !SLibAtleastOneInputHasReusableCSCWithoutReuseBufferName() && !isCoderGroupVarGroup
   
  %% New IR Implementation
  %assign irInitBuffer = ""
  %if UseIRModelInitCode
    %assign irInitBuffer = SLibDumpExternalInputsInitializationCode(::CompiledModel.System[GetBaseSystemIdx()])
  %endif
   
  %openfile tlcInitBuffer
  %assign needMemsetToZero = TLC_FALSE
       
  %% Old TLC Implementation
  %if ((NumModelInputs > 0) && ...
    !SLibAutosarActive())
    %% When one or more inputs are classes, we should never use memset on whole outputs
    %assign forbidMemsetToZero = TLC_FALSE
    %openfile NonMemsetBuffer
    %if isCoderGroupVarGroup
        %assign coderGroupVarGroup = ::CompiledModel.VarGroups.VarGroup[coderGroupVarGroupIdx]
        %assert coderGroupVarGroup.Category == "HierarchicalCoderData"
         
        %%loop through all elements to see if we need to forbid memset to zero
        %foreach elIdx = coderGroupVarGroup.NumVarGroupElements
          %assign idnum = IDNUM(coderGroupVarGroup.VarGroupElements[elIdx])
          %assign recType = idnum[0]
          %if recType == "U"
            %assign recIdx = idnum[1]
            %assign extInp = ::CompiledModel.ExternalInputs.ExternalInput[recIdx]
            %if SLibShouldForbidMemsetToZeroForRecord(extInp)
              %assign forbidMemsetToZero = TLC_TRUE
            %endif
          %endif
        %endforeach
         
        %foreach elIdx = coderGroupVarGroup.NumVarGroupElements
          %assign idnum = IDNUM(coderGroupVarGroup.VarGroupElements[elIdx])
          %assign recType = idnum[0]
          %if recType == "U"
            %assign recIdx = idnum[1]
            %assign extInp = ::CompiledModel.ExternalInputs.ExternalInput[recIdx]
            %if !SLibDataRecordIsInCoderGroup(extInp)
              %continue
            %endif
            %assign ret = SLibInitExternalInputRecord(localIn, fromSFcn, recIdx, useIRInitialization,forbidMemsetToZero)
            %if ret
              %assign needMemsetToZero = TLC_TRUE
            %endif
          %endif
        %endforeach
    %else
      %%loop through all elements to see if we need to forbid memset to zero
      %foreach idx = ::CompiledModel.ExternalInputs.NumExternalInputs
        %assign extInp = ::CompiledModel.ExternalInputs.ExternalInput[idx]
        %if SLibShouldForbidMemsetToZeroForRecord(extInp)
          %assign forbidMemsetToZero = TLC_TRUE
        %endif
      %endforeach
       
      %foreach idx = ::CompiledModel.ExternalInputs.NumExternalInputs
        %assign extInp = ::CompiledModel.ExternalInputs.ExternalInput[idx]
        %if SLibDataRecordIsInCoderGroup(extInp)
              %continue
        %endif
        %assign ret = SLibInitExternalInputRecord(localIn, fromSFcn, idx, useIRInitialization,forbidMemsetToZero)
        %if ret
          %assign needMemsetToZero = TLC_TRUE
        %endif
      %endforeach
    %endif
    %closefile NonMemsetBuffer
     
    %if needMemsetToZero
      %if !isCoderGroupVarGroup
        %assign initAddr = (UQualifier == "." ? "&" : "") + ...
          LibGetExternalInputStruct()
        (void) %<LibGenMemFcnCall("memset", "(void *)" + initAddr, ...
          " 0", " sizeof(%<::tInputType>)")>;
      %endif
    %endif
 
    %%
    %if !WHITE_SPACE(NonMemsetBuffer)
      %<NonMemsetBuffer>
    %endif
  %endif
   
  %closefile tlcInitBuffer
 
  %assign retBuffer = ["", 0]
  %assign retBuffer[0] = useIRInitialization ? ...
    irInitBuffer + "/n" + tlcInitBuffer : ...
    tlcInitBuffer
  %assign retBuffer[1] = needMemsetToZero
   
  %return retBuffer
%endfunction
 
%%Function:SLibInitExternalInputs============================================
%%Abstract:
%%Initializetheexternalinputsstructureandwithexternalstorage
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortFcnCall3.m
%%
%function SLibInitExternalInputs(usingStatic, localIn, fromSFcn) Output
  %assign ret = SLibInitExternalInputsHelper(usingStatic, localIn, fromSFcn, -1)
  %assign initBuffer = ret[0]
  %<initBuffer>/
%endfunction %% SLibInitExternalInputs
 
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmg1293017_VC1.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants6.m
%function SLibInitExternalInputSizes() Output
  %with ::CompiledModel.System[NumSystems-1]
  %if ((::CompiledModel.NumModelInputs > 0) && ...
    (!IsModelReferenceTarget()) && ...
    !SLibAutosarActive())
    %% initialize root inport sizes for auto and exported global.
    %foreach idx = ::CompiledModel.ExternalInputs.NumExternalInputs
      %assign extInp = ::CompiledModel.ExternalInputs.ExternalInput[idx]
      %if ISFIELD(extInp, "HasVarDims")
        %if ISFIELD(extInp, "SizeVarGroupIdx")
          %assert extInp.StorageClass == "Auto"
          %assign sizeTypeIdx = SLibCGVarGroupMemberCGTypeIdx(...
            extInp.SizeVarGroupIdx[0], ...
            extInp.SizeVarGroupIdx[1])
          %assign sizeVecLen = LibCGTypeWidth(sizeTypeIdx)
          %foreach dimIdx = sizeVecLen
            %<SLibGetInportSize(idx, sizeVecLen, "", -1, "", dimIdx)> = ...
              %<SLibGetDefaultInitialValueByCGTypeIdx(...
              sizeTypeIdx, tRealPart)>;
          %endforeach
        %elseif ISFIELD(extInp, "DimSizeDWork")
          %assert extInp.StorageClass == "ExportedGlobal"
          %assign dworkRec = ::CompiledModel.DWorks.DWork[extInp.DimSizeDWork]
          %assign sizeVecLen = LibCGTypeWidth(LibGetRecordCGTypeIdx(dworkRec))
          %foreach dimIdx = sizeVecLen
            %<SLibCG_V(LibGetRecordIdentifier(dworkRec), TLC_FALSE, sizeVecLen, ...
              "", -1, "", dimIdx)> = ...
              %<SLibGetDefaultInitialValue(dworkRec, ...
              tRealPart)>;
          %endforeach
        %endif
      %endif
    %endforeach
  %endif
  %endwith
%endfunction %% SLibInitExternalInputSizes
 
%%Function:FcnIgnoreExtOutForInit=======================================
%%Abstract:
%%Returnswhetherweshouldignorethisexternaloutputforinitialization
%%routines
%%
%%TopTester:test/toolbox/simulink/variants/outputWhenUnconnected/tOutWhenUnconnected.m
%%
%function FcnIgnoreExtOutForInit(extOut)
  %assign sysIdx = extOut.Block[0]
  %assign blkIdx = extOut.Block[1]
  %assign outportBlock = System[sysIdx].Block[blkIdx]
 
  %if (ISFIELD(outportBlock, "Inactive"))
    %return TLC_TRUE
  %endif
   
  %% ignore external port that is accessed by an access function
  %if (ISFIELD(extOut, "UseAccessFunctions") && extOut.UseAccessFunctions == 1)
    %return TLC_TRUE
  %endif
 
  %% ignore external port that is a message
  %if (ISFIELD(extOut, "IsMessage") && extOut.IsMessage == 1)
    %return TLC_TRUE
  %endif
   
  %% ingore external port whose data type has a constructor
  %assign dataTypeId = LibGetRecordDataTypeId(extOut)
  %if !ISEMPTY(SLibDataTypeConstructFcnName(dataTypeId))
    %return TLC_TRUE
  %endif
 
  %if SLibShouldSkipInitForRecord(extOut)
    %return TLC_TRUE
  %endif
   
  %return TLC_FALSE
%endfunction
 
%%Function:FcnInitializeExternalOutput==================================
%%Abstract:
%%Returnswhetherweshouldinitializeanexternaloutport
%%
%function FcnInitializeExternalOutput(extOut)
  %assign sysIdx = extOut.Block[0]
  %assign blkIdx = extOut.Block[1]
  %assign outportBlock = System[sysIdx].Block[blkIdx]
 
  %if !SLibExternalOutputIsVirtual(outportBlock) && ...
      (!SLibFcnProtoCtrlActive() || extOut.RequiresGlobalAccess == "yes")
      %return TLC_TRUE
  %endif
 
  %return TLC_FALSE
 
%endfunction
 
 
%%Function:SLibInitExternalOutputRecord
%%Abstract:
%%HelperforSLibInitExternalOutputsHelper(..)
%%Givenanexternaloutputrecordidx,initializesthatrecord.
%%TopTester:test/toolbox/simulink/variants/variantBus/tmMultiportBlockBasic2_VC1.m
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/tStringSupport.m
%%Toptetser:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmg1317695_VC1.m
%%
%function SLibInitExternalOutputRecord(localOut, fromSFcn, recIdx, useIRInitialization, forbidMemsetDueToOtherOutputs) Output
  %assign memsetToZeroNeeded = TLC_FALSE
  %assign extOutp = ::CompiledModel.ExternalOutputs.ExternalOutput[recIdx]
  %assign cgTypeIdx = extOutp.CGTypeIdx
  %% Skip initialization if we are generating initialization code through IR
  %% and the CGType is not unknown (e.g. custom type registered using S-function API)
  %if (useIRInitialization && !SLibIsUnknownType(cgTypeIdx) && (extOutp.StorageClass != "Custom" || SLibGetIsReusable(extOutp)))
    %return memsetToZeroNeeded
  %endif
   
  %assign memsetMightBeNeeded = (!localOut && ExternalOutputs.NumExternalOutputs > 1) ...
    && (!MultiInstanceERTCode || RootIOStructures)
 
  %assign sysIdx = extOutp.Block[0]
  %assign blkIdx = extOutp.Block[1]
  %assign outportBlock = System[sysIdx].Block[blkIdx]
 
  %if FcnIgnoreExtOutForInit(extOutp)
    %return memsetToZeroNeeded
  %endif
   
  %assign ifCond = SLibIfVariantCondition(outportBlock)
  %assign ifEndCond = SLibEndIfVariantCondition(outportBlock)
  %with outportBlock
    %% This would skip any ExternalOutput of external storage (which is
    %% covered by SLibInitBlockIOWithExternalStorage)
    %if FcnInitializeExternalOutput(extOutp) || localOut
      %assign rPart = "%<tRealPart>0"
      %assign iPart = "%<tImagPart>0"
      %assign dTypeId = ...
        LibGetDataTypeIdAliasedThruToFromId(LibGetRecordDataTypeId(extOutp))
      %assign uIsComplex = LibGetRecordIsComplex(extOutp)
      %% Streamline code based on storage class
      %if (extOutp.StorageClass == "Auto" || extOutp.StorageClass == "ExportedGlobal")
        %assign AutoOrExportedGlobal = TLC_TRUE
      %elseif (extOutp.StorageClass == "ImportedExtern" || extOutp.StorageClass == "ImportedExternPointer")
        %return memsetToZeroNeeded
      %elseif !ISEMPTY(SLibDataTypeConstructFcnName(dTypeId))
        %return memsetToZeroNeeded
      %else
        %% Must be "Custom"
        %assign AutoOrExportedGlobal = TLC_FALSE
        %% Do not initialize imported custom storage class signals
        %if FcnIsImportedScopeCustomStorageCheck(extOutp)
          %return memsetToZeroNeeded
        %endif
      %endif
      %assign outNumDims = LibGetRecordNumDimsFromContainerCgTypeIdx(extOutp)
      %assign outWidth = LibGetRecordSymbolicWidth(extOutp)
      %assign hasSymbolicWidth = LibRecordHasSymbolicWidth(extOutp)
      %%
      %if AutoOrExportedGlobal
        %% Always assign initial value for SFcn wrapper for local vars
        %% since even if we can optimize away zeros on the target, we may
        %% not be able to on the host
        %if !localOut && SLibRemoveZeroInitForDataDefault(extOutp) && ...
          !(fromSFcn && SLibCPPClassNeedERTSfcnZeroIOMemory())
          %return memsetToZeroNeeded
        %endif
        %%
        %if extOutp.StorageClass == "Auto"
          %% Make sure the extOutp is marked as accessed
          %<SLibAccessArgHelper(extOutp,"","")>
           
          %if SLibDataRecordIsInCoderGroup(extOutp)
            %assign coderGroupId = ...
              SLibGetCoderGroupIdForDataRecord(extOutp)
            %<SLibCG_TrackCoderDataGroup(GetBaseSystemIdx(), ...
                                        coderGroupId)>
          %endif
          %% If the memset optimization is possible, check this Output
          %if memsetMightBeNeeded && !forbidMemsetDueToOtherOutputs
            %if FcnMemsetToZeroInitSuffice(dTypeId)
              %assign memsetToZeroNeeded = TLC_TRUE
              %% We know we can ignore this one. Memset has taken care of it.
              %return memsetToZeroNeeded
            %endif
          %endif
        %endif
        %%
        %% Warning: this will trigger the GroundUsed flag for struct data type
        %if LibIsDataTypeMultiWordFixpt(dTypeId)
          %assign defaultInitialValue = SLibGetDtGroundName(dTypeId, ...
            LibGetRecordIsComplex(DataInputPort), tRealPart)
        %else
          %assign defaultInitialValue = SLibGetDefaultInitialValue(DataInputPort, tRealPart)
        %endif
        %%
        %<ifCond>
        %if outWidth == "1"
          %% LibBlockDstSiganlLocation would take care of LibAccessArg
          %if localOut
            %assign lhs = "localOut%<recIdx>"
            %if uIsComplex
              %assign lhs = lhs + "." + tRealPart
            %endif
            %<lhs> = %<defaultInitialValue>;
            %if uIsComplex
              %assign lhs = "localOut%<recIdx>" + "." + tImagPart
              %<lhs> = %<defaultInitialValue>;
            %endif
          %elseif extOutp.StorageClass == "Auto"
            %<LibBlockDstSignalLocation("outportblk","","",rPart)> = %<defaultInitialValue>;
            %if uIsComplex
              %<LibBlockDstSignalLocation("outportblk","","",iPart)> = %<defaultInitialValue>;
            %endif
          %elseif extOutp.StorageClass == "ExportedGlobal"
            %assign lhs = LibGetRecordIdentifier(extOutp)
            %if uIsComplex
              %<lhs>.%<tRealPart> = %<defaultInitialValue>;
              %<lhs>.%<tImagPart> = %<defaultInitialValue>;
            %else
              %<lhs> = %<defaultInitialValue>;
            %endif
          %endif
        %else
          %% Because SLibValueIsAllZeroBitsCrudeCheck interogates a string for '0',
          %% or '0.0', it is OK to memset multiword as long as initValue is 0.
          %% To be conservative, since multiword's ground value is '{0}' at the
          %% closest, not '0', it is never memset.
          %assign memsetSuitable = !localOut && ...
            FcnSuitableForMemset(defaultInitialValue, dTypeId, "")
           
          %if !memsetSuitable
            %%
            %if hasSymbolicWidth || %<outWidth> >= RollThreshold
              %assign loopCode = SLibEmitForLoopCounterCode(outWidth, "i")
              {
                %
                % {
                  %if localOut
                    %assign sigIndexer = SLibGet1DArrayIndexer(outWidth, "i", "", 0)
                    %assign lhsVarAccess = LibGetAddressOfFirstElement(...
                                             "localOut%<recIdx>", ...
                                             outNumDims) + sigIndexer
                    %assign lhs = lhsVarAccess
                    %if uIsComplex
                      %assign lhs = lhs + "." + tRealPart
                    %endif
                    %<lhs> = %<defaultInitialValue>;
                    %if uIsComplex
                      %assign lhs = lhsVarAccess + "." + tImagPart
                      %<lhs> = %<defaultInitialValue>;
                    %endif
                  %elseif extOutp.StorageClass == "Auto"
                    %<LibBlockDstSignalLocation("outportblk","i","",rPart)> = %<defaultInitialValue>;
                    %if uIsComplex
                      %<LibBlockDstSignalLocation("outportblk","i","",iPart)> = %<defaultInitialValue>;
                    %endif
                  %elseif extOutp.StorageClass == "ExportedGlobal"
                    %assign lhs = LibGetAddressOfFirstElement(...
                                    LibGetRecordIdentifier(extOutp), ...
                                    outNumDims)
                    %if uIsComplex
                      %<lhs>[i].%<tRealPart> = %<defaultInitialValue>;
                      %<lhs>[i].%<tImagPart> = %<defaultInitialValue>;
                    %else
                      %<lhs>[i] = %<defaultInitialValue>;
                    %endif
                  %endif
                }
              }
            %else %% if hasSymbolicWidth
              %foreach initIdx = %<outWidth>
                %if localOut
                  %assign sigIndexer = SLibGet1DArrayIndexer(%<outWidth>, "%<initIdx>", "", 0)
                  %assign lhsVarAccess = LibGetAddressOfFirstElement(...
                                           "localOut%<recIdx>", ...
                                           outNumDims) + sigIndexer
                  %assign lhs = lhsVarAccess
                  %if uIsComplex
                    %assign lhs = lhs + "." + tRealPart
                  %endif
                  %<lhs> = %<defaultInitialValue>;
                  %if uIsComplex
                    %assign lhs = lhsVarAccess + sigIndexer + "." + tImagPart
                    %<lhs> = %<defaultInitialValue>;
                  %endif
                %elseif extOutp.StorageClass == "Auto"
                  %<LibBlockDstSignalLocation("outportblk","%<initIdx>","",rPart)> = %<defaultInitialValue>;
                  %if uIsComplex
                    %<LibBlockDstSignalLocation("outportblk","%<initIdx>","",iPart)> = %<defaultInitialValue>;
                  %endif
                %elseif extOutp.StorageClass == "ExportedGlobal"
                  %assign lhs = LibGetAddressOfFirstElement(...
                                    LibGetRecordIdentifier(extOutp), ...
                                    outNumDims)
                  %if uIsComplex
                    %<lhs>[%<initIdx>].%<tRealPart> = %<defaultInitialValue>;
                    %<lhs>[%<initIdx>].%<tImagPart> = %<defaultInitialValue>;
                  %else
                    %<lhs>[%<initIdx>] = %<defaultInitialValue>;
                  %endif
                %endif
              %endforeach %%foreach initIdx =
            %endif %% if hasSymbolicWidth
          %else %% if !memsetSuitable
            %assign needMemset = TLC_TRUE
 
            %assign dtName = SLibGetRecordContainerBaseTypeName(extOutp)
            %if extOutp.StorageClass == "ExportedGlobal"
              %assign srcLoc = LibGetAddressOfFirstElement(...
                                 LibGetRecordIdentifier(extOutp), ...
                                 outNumDims) +"[0]"
            %else
              %assign srcLoc = LibBlockDstSignalLocation("outportblk","","",0)
            %endif
            %if hasSymbolicWidth
              %assign memsetWidth = "(" + outWidth + ")"
            %else
              %assign memsetWidth = "%<outWidth>U"
            %endif
            %if uIsComplex
              %assign memsetWidth = "2*%<memsetWidth>"
            %endif
            %assign sanitizedInitValue = ...
              FcnCastValueForMemsetUse(dTypeId, defaultInitialValue)
            (void) %<LibGenMemFcnCall("memset", "&%<srcLoc>", sanitizedInitValue, ...
              "%<memsetWidth>*sizeof(%<dtName>)")>;
          %endif
        %endif %%if outWidth == "1"
        %<ifEndCond>
      %else %% if AutoOrExportedGlobal
        %% Not AutoOrExportedGlobal, must be "Custom"
        %openfile customDataBuf
        %<SLibEmitLibCustomInitCode(extOutp, outWidth, LibGetRecordIsComplex(extOutp))>
        %closefile customDataBuf
        %if !WHITE_SPACE(customDataBuf)
            %<ifCond>
            %<customDataBuf>
            %<ifEndCond>
        %endif
      %endif %% if AutoOrExportedGlobal
    %endif %% skip ExternalOutput
  %endwith %% outportBlock
 
  %return memsetToZeroNeeded
%endfunction
 
 
%%Function:SLibInitExternalOutputsHelper===========================================
%%Abstract:
%%HelperforSLibInitExternalOutputs.Seethatfunctionfordetails.
%%toptester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%
%function SLibInitExternalOutputsHelper(usingStatic,localOut, fromSFcn, coderGroupVarGroupIdx) Output
  %assign isCoderGroupVarGroup = (coderGroupVarGroupIdx != -1)
  %assign useIRInitialization = UseIRModelInitCode && RootOutputInitInIR && !fromSFcn && !SLibAtleastOneOutputHasReusableCSCWithoutReuseBufferName() && !isCoderGroupVarGroup
 
  %% New IR Implementation
  %assign irInitBuffer = ""
  %if UseIRModelInitCode && RootOutputInitInIR
    %assign irInitBuffer = SLibDumpExternalOutputsInitializationCode(::CompiledModel.System[GetBaseSystemIdx()])
  %endif
 
  %openfile tlcInitBuffer
  %assign needMemsetToZero = TLC_FALSE
  %% When one or more inputs are classes, we should never use memset on whole outputs
  %assign forbidMemsetToZero = TLC_FALSE
  %% Old TLC Implementation
  %with ::CompiledModel.System[NumSystems-1]
    %if ::CompiledModel.NumModelOutputs > 0 && !SLibAutosarActive()
      %assign isCoderGroupVarGroup = (coderGroupVarGroupIdx != -1)
       
      %openfile NonMemsetBuffer
      %if isCoderGroupVarGroup
        %assign coderGroupVarGroup = ::CompiledModel.VarGroups.VarGroup[coderGroupVarGroupIdx]
        %assert coderGroupVarGroup.Category == "HierarchicalCoderData"
         
        %%loop through all outputs to see if any of them forbid use memset
        %foreach elIdx = coderGroupVarGroup.NumVarGroupElements
          %assign idnum = IDNUM(coderGroupVarGroup.VarGroupElements[elIdx])
          %assign recType = idnum[0]
          %if recType == "Y"
            %assign recIdx = idnum[1]
            %assign extOutp = ::CompiledModel.ExternalOutputs.ExternalOutput[recIdx]
            %if SLibShouldForbidMemsetToZeroForRecord(extOutp)
              %assign forbidMemsetToZero = TLC_TRUE
            %endif
          %endif
        %endforeach
         
        %foreach elIdx = coderGroupVarGroup.NumVarGroupElements
          %assign idnum = IDNUM(coderGroupVarGroup.VarGroupElements[elIdx])
          %assign recType = idnum[0]
          %if recType == "Y"
            %assign recIdx = idnum[1]
            %assign extOutp = ::CompiledModel.ExternalOutputs.ExternalOutput[recIdx]
            %if !SLibDataRecordIsInCoderGroup(extOutp)
              %continue
            %endif
            %assign ret = SLibInitExternalOutputRecord(localOut, fromSFcn, recIdx, useIRInitialization, forbidMemsetToZero)
            %if ret
              %assign needMemsetToZero = TLC_TRUE
            %endif
          %endif
        %endforeach
      %else
        %%loop through all outputs to see if any of them forbid use memset
        %foreach idx = ::CompiledModel.ExternalOutputs.NumExternalOutputs
          %assign extOutp = ::CompiledModel.ExternalOutputs.ExternalOutput[idx]
          %if SLibShouldForbidMemsetToZeroForRecord(extOutp)
            %assign forbidMemsetToZero = TLC_TRUE
          %endif
        %endforeach
         
        %foreach idx = ::CompiledModel.ExternalOutputs.NumExternalOutputs
          %assign extOutp = ::CompiledModel.ExternalOutputs.ExternalOutput[idx]
            %if SLibDataRecordIsInCoderGroup(extOutp)
              %continue
            %endif
            %% emxArray is initialized in code generation IR. We don't do it here.
            %if LibCGTypeIsEmxArray(extOutp.CGTypeIdx) && extOutp.HasVarDims == 1
              %continue
            %endif
          %assign ret = SLibInitExternalOutputRecord(localOut, fromSFcn, idx, useIRInitialization, forbidMemsetToZero)
          %if ret
            %assign needMemsetToZero = TLC_TRUE
          %endif
        %endforeach
      %endif
      %closefile NonMemsetBuffer
 
      %if needMemsetToZero
        %% For coder groups, we memset in ertlib.tlc:SLibDumpERTAndModelrefInitMemoryCode(...)
        %% which is why we do not memset here
        %if !isCoderGroupVarGroup
          %assign initAddr = (YQualifier == "." ? "&" : "") +...
            LibGetExternalOutputStruct()
          (void) %<LibGenMemFcnCall("memset", "(void *)" + initAddr, ...
            " 0", " sizeof(%<tOutputType>)")>;
        %endif
      %endif
      %%
      %if !WHITE_SPACE(NonMemsetBuffer)
        %<NonMemsetBuffer>
      %endif
    %endif
  %endwith %% System[NumSystems-1]
   
  %closefile tlcInitBuffer
   
  %assign retBuffer = ["", 0]
  %assign retBuffer[0] = useIRInitialization ? ...
    irInitBuffer + "/n" + tlcInitBuffer : ...
    tlcInitBuffer
  %assign retBuffer[1] = needMemsetToZero
   
  %return retBuffer
%endfunction %% SLibInitExternalOutputsHelper
 
%%Function:SLibInitExternalOutputs===========================================
%%Abstract:
%%Initializetheexternaloutputsstructure(ie.withinternalstorage,not
%%includingexternaloutputswithexternalstorage,whichshouldbecovered
%%byBlockIO)
%function SLibInitExternalOutputs(usingStatic,localOut, fromSFcn) Output
  %assign ret = SLibInitExternalOutputsHelper(usingStatic,localOut, fromSFcn, -1)
  %assign initBuffer = ret[0]
  %<initBuffer>/
%endfunction %% SLibInitExternalOutputs
   
%%ItissimplerthanSLibInitExternalOutputsbecause
%%-Externaloutportcannothavestorageclass.
%%-FcnConditionRootOutputsAsSeparateArgscannotbetrue
%%forVarDims(FPCisnotsupportedyet)
%%thusthereisnoneedtoconsiderlocalOut
%%TopTester:test/toolbox/simulink/variants/inlineVariants/ivGeneral/tIVfcnCall_neg.m-
%%
%function SLibInitExternalOutputSizes() Output
  %with ::CompiledModel.System[NumSystems-1]
  %if ::CompiledModel.NumModelOutputs > 0 && ...
    !SLibAutosarActive()
    %% initialize root outport for auto.
    %foreach idx = ::CompiledModel.ExternalOutputs.NumExternalOutputs
      %assign extOut = ::CompiledModel.ExternalOutputs.ExternalOutput[idx]
      %if ISFIELD(extOut, "SizeVarGroupIdx")
        %assert ISFIELD(extOut, "HasVarDims")
        %assign sizeTypeIdx = SLibCGVarGroupMemberCGTypeIdx(...
          extOut.SizeVarGroupIdx[0], ...
          extOut.SizeVarGroupIdx[1])
        %assign sizeVecLen = LibCGTypeWidth(sizeTypeIdx)
        %foreach dimIdx = sizeVecLen
          %<SLibGetOutportSize(idx, sizeVecLen, "", -1, "", dimIdx)> = ...
            %<SLibGetDefaultInitialValueByCGTypeIdx(...
            sizeTypeIdx, tRealPart)>;
        %endforeach
      %endif
    %endforeach
  %endif
  %endwith %% System[NumSystems-1]
%endfunction
 
%%Function:FcnAddSharedDataInitProtection====================================
%%Abstract:
%%Preventre-initializationofsharedlocaldatastores.
%%
%function FcnAddSharedDataInitProtection(dwRec, vcRecord) void
  %if (dwRec.SharedLocalDSM && SLibMultiInstance())
    %assign hasBeenInitId = SLibGetDataStoreForHasBeenInitIdentifier()
    %assign vcRecord.ifCond = vcRecord.ifCond + "/n if (!%<hasBeenInitId>) {"
    %assign vcRecord.endIfCond = "}/n" + vcRecord.endIfCond
  %endif
  %return vcRecord
%endfunction
   
%%Function:FcnInitStatesWithExternalStorage==================================
%%Abstract:
%%HelperfunctiontoInitializethestateswithexternalstorageclass
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%TopTester:test/toolbox/simulink/variants/tVariantGecks.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmg1396738_inlined_VC1.m
%%TopTester:test/toolbox/simulink/variants/tVariantGecks6.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmFunctionCallSplitBlock_hidden_VC1.m
%%
%function FcnInitStatesWithExternalStorage(sc, comment, fieldsep, addressof, deref) void
  %openfile rtnBuffer
  %foreach dwIdx = ::CompiledModel.DWorks.NumDWorks
    %assign dwRec = ::CompiledModel.DWorks.DWork[dwIdx]
    %if SLibOmitRecord(dwRec) || 1 == dwRec.IsLocalScratchDWork
      %continue
    %endif
    %assign id = LibGetRecordIdentifier(dwRec)
    %assign symbolicWidth = LibGetRecordSymbolicWidth(dwRec)
    %assign hasSymbolicWidth = LibRecordHasSymbolicWidth(dwRec)
 
    %if FcnIsNotInterfaceableStorageClassCheck(dwRec)
      %continue
    %endif
    %if !SLibWriteOutInstForSignalRec(dwRec)
      %continue
    %endif
    %assign dTypeId = SLibGetRecordDataTypeId(dwRec)
    %if !ISEMPTY(SLibDataTypeConstructFcnName(dTypeId))
      %continue
    %endif
    %with dwRec
      %% Skip zero initialization for shared data initialized flag
      %if dwRec.SharedLocalDSMForHasBeenInit
        %continue
      %endif
      %assign vcRecord = SLibGetDataInlineVariantNetConditions(dwRec)
      %assign vcRecord = FcnAddSharedDataInitProtection(dwRec, vcRecord)
      %% TopTester: test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmIV_CSCDataPlacement.m
      %assign ifCond = vcRecord.ifCond
      %assign ifEndCond = vcRecord.endIfCond
   
      %%
      %% Standalone subsystems cache separately
      %assign stdSSIdx = -1
      %assign sysIdx = StandaloneParentSysIdxOfDataRec(dwRec)
      %if sysIdx == -1 && FcnIsFileScopeCustomStorageCheck(dwRec)
        %assign sysIdx = FcnGetNonRootFileFunctionOwner(dwRec, sysIdx)
      %endif
      %if sysIdx != -1
        %assign stdSSIdx = sysIdx
        %assign stdSSBuffer = ""
      %endif
      %if StorageClass != sc
        %%
        %% Skip those records whose StorageClass not as specified in sc
        %%
        %continue
        %%
      %endif
      %%
      %if StorageClass == "Custom"
        %%
        %% For custom storage class, call "initialize" in its .tlc
        %%
        %% Note that custom storage class .tlc itself should check
        %% remove zero initialization option
        %%
        %openfile initCode
        %<SLibEmitLibCustomInitCode(dwRec, symbolicWidth, SLibDWorkIsComplex(dwRec))>
        %if SLibIsAuxBufferForReusableCSC(dwRec)
          %assign tempId = dwRec.Identifier
          %assign dwRec.Identifier = dwRec.ReuseBufferName
          %% Need to generate initialization code for the dwork reuse buffer
          %<SLibEmitLibCustomInitCode(dwRec, symbolicWidth, SLibDWorkIsComplex(dwRec))>
          %assign dwRec.Identifier = tempId
        %endif
        %closefile initCode
        %if !WHITE_SPACE(initCode)
          %if stdSSIdx != -1
            %% cache output to tmpBuffer, no %continue until %closefile
            %openfile tmpBuffer
          %endif
          %<ifCond>
          %<initCode>
          %<ifEndCond>
          %if stdSSIdx != -1
            %closefile tmpBuffer
            %assign stdSSBuffer = stdSSBuffer + tmpBuffer
          %endif
        %endif
      %else
        %%
        %% For any other external storage, use its default initial value
        %%
        %% Check remove zero initialization option
        %if SLibRemoveZeroInitForDataDefault(dwRec)
          %continue
        %endif
        %%
        %if stdSSIdx != -1
          %% cache output to tmpBuffer, no %continue until %closefile
          %openfile tmpBuffer
        %endif
        %<ifCond>
        %if LibIsDataTypeMultiWordFixpt(dTypeId)
          %assign defaultInitialValue = LibGetGroundName(dwRec, tRealPart)
        %else
          %assign defaultInitialValue = SLibGetDefaultInitialValue(dwRec, tRealPart)
        %endif
 
        %%
        %assign memsetSuitable = FcnSuitableForMemset(defaultInitialValue, dTypeId, "")
        %%
 
        %if symbolicWidth == "1"
          %% scalar case
          %if SLibDWorkIsComplex(dwRec)
            %<id>%<fieldsep>%<tRealPart> = %<defaultInitialValue>;
            %<id>%<fieldsep>%<tImagPart> = %<defaultInitialValue>;
          %else
            %<deref>%<id> = %<defaultInitialValue>;
          %endif
        %elseif !memsetSuitable
          %%
          %if hasSymbolicWidth || %<symbolicWidth> >= RollThreshold
            %assign loopCode = SLibEmitForLoopCounterCode(symbolicWidth, "i")
            {
              %
              % {
                %if SLibDWorkIsComplex(dwRec)
                  %<id>[i]%<fieldsep>%<tRealPart> = %<defaultInitialValue>;
                  %<id>[i]%<fieldsep>%<tImagPart> = %<defaultInitialValue>;
                %else
                  %<deref>%<id>[i] = %<defaultInitialValue>;
                %endif
              }
            }
          %else
            %foreach initIdx = %<symbolicWidth>
              %if SLibDWorkIsComplex(dwRec)
                %<id>[%<initIdx>]%<fieldsep>%<tRealPart> = %<defaultInitialValue>;
                %<id>[%<initIdx>]%<fieldsep>%<tImagPart> = %<defaultInitialValue>;
              %else
                %<deref>%<id>[%<initIdx>] = %<defaultInitialValue>;
              %endif
            %endforeach
          %endif
        %else
          %% non-float vector case
          %if hasSymbolicWidth
            %assign memsetWidth = "(" + symbolicWidth + ")"
          %else
            %assign memsetWidth = "%<symbolicWidth>U"
          %endif
          %if SLibDWorkIsComplex(dwRec)
            %assign memsetWidth = "2*%<memsetWidth>"
          %endif
          %assign dtName = SLibGetRecordContainerBaseTypeName(dwRec)
          %assign sanitizedInitValue = ...
            FcnCastValueForMemsetUse(dTypeId, defaultInitialValue)
          (void) %<LibGenMemFcnCall("memset", "%<addressof>%<id>", ...
            sanitizedInitValue, "%<memsetWidth>*sizeof(%<dtName>)")>;
        %endif
        %<ifEndCond>
        %if stdSSIdx != -1
          %closefile tmpBuffer
          %assign stdSSBuffer = stdSSBuffer + tmpBuffer
        %endif
      %endif
      %if stdSSIdx != -1 && !WHITE_SPACE(stdSSBuffer)
        %<LibAddToSystemField(System[stdSSIdx],"TempInitBuffer",...
          stdSSBuffer)>
      %endif
    %endwith
  %endforeach
  %closefile rtnBuffer
   
  %% Cache standalone subsystem initialization
  %<FcnCacheStandaloneSubsyInitFromTempBuffers(comment)>
 
  %% Cache root model initialization
  %if !WHITE_SPACE(rtnBuffer)
    %return "/n" + comment + "/n" + rtnBuffer
  %else
    %return ""
  %endif
%endfunction %% FcnInitStatesWithExternalStorage
 
%%Function:SLibInitStatesWithExternalStorage=================================
%%Abstract:
%%Initializethestateswithexternalstorageclass
%%
%function SLibInitStatesWithExternalStorage(usingStatic) Output
  %%
  %% Exported global states
  %%
  %if !SLibExportedGlobalDWorkIsEmpty()
    %<FcnInitStatesWithExternalStorage("ExportedGlobal", ...
      "/* exported global states */", ".", "&", "")>
  %endif
  %%
  %% Custom states
  %%
  %if !SLibCustomDataBufferIsEmpty("Definitions")
    %<FcnInitStatesWithExternalStorage("Custom", ...
      "/* custom states */", ".", "&", "")>
  %endif
%endfunction %% SLibInitStatesWithExternalStorage
 
 
%%Function:CacheStandaloneSystemDWorkInfo=====================================
%%Abstract:
%%Thisisahelperfunctionfordumpingdworkinitialization.
%%Thisfunctionreturnsarecord.Therecordconsistsofanarrayofrecords.
%%Therootsystemandeachstandalonesubsystemhasanentryinthisrecord.
%%WhileloopingthroughtheSystems,wewilladd
%%IndexInStandaloneSubsystemArraytotherootsystemandeachstandalone
%%system.Rootsystemhas0-thindex.
%%
%%Notethattherecordispartiallypopulated.
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Inport/rtw/tInportStringSupport.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants3.m
%%
%function CacheStandaloneSystemDWorkInfo()
  %assign counter = 0
  %assign rootSSIdx = GetBaseSystemIdx()
  %assign totalNumSys = GetNumSystemsForCodeGen()
   
  %% standalone subsystem buffer
  %createrecord stdSSBuf {}
  
  %foreach sysIdx = totalNumSys
    %% Root or standalone subsystem (root will have 0th group index)
    %assign thisIdx = totalNumSys - 1 - sysIdx
     
    %if thisIdx == rootSSIdx || System[thisIdx].StandaloneSubsystem
      %if !(ISFIELD(System[thisIdx], "IndexInStandaloneSubsystemArray"))
        %addtorecord System[thisIdx] IndexInStandaloneSubsystemArray counter
      %endif
      %addtorecord stdSSBuf DWorkBuff { ...
        SystemIdx %<thisIdx>; ...
        DWorkType ""; ...
        DWorkVar ""; ...
        haveFloat 0; ...
        needMemset 0; ...
        forbidMemset 0; ...
        initBuffer ""; ...
        emitMsgInit 0; ...
        msgInitBuffer "" ...
        emitStringInit 0; ...
        stringInitBuffer "" ...
      }
       
      %if IsModelReferenceTarget() && (! GenerateClassInterface)
        %assign baseSystem = ::CompiledModel.System[GetBaseSystemIdx()]
        %assign varGroupType = FcnSysVarGroupType(baseSystem,"DWork")
        %assign stdSSBuf.DWorkBuff[counter].DWorkType = varGroupType
        %if IsModelRefScalableBuild()
          %assign stdSSBuf.DWorkBuff[counter].DWorkVar = ...
            FcnSysVarGroupNonreusedName(baseSystem, "DWork")
        %else
          %assign stdSSBuf.DWorkBuff[counter].DWorkVar = "localDW"
        %endif
      %elseif IsModelReferenceTarget() && GenerateClassInterface
        %assign stdSSBuf.DWorkBuff[counter].DWorkType = "%<::tDWorkType>"
        %assign stdSSBuf.DWorkBuff[counter].DWorkVar = "%<::tDWork>"
      %elseif thisIdx == rootSSIdx
        %assign stdSSBuf.DWorkBuff[counter].DWorkType = "%<::tDWorkType>"
        %assign stdSSBuf.DWorkBuff[counter].DWorkVar = "%<LibGetDWorkStruct()>"
      %else
        %assign varGroupType = FcnSysVarGroupType(System[thisIdx],"DWork")
        %assign stdSSBuf.DWorkBuff[counter].DWorkType = varGroupType
        %assign stdSSBuf.DWorkBuff[counter].DWorkVar = ...
          FcnSysVarGroupNonreusedName(System[thisIdx],"DWork")
      %endif
      %assign counter = counter+1
    %endif
  %endforeach
   
  %% If this is a model reference, then counter should be 1
  %% A -> B is equivalent to (!A) || B
  %assert((! IsModelReferenceTarget()) || (counter == 1))
   
  %return stdSSBuf
%endfunction
 
 
%%FunctionSLibGetExtUIdentifier(extInpRec,idx,reim)
%%Abstract:
%%Getinportvariablename
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Inport/rtw/tInportStringSupport.m
%%
%function SLibGetExtUIdentifier(extInp, idx, reim)
  %%
  %if extInp.StorageClass == "Auto"
    %assign varName = "%<LibGetExternalInputStruct()>%<UQualifier>%<LibGetRecordIdentifier(extInp)>"
  %elseif extInp.StorageClass == "ExportedGlobal" || extInp.StorageClass == "ImportedExtern"
    %assign varName = LibGetRecordIdentifier(extInp)
  %elseif extInp.StorageClass == "ImportedExternPointer"
    %assign varName = "(*%<LibGetRecordIdentifier(extInp)>)"
  %endif
  %%
  %assign width = LibGetRecordWidth(extInp)
  %if width != 1
    %assign varName = "%<varName>[%<idx>]"
  %endif
  %if LibGetRecordIsComplex(extInp)
    %assign varName = "%<varName>."
  %elseif reim == "im"
    %assign errTxt = "Try to generate complex variable name but Inport block is set to accept real signal"
    %<LibReportFatalError(errTxt)>
  %else
    %assign reim =""
  %endif
  %assign varName = "%<varName>%<reim>"
  %return varName
%endfunction %% SLibGetExtUIdentifier
 
 
%%Function:LocalInitDworkVector==============================================
%%Abstract:
%%Doesnotcheckremovezeroinitializationoption.Callershoulddothat.
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants_crossfeature.m
%%
%function LocalInitDworkVector(stdSSBuf, stdIdx, ...
  initCount, name, initValue, isComplex, ppIf, ppFi, ...
  aNdContainerTypeIdx) void
   
  %assert TYPE(initCount) == "String"
  %assign twoParts = IDNUM(initCount)
  %assign isSymbolic = !ISEMPTY(twoParts[0])
 
  %assign dWorkAccess = name
  %if aNdContainerTypeIdx >= 0
    %% If multi-dimensional container type index was provided. Then
    %% we need to create a reference to the first element; e.g.,
    %% (&dWorkVar[0][0])[i] = 0; // See g1835844 for details.
    %assign dWorkNumDims = LibCGTypeNumDimensions(aNdContainerTypeIdx)
    %assign dWorkAccess = LibGetAddressOfFirstElement(name, dWorkNumDims)
  %endif
   
  %openfile tmpBuf
  %<ppIf>
  %if "%<initCount>" == "1"
    %if %<isComplex>
      %<name>.%<tRealPart> = %<initValue>;
      %<name>.%<tImagPart> = %<initValue>;
    %else
      %<name> = %<initValue>;
    %endif
  %elseif isSymbolic || %<initCount> >= RollThreshold
    %% use a loop
    %assign loopCode = SLibEmitForLoopCounterCode(initCount, "i")
    {
      %
      % {
        %if %<isComplex>
          %<dWorkAccess>[i].%<tRealPart> = %<initValue>;
          %<dWorkAccess>[i].%<tImagPart> = %<initValue>;
        %else
          %<dWorkAccess>[i] = %<initValue>;
        %endif
      }
    }
  %else
    %% do not use loop
    %foreach initIdx = %<initCount>
      %if %<isComplex>
        %<dWorkAccess>[%<initIdx>].%<tRealPart> = %<initValue>;
        %<dWorkAccess>[%<initIdx>].%<tImagPart> = %<initValue>;
      %else
        %<dWorkAccess>[%<initIdx>] = %<initValue>;
      %endif
    %endforeach
  %endif
  %<ppFi>
  %closefile tmpBuf
 
  %% Add the initialization code to the right buffer
  %assign stdSSBuf.DWorkBuff[stdIdx].initBuffer = ...
    stdSSBuf.DWorkBuff[stdIdx].initBuffer + tmpBuf
   
  %return stdSSBuf
%endfunction
 
%%TopTester:test/toolbox/simulink/blocks/CPPCodeGen/tsmlk_core_cpp_coverage.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/ivGeneral/tGotoFromWithVariableConditions.m
%%
%function SLibInitDWorkHelper(stdSSBuf, stdIdx, sysIdx, cross, dwRec, ignoreInitInStart, ppIf, ppFi) void
   
  %%
  %if dwRec.StorageClass != "Auto" || SLibOmitRecord(dwRec) ...
    || 1 == dwRec.IsLocalScratchDWork
    %return stdSSBuf
  %endif
   
  %% If Simulink Messages storage id dwork, then leave the initialization
  %if ISFIELD(dwRec,"Name") && FEVAL("strncmp", dwRec.Name, "msgQid", 6) ...
        && !::CompiledModel.MsgUsingIRBasedCG
    %assign stdSSBuf.DWorkBuff[stdIdx].emitMsgInit = 1
    %%assign stdSSBuf.DWorkBuff[stdIdx].initialValue = dwRec.InitalValue
    %assign qname = SLibCG_GetVarGroupElementPath(dwRec.VarGroupIdx,...
      sysIdx, cross)
    %assign isComplex = SLibDWorkIsComplex(dwRec)
    %assign msgStorageId = dwRec.InitialValue
    %openfile tBuf
    %if IsModelReferenceSimTarget() && ::CompiledModel.MessageModelRefSupport
      %assign simstruct = RTMGet("MdlRefSfcnS")
      %<qname> = slmsg_ssGetMsgQueueId(%<simstruct>, %<msgStorageId>);
    %else
      %<qname> = %<msgStorageId>;
    %endif
    %closefile tBuf
     
    %% Add the initialization code to the right buffer
    %assign stdSSBuf.DWorkBuff[stdIdx].msgInitBuffer = ...
      stdSSBuf.DWorkBuff[stdIdx].msgInitBuffer + tBuf
  %endif
 
  %%
  %assign DataTypeIdx = SLibDWorkDataTypeId(dwRec)
  %assign dwWidth = SLibDWorkWidth(dwRec)
  %assign curDataTypeId = LibGetDataTypeIdAliasedThruToFromId(DataTypeIdx)
 
  %% Initialize string (including string elements in bus) for dworks in generated C code in
  %% * model reference sim target
  %% * rapid accelerator
  %if IsModelReferenceSimTarget() || ::isRAccel
    %if LibIsStringDataType(curDataTypeId) || LibIsStructDataType(curDataTypeId)
      %% Initialize string dwork for model reference sim target
      %assign name = SLibCG_GetVarGroupElementPath(dwRec.VarGroupIdx, sysIdx, cross)
 
      %openfile tBuf
      %<SlibInitStringData(curDataTypeId, name, dwWidth)>
      %closefile tBuf
 
      %if !ISEMPTY(tBuf)
        %assign stdSSBuf.DWorkBuff[stdIdx].emitStringInit = 1
        %assign stdSSBuf.DWorkBuff[stdIdx].stringInitBuffer = stdSSBuf.DWorkBuff[stdIdx].stringInitBuffer + tBuf
      %endif
    %endif
  %endif
   
  %% InitialValue is not provided. Use default initial value then.
  %if SLibRemoveZeroInitForDataDefault(dwRec)
    %return stdSSBuf
  %endif
 
  %%
  %assign curMemsetToZeroSuffice = FcnMemsetToZeroInitSuffice(curDataTypeId)
  %if curMemsetToZeroSuffice && !stdSSBuf.DWorkBuff[stdIdx].forbidMemset
    %if SLibZeroMemory("DWork")
      %assign stdSSBuf.DWorkBuff[stdIdx].needMemset = 1
    %endif
    %% We know we can ignore this one. Memset has taken care of it. Go get next one.
    %return stdSSBuf
  %endif
     
  %if (curDataTypeId == tSS_DOUBLE || curDataTypeId == tSS_SINGLE)
    %if InitFltsAndDblsToZero
      %if ignoreInitInStart || !dwRec.InitInStart
        %% Need to set floating-point dworks explicitly to 0.0
        %% Lifted from FcnGetDWorkIdentifier
        %assign name = SLibCG_GetVarGroupElementPath(dwRec.VarGroupIdx, ...
          sysIdx, cross)
        %assign initCount = LibGetRecordSymbolicWidth(dwRec)
        %assign isComplex = SLibDWorkIsComplex(dwRec)
        %assign defaultInitialValue = SLibGetDefaultInitialValueFromId(DataTypeIdx)
        %%
        %assign stdSSBuf.DWorkBuff[stdIdx].haveFloat = 1
 
        %assign dWorkContainerTypeIdx = -1
        %if SLibIsContainerCGTypeND(dwRec)
          %assign dWorkContainerTypeIdx = dwRec.ContainerCGTypeIdx
        %endif
 
        %% Need to see if this is an RWORK substructure, in which case we need an inner loop
        %assign block = System[dwRec.SigSrc[0]].Block[dwRec.SigSrc[2]]
        %with block
          %if (dwRec.Origin == "RWORK") && (NumRWorkDefines > 0)
            %foreach initIdx = NumRWorkDefines
              %assign fieldname = name + ".%"
              %assign initCount = "%"
              %assign stdSSBuf = LocalInitDworkVector(stdSSBuf, stdIdx, ...
                initCount, fieldname, defaultInitialValue, isComplex, ...
                ppIf, ppFi, dWorkContainerTypeIdx)
            %endforeach
            %return stdSSBuf
          %endif
        %endwith
         
        %assign stdSSBuf = LocalInitDworkVector(stdSSBuf, stdIdx, ...
          initCount, name, defaultInitialValue, isComplex, ppIf, ppFi, ...
          dWorkContainerTypeIdx)
      %endif
    %elseif SLibZeroMemory("DWork") && !stdSSBuf.DWorkBuff[stdIdx].forbidMemset
      %assign stdSSBuf.DWorkBuff[stdIdx].needMemset = 1
    %endif
  %elseif SLibZeroMemory("DWork") && !stdSSBuf.DWorkBuff[stdIdx].forbidMemset
    %assign stdSSBuf.DWorkBuff[stdIdx].needMemset = 1
  %endif
  %return stdSSBuf
%endfunction
 
 
%%Function:SLibInitDWork=====================================================
%%Abstract:
%%InitializeDWorkstructure(ie.thosewithinternalstorage)tozero
%%MemsetentireDWorkstructureto0ifnon-floatingelementsexist.
%%Assigndoubleandsinglefloating-pointelementsto0.0
%%
%%Thisfunctionreturnsvectorwiththreevalues[numeric,numeric,string]:
%%haveFloat-foundatleastonefloating-pointregion
%%needMemset-foundatleastonenon-floating-pointregion
%%initBuffer-bufferwithfloating-pointassignmentsto0.0
%%
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortFcnCall.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSink/tmSingleVarSink2_VC1.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/codeGen/tg1375551.m
%%
%function SLibInitDWork(stdSSBuf) void
  %if ForceBlockIOInitOptimize
    %% Choosing this option may result in code that is not MISRA-C compliant.
    %assert(!IsModelReferenceTarget())
    %assign stdSSBuf = SLibInitDWorkOld(stdSSBuf)
    %return stdSSBuf
  %endif
   
  %%loop through all dwork records, mark the ones that forbid to use memset
  %foreach dwIdx = ::CompiledModel.DWorks.NumDWorks
    %assign dwRec = ::CompiledModel.DWorks.DWork[dwIdx]
    %% The skipped ones should not affect forbidMemset
    %if SLibOmitRecord(dwRec) || 1 == dwRec.IsLocalScratchDWork
      %continue
    %endif
    %if dwRec.SharedLocalDSMForHasBeenInit
      %continue
    %endif
    %% Skip this as well for now to preserve the behavior, should not need this
    %if (ISFIELD(dwRec, "UseAccessFunctions") && dwRec.UseAccessFunctions == 1) || ...
      SLibDataRecordIsInCoderGroup(dwRec)
      %continue
    %endif
     
    %%get the corresponding standalone index
    %assign idx = SLibGetSystemAndCallSideIndex(dwRec)
    %if SigSrcLivesInStandaloneSS(idx)
      %assign baseSystemIdx = StandaloneParentSysIdxOfDataRec(dwRec)
    %else
      %assign baseSystemIdx = GetBaseSystemIdx()
    %endif
    %assign stdIdx = System[baseSystemIdx].IndexInStandaloneSubsystemArray
     
    %%check for class type, containing this will forbig memset for a whole DWorkBuff
    %assign DataTypeIdx = SLibDWorkDataTypeId(dwRec)
    %if SLibShouldForbidMemsetToZeroForRecord(dwRec) || LibIsDataTypeMessage(DataTypeIdx) || ...
    CGMODEL_ACCESS("CGModel.isGpuCodeGen") == TLC_TRUE
      %assign stdSSBuf.DWorkBuff[stdIdx].forbidMemset = 1
    %endif
  %endforeach
   
   
  %foreach dwIdx = ::CompiledModel.DWorks.NumDWorks
    %assign dwRec = ::CompiledModel.DWorks.DWork[dwIdx]
    %if SLibOmitRecord(dwRec) || 1 == dwRec.IsLocalScratchDWork
      %continue
    %endif
    %% Skip zero initialization for shared data initialized flag
    %if dwRec.SharedLocalDSMForHasBeenInit
      %continue
    %endif
    %if (ISFIELD(dwRec, "UseAccessFunctions") && dwRec.UseAccessFunctions == 1) || ...
      SLibDataRecordIsInCoderGroup(dwRec)
      %continue
    %endif
    %assign idx = SLibGetSystemAndCallSideIndex(dwRec)
    %if SigSrcLivesInStandaloneSS(idx)
      %assign baseSystemIdx = StandaloneParentSysIdxOfDataRec(dwRec)
    %else
      %assign baseSystemIdx = GetBaseSystemIdx()
    %endif
    %assign cross = System[baseSystemIdx].CrossNoArgFcnBound
     
    %assign vcRecord = SLibGetDataInlineVariantNetConditions(dwRec)
    %assign vcRecord = FcnAddSharedDataInitProtection(dwRec, vcRecord)
    %assign ifCond = vcRecord.ifCond
    %assign ifEndCond = vcRecord.endIfCond
 
    %assign stdIdx = System[baseSystemIdx].IndexInStandaloneSubsystemArray
 
    %assign stdSSBuf = SLibInitDWorkHelper(stdSSBuf, stdIdx, baseSystemIdx, cross, dwRec, TLC_FALSE, ifCond, ifEndCond)
  %endforeach
   
  %if stdSSBuf.DWorkBuff[0].needMemset && !SLibIsSelfStructured()
    %assign baseSystemIdx = GetBaseSystemIdx()
    %<SLibAccessArgHelper(System[baseSystemIdx].Interface.DWorkArgDef,"","")>
  %endif
  %% SLibGetDataLayout above took care of LibAccessArg for what's in initBuffer
  %return stdSSBuf
 
%endfunction %% SLibInitDWork
 
 
%%Function:SLibMemsetDWorkInSelf============================================
%%Abstract:
%%Memsetdworkfieldinselfstructs(includingmodelself,i.e.RTMand
%%subsystemself)
%%
%function SLibMemsetDWorkInSelf() void
  %assert SLibIsSelfStructured()
  %assign selfCoderGroupIdx = SLibGetSelfCoderDataGroupIndex()
  %assign selfCoderGroup = ::CompiledModel.CoderDataGroup[selfCoderGroupIdx]
  %if !selfCoderGroup.IsSynthesized
    %% Skip user-defined self since it doesn't nest dwork into it.
    %return ""
  %endif
  %openfile tempBuf
  %if (!(ForceBlockIOInitOptimize && IsModelReferenceTarget()) && ...
    !GenerateClassInterface)
    %assign numSys = GetNumSystemsForCodeGen()
    %assign baseSysIdx = GetBaseSystemIdx()
    %assign numDWorks = ::CompiledModel.DWorks.NumDWorks
    %foreach sysIdx = numSys
      %assign currSys = System[sysIdx]
      %assign currModIdx = currSys.CGIRModuleIdx
      %assign currMod = ::CompiledModel.RTWCGModules.RTWCGModule[currModIdx]
      %if !currMod.SimplifiedInterface
        %continue %% Skip non-simplified interface subsystems which don't use self
      %endif
      %if ISFIELD(currSys, "DWorkVarGroupIndex")
        %assign dwVGIdx = currSys.DWorkVarGroupIndex[0]
        %assert dwVGIdx >= 0
        %assign dwVarGroup = ::CompiledModel.VarGroups.VarGroup[dwVGIdx]
 
        %% Make sure the DWork vargroup's parent is a self vargroup
        %assign dwParentIdx = dwVarGroup.ParentVarGroupIdx
        %assert dwParentIdx >= 0
        %assign dwParentVG = ::CompiledModel.VarGroups.VarGroup[dwParentIdx]
        %assert (dwParentVG.Category == "HierarchicalCoderData" && ...
          dwParentVG.CoderDataGroupIndex == selfCoderGroupIdx)
 
        %assign dwRec = ""
        %assign needMemset = TLC_FALSE
        %foreach dwIdx = numDWorks
          %assign currDWRec = ::CompiledModel.DWorks.DWork[dwIdx]
          %if ISFIELD(currDWRec, "VarGroupIdx") && currDWRec.VarGroupIdx[0] == dwVGIdx
            %if ISEMPTY(dwRec)
              %assign dwRec = currDWRec %% Use the first dwRec to get variant condition
            %endif
            %assign dtypeIdx = SLibDWorkDataTypeId(currDWRec)
            %assign curDataTypeId = LibGetDataTypeIdAliasedThruToFromId(dtypeIdx)
            %assign curMemsetToZeroSuffice = FcnMemsetToZeroInitSuffice(curDataTypeId)
            %if curMemsetToZeroSuffice && !SLibOmitRecord(currDWRec)
              %assign needMemset = TLC_TRUE
            %endif
 
            %% Verify that matrix type elements are correctly initialized
            %if LibCGTypeIsMatrix(dwVarGroup.CGTypeIdx) && !currDWRec.InitInStart
              %% do not report error for certain dworks
              %if currDWRec.Name == "sysIdxToRun"
                %continue
              %endif
              %<LibReportFatalError("Should not be here. Matrix type not handled")>
            %endif
          %endif
        %endforeach
 
        %if !needMemset
          %continue
        %endif
 
        %if !ISEMPTY(dwRec)
          %assign vcRecord = SLibGetDataInlineVariantNetConditions(dwRec)
        %else
          %assign vcRecord = SLibVariantConditionRecord()
        %endif
 
        %assign dwCGTypeIdx = dwVarGroup.CGTypeIdx
        %assign dwType = LibCGTypeName(dwCGTypeIdx)
 
        %if LibCGTypeIsMatrix(dwCGTypeIdx)
          %continue %% For matrix type, dwork init should already be emitted through IR
        %endif
 
        %% Build up path to the DWork VarGroup
        %assign path = SLibCGIRVarGroupPath(dwParentIdx, baseSysIdx, currSys.CrossNoArgFcnBound)
        %assign dworkAddr = "&(%<path>%<dwVarGroup.Name>)"
        %assign sizeExpr = " sizeof(%<dwType>)"
 
        %if vcRecord.hasConds
          %<vcRecord.ifCond>
        %endif
        (void) %<LibGenMemFcnCall("memset", ...
          "(void *) " + "%<dworkAddr>", ...
          " 0", "%<sizeExpr>")>;
        %if vcRecord.hasConds
          %<vcRecord.endIfCond>
        %endif
      %endif
    %endforeach
  %endif
  %closefile tempBuf
  %return tempBuf
%endfunction
 
 
%%Function:SLibDumpModelDataInitialization===================================
%%Abstract:
%%Dumpalldatainitializationformodel.
%%
%%TopTester:test/toolbox/simulink/variants/string/tStringSupport.m
%%TopTester:test/toolbox/simulink/blocks/sb2sl/tsb2slmdlref.m
%%TopTester:test/toolbox/simulink/variants/defaultVariants/tDefaultVariants2.m
%%
%function SLibDumpModelDataInitialization() Output
  %%
  %% Combine DWork and BlockIO is a Embedded Coder feature and not expected to
  %% be enabled for Simstruct based targets (such as RSIM and Accelerator).
  %%
  %assert !::CompiledModel.DWorkAndBlockIOCombined
  %%
  %assert(!UsingMalloc)
  /*
   * initialize model vectors and cache them in SimStruct
   */
  %%
  %% Block I/O
  %%
  %assign ptrBlockIOLabel = "#error no valid pointer to BlockIO because it is empty"
  %openfile tmpBuf
  %if !LibBlockIOStructIsEmpty()
    %assign ptrBlockIOLabel = "((void *) &%<LibGetBlockIOStruct()>)"
    %if ::CompiledModel.HasSimStructVars == 0
      %<RTMSet("BlockIO", ptrBlockIOLabel)>;
    %endif
  %endif
 
  %% Find out whether a memset is needed for combined Dwork and Block IO
  %assign needMemsetForCombinedDWorkAndBlockIO = SLibInitBlockIO(ptrBlockIOLabel)
  %% Initialize strings in rapid accelerator mode
  %if ::isRAccel
    %% Loop through all global block outputs
    %foreach boIdx = BlockOutputs.NumGlobalBlockOutputs
      %assign bo = BlockOutputs.GlobalBlockOutput[boIdx]
      %% Only do this if we can find variable name for this block output
      %if ISFIELD(bo, "VarGroupIdx")
        %% Construct variable name for the block output ("rtB.b1")
        %assign fullName = SLibGetBlockOutputIdentifierFromRecord(bo, GetBaseSystemIdx())
        %% Emit initialization code for string signal or bus element
        %assign boDataTypeId = LibGetRecordDataTypeId(bo)
        %assign boWidth = LibGetRecordWidth(bo)
        %<SlibInitStringData(boDataTypeId, fullName, boWidth)>
      %endif
    %endforeach
  %endif
  %closefile tmpBuf
  %if !WHITE_SPACE(tmpBuf)
 
    /* block I/O */
    {
      %<tmpBuf>
    }
  %endif
  %%
  %% U
  %%
  %openfile tmpBuf
  %if !LibExternalInputsStructIsEmpty()
    %<RTMSet("U", "((void*) &%<LibGetExternalInputStruct()>)")>;
  %endif
  %<SLibInitExternalInputs(TLC_TRUE,0, 0)>/
  %closefile tmpBuf
  %if !WHITE_SPACE(tmpBuf)
 
    /* external inputs */
    {
      %<tmpBuf>/
    }
  %endif
  %%
  %% Y
  %%
  %if !LibExternalOutputsStructIsEmpty()
 
    /* external outputs */
    {
      %<RTMSet("Y", "&%<LibGetExternalOutputStruct()>")>;
      %<SLibInitExternalOutputs(1,0,0)>/
      %% Initialize string model outputs in rapid accelerator mode
      %if ::isRAccel
        %% Loop through all model outputs
        %foreach idx = ::CompiledModel.ExternalOutputs.NumExternalOutputs
          %assign mo = ::CompiledModel.ExternalOutputs.ExternalOutput[idx]
          %% Only do this if we can find variable name for this model output
          %if ISFIELD(mo, "VarGroupIdx")
            %% Construct variable name for the model output ("rtY->b1" or "rtY.b2")
            %assign modelOutput = LibGetExternalOutputStruct()
            %assign fieldAccess = YQualifier
            %assign varName = SLibVarGroupElementName(mo.VarGroupIdx[0], mo.VarGroupIdx[1])
            %assign fullName = modelOutput + fieldAccess + varName
            %% Emit initialization code for string signal or bus element
            %assign moDataTypeId = LibGetRecordDataTypeId(mo)
            %assign moWidth = LibGetRecordWidth(mo)
            %<SlibInitStringData(moDataTypeId, fullName, moWidth)>
          %endif
        %endforeach
      %endif
    }
  %endif
  %%
  %% Parameters
  %%
  %if !LibParametersStructIsEmpty() && !FcnParamsAreGlobalStruct()
 
    /* parameters */
    %<RTMSet("DefaultParam", "(real_T *) &%<LibGetParametersStruct()>")>;
    
  %endif
  %%
  %% States
  %%
  %if (NumContStates) > 0
 
    %assign contStateTypeInRTM = FcnGetContStateType()
    /* states (continuous)*/
    {
      %<contStateTypeInRTM> *x = (%<contStateTypeInRTM> *) &%<LibGetContinuousStateStruct()>;
       
      %% Always setup continuous states so ssGetX in logging code works
      %<RTMSet("ContStates", "x")>;
      (void) %<LibGenMemFcnCall("memset", "(void *)x", "0", ...
    "sizeof(%<::tContStateType>)")>;
    }
  %endif
  %%
  %% DWork
  %%
  %if !LibDWorkStructIsEmpty()
    %assign stdSSBuf = CacheStandaloneSystemDWorkInfo()
 
    %% This is a non-ert target. Root system should be the only system in
    %% stdSSBuf
    %assert(SIZE(stdSSBuf.DWorkBuff, 1) == 1)
    /* states (dwork) */
    {
      %assign stdSSBuf = SLibInitDWork(stdSSBuf)
      void *dwork = (void *) &%<LibGetDWorkStruct()>;
      
      %<RTMSet("RootDWork", "dwork")>;
      %if !SLibGetUseRTMcgType() && stdSSBuf.DWorkBuff[0].needMemset ...
          || needMemsetForCombinedDWorkAndBlockIO == 1
        (void) %<LibGenMemFcnCall("memset", "dwork", " 0", ...
          " sizeof(%<::tDWorkType>)")>;
        %assign baseSystemIdx = GetBaseSystemIdx()
        %<SLibAccessArgHelper(System[baseSystemIdx].Interface.DWorkArgDef,"","")>
      %endif
      %if stdSSBuf.DWorkBuff[0].haveFloat
        %/
      %endif
      %if stdSSBuf.DWorkBuff[0].emitMsgInit
        %/
      %endif
      %if stdSSBuf.DWorkBuff[0].emitStringInit
        %/
      %endif
    }
 
  %endif
  %openfile tmpBuf
  %<SLibInitStatesWithExternalStorage(TLC_TRUE)>/
  %closefile tmpBuf
  %if !WHITE_SPACE(tmpBuf)
    %<tmpBuf>/
  %endif
 
  %%
  %%
  %% Initialize MassMatrix-related DWorks in Registration function.
  %% This function is calledfor non-ERT-based targets (Rsim, GRT_malloc, Generated Sfcn).
  %% We need to configure Pr-s for Rsim here.
  %%
  %if (ModelIsLinearlyImplicit == "yes")
    %assert( !IsModelReferenceTarget() )
    %<FcnGenInitMassMatrixPrInRoot()>
  %endif
     
  %%
  %% Multi-Instance Stateflow chart initialization
  %%
  %% dboissy & vijay say:
  %% Don't need this
  %%<SLibDumpSFLibraryBlockInitialization()>/
  %%
%endfunction %% SLibDumpModelDataInitialization
 
 
%%Function:SLibDumpTimingInfoRegistration====================================
%%Abstract:
%%Dumpalltiminginfo
%%
%%TopTester:test/toolbox/simulink/variants/tTypesToPrivate.m-tVariantGecks.m
%%TopTester:test/toolbox/simulink/variants/string/tStringSupport.m
%%
%function SLibDumpTimingInfoRegistration() Output
  %%
  %% Timing Info. Supports these code formats
  %% o RealTime using SimStruc
  %assert(!UsingMalloc)
  /* timing info */
  {
    %assign nTs = "NSAMPLE_TIMES"
    %assign nTs = SLibIsERTCodeFormat() ? NumRuntimeExportedRates : "NSAMPLE_TIMES"
    static time_T mdlPeriod[%<nTs>];
    static time_T mdlOffset[%<nTs>];
    static time_T mdlTaskTimes[%<nTs>];
    static int_T mdlTsMap[%<nTs>];
    static int_T mdlSampleHits[%<nTs>];
    %if isRSimWithSolverModule %% assert !IsModelReferenceTarget
      static boolean_T mdlTNextWasAdjustedPtr[%<nTs>];
      static int_T mdlPerTaskSampleHits[%<nTs> * %<nTs>];
      static time_T mdlTimeOfNextSampleHit[%<nTs>];
    %endif
     
    {
      int_T i;
 
      for (i = 0; i < %<nTs>; i++) {
    mdlPeriod[i] = 0.0;
    mdlOffset[i] = 0.0;
    mdlTaskTimes[i] = 0.0;
    mdlTsMap[i] = i;
        %if SLibSingleTasking()
      mdlSampleHits[i] = 1;
    %endif
      }
    }
    %if !SLibSingleTasking()
      mdlSampleHits[0] = 1;
    %endif
 
    %<RTMSet("SampleTimePtr", "&mdlPeriod[0]")>;
    %<RTMSet("OffsetTimePtr", "&mdlOffset[0]")>;
    %<RTMSet("SampleTimeTaskIDPtr", "&mdlTsMap[0]")>;
    %<RTMSet("TPtr", "&mdlTaskTimes[0]")>;
    %<RTMSet("SampleHitPtr", "&mdlSampleHits[0]")>;
    %if isRSimWithSolverModule %% assert !IsModelReferenceTarget
      %<RTMSet("TNextWasAdjustedPtr", "&mdlTNextWasAdjustedPtr[0]")>;
      %<RTMSet("PerTaskSampleHitsPtr", "&mdlPerTaskSampleHits[0]")>;
      %<RTMSet("TimeOfNextSampleHitPtr", "&mdlTimeOfNextSampleHit[0]")>;
    %endif
  }
  %if ::CompiledModel.SolverType == "FixedStep"
    %if ::CompiledModel.FixedStepOpts.SolverMode == "MultiTasking"
      {
        static int_T mdlPerTaskSampleHits[%<nTs> * %<nTs>];
     
        (void) %<LibGenMemFcnCall("memset", "(void *)&mdlPerTaskSampleHits[0]", "0", ...
      "%<NumRuntimeExportedRates> * %<NumRuntimeExportedRates> * sizeof(int_T)")>;
        %<RTMSet("PerTaskSampleHitsPtr", "&mdlPerTaskSampleHits[0]")>;
      }
      %<RTMSolverSet("SolverMode", "SOLVER_MODE_MULTITASKING")>;
    %else
      %<RTMSolverSet("SolverMode", "SOLVER_MODE_SINGLETASKING")>;
    %endif
  %else %% Variable-Step solver
    %<RTMSolverSet("SolverMode", "SOLVER_MODE_SINGLETASKING")>;
  %endif
%endfunction %% SLibDumpTimingInfoRegistration
 
 
%%Function:genAbsTolControlSetup=========================================
%%Abstract:
%%Absolutetolerancecontrolvectorsetupinmodelregistration
%%
%function genAbsTolControlSetup() void
   
  %assign zeroArray = FEVAL("zeros", 1, NumContStates)
  %assign absTolControl = FEVAL("uint8", zeroArray)
  %assign mdlAbsTolControl = ::CompiledModel.VariableStepOpts.AbsTolControl
   
  %% Copy top model absolute tolerance control first
  %if NumContStates > 1
    %foreach ix = NumContStates
      %assign absTolControl[ix] = mdlAbsTolControl[ix]
    %endforeach
  %else
    %% TLC loops do not like size-1 arrays
    %assign absTolControl = mdlAbsTolControl
  %endif
   
  %% Now handle model reference case by looping over all cstate records
  %foreach csIdx = ::CompiledModel.ContStates.NumContStates
    %assign cs = ::CompiledModel.ContStates.ContState[csIdx]
    %assign isMdlRef = FcnOwnerBlkType(cs) == "ModelReference"
 
    %% Global setting ok if no model reference.
    %if !isMdlRef
      %continue
    %endif
 
    %assert(isMdlRef)
 
    %% If model reference : Look at interface data for model reference
    %assign blk = System[cs.SigSrc[0]].Block[cs.SigSrc[2]]
    %assign intrf = GetModelrefInterface(blk)
 
    %% If abstol control is available
    %% (it might not be if referenced model was built with fixed-step settings)
    %% Prefer global settings in such case.
    %if !EXISTS(intrf.refAbsTolControl)
      %continue
    %endif
     
    %assert(EXISTS(intrf.refAbsTolControl))
     
     
    %assign refAbsTolControl = intrf.refAbsTolControl
    %assign csparts = cs.Partitions
    %% Loop over cstate partition
    %foreach csp = csparts.NumPartitions
      %assign cstateIndices = csparts.Partition[csp].CStateIndices
      %assign nci = SIZE(cstateIndices)[1]
      %assign pwidth = csparts.Partition[csp].Width
      %% For a plain model ref niter is equal to one,
      %% i.e. number of indices is equal to partition width
      %% For For-each subsystem niter > 1
      %assign niter = nci/pwidth
      %% This is the offset over model reference states
      %% We increment it by width of each partition in the
      %% outer niter loop
      %assign refOffset = 0
      %% Now loop over the iterations
      %foreach i_iter = niter
        %% over partition width for this record
        %foreach i_x = pwidth
          %% Compute the index for indexing cstatesIndices
          %% Essentially we are processing chunks of cstateIndices equal to
          %% pwidth
          %assign csiIndex = (i_iter*pwidth) + i_x
          %% If the control on referenced model refers to local setting
          %% Prefer the local otherwise prefer the top model setting
          %if refAbsTolControl[refOffset+i_x] == 1
            %assign absTolControl[cstateIndices[csiIndex] ] = FEVAL("uint8", 1)
          %endif %% if control is local
        %endforeach %% width of cstate partition
      %endforeach %% For number of iteration (for-each) or 1 (for normal cases)
      %% Move the referenced model state offset by the partition width
      %assign refOffset = refOffset + pwidth
    %endforeach %% for each partition
  %endforeach %% for each cstate record
 
  %assign absTolControlStr = "static uint8_T absTolControl[%<NumContStates>] = {"
  %assign comma = ""
  %foreach i_x = NumContStates
    %assign absTolControlStr = "%<absTolControlStr>%<comma> %"
    %assign comma = ", "
  %endforeach
  %% Close the array in C with };
  %assign absTolControlStr = "%<absTolControlStr> };"
   
  %return absTolControlStr
   
%endfunction
 
%%Function:SLibDumpModelRegRSimSetup=========================================
%%Abstract:
%%RegistrationcodeneedfortheRSimtarget.
%%TopTester:test/toolbox/simulink/variants/tsvarDDG.m
%%
%function SLibDumpModelRegRSimSetup() Output
  {
    static ssSolverInfo slvrInfo;
 
    %if NumContStates > 0
      %if (ModelHasProjections == "yes") || (ModelIsLinearlyImplicit == "yes")
        static struct _ssSFcnModelMethods3 mdlMethods3;
        static struct _ssSFcnModelMethods2 mdlMethods2;
      %endif
      static boolean_T contStatesDisabled[%<NumContStates>];
 
    %endif
    %if SolverType == "VariableStep"
      %assign nOutTimes = SIZE(VariableStepOpts.OutputTimes,1)
      %assign outTimes = (nOutTimes == 0) ? SLibGetNullDefinitionFromTfl() : "outputTimes"
      %assign nDU = SolverResetInfo.NumNonContDerivSignals
      %assign dU = (nDU == 0) ? SLibGetNullDefinitionFromTfl() : "nonContDerivSigInfo"
       
      %if NumContStates > 0
        static real_T absTol[%<NumContStates>] = {/
        %assign comma = ""
        %foreach idx = NumContStates
          %<comma>%/
          %assign comma = ", "
        %endforeach
      };
       
      %% Generate the Absolute tolerance control setup
      %<genAbsTolControlSetup()>
       
      %% Generate the cont state perturbation vec
      %if NumContStates > 0 && SolverType == "VariableStep"
         static real_T contStateJacPerturbBoundMinVec[%<NumContStates>];
         static real_T contStateJacPerturbBoundMaxVec[%<NumContStates>];
                  
      %endif
                    
    %endif
      %%adzc
      %if NumNonsampledZCs > 0
        %assign zcVectorLen = ::CompiledModel.ZCVectorlength
        %assign zcAttributes = FEVAL("zeros", 1, zcVectorLen)
        %assign zcEvents = FEVAL("zeros", 1, zcVectorLen)
    %foreach idx = ZcRec. NumBlkZcRecs
      %assign blkZcRec = ZcRec.BlkZcRec[idx]
      %foreach zcsIdx = blkZcRec.NumZcSignalInfos
        %assign zcs = blkZcRec.ZcSignalInfo[zcsIdx]
            %assign needEvent = zcs.NeedsEvent
            %assign needsSolverReset = zcs.NeedsSolverReset
            %assign zcDir = zcs.ZcEventType
            %assign zcVectorIndices = zcs.ZcVectorIndices
            %assign zcWidth = zcs.Width
            %assign jdx = 0
            %foreach zcVectorIdx = SIZE(zcVectorIndices)[1]
              %if jdx == zcWidth
                %assign jdx = 0
              %endif
              %if zcs.ZcSignalType == "Hybrid"
                %assign isDisc = zcs.IsElementDisc[jdx]
              %elseif zcs.ZcSignalType == "Continuous"
                %assign isDisc = 0
              %else
                %assign isDisc = 1
              %endif
              %if zcVectorLen == 1
                %assign zcAttributes = "%<SLibGetZCAttributes(isDisc, needEvent, zcDir)>"
                %assign zcEvents = "%<SLibGetZCEvents(needsSolverReset, 0, zcDir)>"
              %else
                %assign zcAttributes[zcVectorIndices[zcVectorIdx]] = SLibGetZCAttributes(isDisc, needEvent, zcDir)
                %assign zcEvents[zcVectorIndices[zcVectorIdx]] = SLibGetZCEvents(needsSolverReset, 0, zcDir)
              %endif
              %assign jdx = jdx + 1
            %endforeach
      %endforeach
    %endforeach
    %assign comma = ""
    static uint8_T zcAttributes[%<zcVectorLen>] = {/
        %if zcVectorLen == 1
          %<zcAttributes>/
        %else
          %foreach idx = zcVectorLen
            %<comma>%/
            %assign comma = ", "
          %endforeach
        %endif
        };
        %if ZcRec.OptimalSolverResetCausedByZc > 0
          %assign comma = ""
          static uint8_T zcEvents[%<zcVectorLen>] = {/
          %if zcVectorLen == 1
            %<zcEvents>/
          %else
            %foreach idx = zcVectorLen
              %<comma>%/
              %assign comma = ", "
            %endforeach
          %endif
        };
        %endif
        %%adzc
    %endif
     
      %if nOutTimes > 0
    static real_T %<outTimes>[%<nOutTimes>] = {/
      %assign comma = ""
      %foreach idx = nOutTimes
        %<comma>%/
        %assign comma = ", "
      %endforeach
    };
      %endif
 
      %if nDU > 0
        %assign codebuf = ""
    static ssNonContDerivSigInfo %<dU>[%<nDU>] = {
      %assign comma = ""
          %assign numSigs = SIZE(SolverResetInfo.NonContDerivSignal,1)
          %assign arrayIdx = 0
      %foreach idx = numSigs
        %assign nonContSig = SolverResetInfo.NonContDerivSignal[idx]
            %if ISFIELD(nonContSig,"MdlRefInfo")
              %assign mdlRefInfo = nonContSig.MdlRefInfo
              %assign mSysIdx = mdlRefInfo[0][0]
              %assign bIdx = mdlRefInfo[0][1]
              %assign instIdx = mdlRefInfo[0][2]
              %assign port = mdlRefInfo[0][3]
              %assign blk = System[mSysIdx].Block[bIdx]
              %assign name = blk.ParamSettings.ReferencedModelName
              %assign mangleName = FcnGetNoncontMangledName(name, mSysIdx, ...
                bIdx, instIdx)
              %foreach subIdx = nonContSig.NumMdlRefNonContSigs
                %<comma>{0, %<SLibGetNullDefinitionFromTfl">SLibGetNullDefinitionFromTfl()>, %<SLibGetNullDefinitionFromTfl">SLibGetNullDefinitionFromTfl()>}
                %openfile declbuf
                %<dU>[%<arrayIdx>].sizeInBytes = ...
                  mr_%<mangleName>nonContOutputArray[%<port>][%<subIdx>].sizeInBytes;
                %<dU>[%<arrayIdx>].pCurrVal = ...
                  (char *)mr_%<mangleName>nonContOutputArray[%<port>][%<subIdx>].currVal;
                %closefile declbuf
                %assign codebuf = codebuf + declbuf
                %assign comma = ", "
                %assign arrayIdx = arrayIdx + 1
              %endforeach
            %else
              %assign sigSrc = nonContSig.SigSrc
              %assign startEl = nonContSig.StartEl
              %assign regLen = nonContSig.RegionLen
              %%
              %assign idNum = IDNUM(sigSrc)
              %assert (idNum[0] == "B")
              %assign bo = BlockOutputs.GlobalBlockOutput[idNum[1]]
              %assert (LibGetRecordWidth(bo) >= regLen)
              %assert (LibGetRecordWidth(bo) > startEl)
              %assert (bo.Invariant == "no")
              %% For NonContDerivSignal inside For Each subsystem, we need to
              %% index each For Each vargroup level by right index
              %if ISFIELD(nonContSig, "ForEachSSIterIndices")
                %assign ::UseConstantForVarGroupIdx = TLC_TRUE
                %assign ::VarGroupIndexVector = nonContSig.ForEachSSIterIndices
                %assign ::VarGroupIndexVectorSize = SIZE(::VarGroupIndexVector, 1)
                %assign ::VarGroupIndexVectorIdx = ::VarGroupIndexVectorSize - 1
              %endif
              %assign name = SLibGetBlockOutputIdentifierFromRecord(bo,NumSystems-1)
              %if ISFIELD(nonContSig, "ForEachSSIterIndices")
                %assign ::UseConstantForVarGroupIdx = TLC_FALSE
                %assign ::VarGroupIndexVectorIdx = ::VarGroupIndexVectorSize - 1
              %endif
              %assign opW = (LibGetRecordWidth(bo) == 1) ? "" : "[%<startEl>]"
              %assign addr = "&%<name>%<opW>"
              %%
              %assign dType = SLibGetRecordContainerTypeName(bo)
              %assign sizeInBytes = "%<regLen>*sizeof(%<dType>)"
              %%
              %<comma>{ %<sizeInBytes>, (char*)(%<addr>), %<SLibGetNullDefinitionFromTfl()> }
              %assign comma = ", "
              %assign arrayIdx = arrayIdx + 1
            %endif
      %endforeach
    };
         
        %<codebuf>
      %endif
 
      %% Do not put any more declarations after this line.
       
      %if NumContStates > 0 && SolverType == "VariableStep"
        /* Initialize cont state perturbation bound */
        {
          int i;
          for (i = 0; i < %<NumContStates>; ++i){
            contStateJacPerturbBoundMinVec[i] = 0;
            contStateJacPerturbBoundMaxVec[i] = rtGetInf();
          }
        }
      %endif
       
      %if NumContStates > 0
    %<RTMSolverSet("SolverRelTol", "%<VariableStepOpts.RelTol>")>;
      %endif
      %<RTMSet("StepSize", "%<VariableStepOpts.InitialStep>")>;
      %<RTMSolverSet("MinStepSize", "%<VariableStepOpts.MinStep>")>;
      %<RTMSolverSet("MaxNumMinSteps", "%<VariableStepOpts.MaxNumMinSteps>")>;
      %assign minStepErr = ISEQUAL(VariableStepOpts.MinStepViolatedError,"yes")
      %<RTMSolverSet("MinStepViolatedError", "%<minStepErr>")>;
      %<RTMSolverSet("MaxStepSize", "%<VariableStepOpts.MaxStep>")>;
      %<RTMSolverSet("SolverMaxOrder", "%<VariableStepOpts.MaxOrder>")>;
 
      %<RTMSolverSet("SolverRefineFactor", "%<VariableStepOpts.Refine>")>;
      %<RTMSet("OutputTimes", "%<outTimes>")>;
      %<RTMSet("NumOutputTimes", "%<nOutTimes>")>;
      %if VariableStepOpts.OutputTimesOption == "specified"
    %<RTMSet("OutputTimesOnly", "1")>;
      %else
    %<RTMSet("OutputTimesOnly", "0")>;
      %endif
      %<RTMSet("OutputTimesIndex", "0")>;
      %%
      %<RTMSet("ZCCacheNeedsReset", "%<SolverResetInfo.ZCCacheNeedsReset>")>;
      %<RTMSet("DerivCacheNeedsReset", "%<SolverResetInfo.DerivCacheNeedsReset>")>;
      %<RTMSet("NumNonContDerivSigInfos", "%<nDU>")>;
      %<RTMSet("NonContDerivSigInfos", "%<dU>")>;
      %%
    %endif %% SolverType == VariableStep
    %%
    %<RTMSet("SolverInfo", "&slvrInfo")>;
    %<RTMSolverSet("SolverName", "/"%<Solver>/"")>;
    %assign isVarStepSolver = ISEQUAL(SolverType,"VariableStep")
    %<RTMSolverSet("VariableStepSolver", "%<isVarStepSolver>")>;
    %assign consCheck = ISEQUAL(SolverConsistencyChecking,"yes")
    %<RTMSet("SolverConsistencyChecking", "%<consCheck>")>;
    %assign adapZc = ISEQUAL(SolverZeroCrossDetection,"Adaptive")
    %<RTMSet("SolverAdaptiveZcDetection", "%<adapZc>")>;
    %%
    %assign robustReset = ISEQUAL(SolverResetMethod,"robust")
    %<RTMSet("SolverRobustResetMethod", "%<robustReset>")>;
    %assign updateJacobianAtReset = ISEQUAL(SolverUpdateJacobianAtReset,"yes")
    %if updateJacobianAtReset
      %<RTMuSet("SolverUpdateJacobianAtReset", "true")>;
    %endif %% _ssSetSolverUpdateJacobianAtReset(S,true)
    %%
   %if SolverType == "VariableStep" && NumContStates > 0
     %<RTMSolverSet("AbsTolVector", "absTol")>;
     %<RTMSolverSet("AbsTolControlVector", "absTolControl")>;
     %<RTMSolverSet("SolverAbsTol_Obsolete", "absTol")>;
     %<RTMSolverSet("SolverAbsTolControl_Obsolete", "absTolControl")>;
      
     %<RTMSolverSet("JacobianPerturbationBoundsMinVec", "contStateJacPerturbBoundMinVec")>;
     %<RTMSolverSet("JacobianPerturbationBoundsMaxVec", "contStateJacPerturbBoundMaxVec")>;
   %endif
     
    %assign hasProj = ISEQUAL(ModelHasProjections, "yes") && (NumContStates > 0)
    %assign isLinearlyImplicit = ISEQUAL(ModelIsLinearlyImplicit, "yes")
    %<RTMSet("SolverStateProjection", "%<hasProj>")>;
    %if hasProj || isLinearlyImplicit
      (void) %<LibGenMemFcnCall("memset", "(void *)&mdlMethods2", "0", ...
    "sizeof(mdlMethods2)")>;
      %<RTMSet("ModelMethods2", "&mdlMethods2")>;
      (void) %<LibGenMemFcnCall("memset", "(void *)&mdlMethods3", "0", ...
    "sizeof(mdlMethods3)")>;
      %<RTMSet("ModelMethods3", "&mdlMethods3")>;
      %if hasProj
        %<RTMSet("ModelProjection", "MdlProjection")>;
      %endif
      %if isLinearlyImplicit
        %<RTMSet("MassMatrixType", "(ssMatrixType)%<ModelMassMatrixType>")>;
        %<RTMSet("MassMatrixNzMax", "%<ModelMassMatrixNzMax>")>;
        %<RTMSet("ModelMassMatrix", "MdlMassMatrix")>;
        %<RTMSet("ModelForcingFunction", "MdlForcingFunction")>;
      %endif
       
    %endif
    %%
    %<RTMSolverSet("SolverMassMatrixType", "(ssMatrixType)%<ModelMassMatrixType>")>;
    %<RTMSolverSet("SolverMassMatrixNzMax", "%<ModelMassMatrixNzMax>")>;
    %%
    %<RTMSet("ModelOutputs", "MdlOutputs")>;
    %<RTMSet("ModelLogData", "rt_UpdateTXYLogVars")>;
    %<RTMSet("ModelLogDataIfInInterval", "rt_UpdateTXXFYLogVars")>;
    %<RTMSet("ModelUpdate", "MdlUpdate")>;
    %if NumContStates > 0
      %%even for linearly-implicit systems, mdlDerivatives is required.
      %<RTMSet("ModelDerivatives", "MdlDerivatives")>;
    %endif
    %if NumNonsampledZCs > 0
      %<RTMSet("SolverZcSignalAttrib", "zcAttributes")>;
      %if ZcRec.OptimalSolverResetCausedByZc > 0
        %<RTMSet("SolverZcEventsVector", "zcEvents")>;
      %endif
      %<RTMSet("SolverNumZcSignals", "%<ZCVectorlength>")>;
      %<RTMSet("ModelZeroCrossings", "MdlZeroCrossings")>;
    %%solver diagnostic controls must be written after ssSetSolverInfo
      %<RTMSolverSet("SolverConsecutiveZCsStepRelTol", "%<VariableStepOpts.ConsecutiveZCsStepRelTol>")>;
      %<RTMSolverSet("SolverMaxConsecutiveZCs", "%<VariableStepOpts.MaxConsecutiveZCs>")>;
      %<RTMSolverSet("SolverConsecutiveZCsError", "%<VariableStepOpts.ConsecutiveZCsError>")>;
      %<RTMSolverSet("SolverMaskedZcDiagnostic", "%<VariableStepOpts.MaskedZcDiagnostic>")>;
      %<RTMSolverSet("SolverIgnoredZcDiagnostic", "%<VariableStepOpts.IgnoredZcDiagnostic>")>;
       
      %if adapZc
        %<RTMSolverSet("SolverZcThreshold","%<VariableStepOpts.ZcThreshold>")>;
      %endif
    %endif
     
    %if NumContStates > 0 && isVarStepSolver
    %<RTMSolverSet("SolverMaxConsecutiveMinStep", "%<VariableStepOpts.MaxConsecutiveMinStep>")>;
    %<RTMSolverSet("SolverShapePreserveControl", "%<VariableStepOpts.ShapePreserveCtl>")>;
    %endif
     
    %<RTMSet("TNextTid","INT_MIN")>;
    %<RTMSet("TNext", LibRealNonFinite("-inf"))>;
    %<RTMSetSolverNeedsReset()>;
    %<RTMSet("NumNonsampledZCs", "%<NumNonsampledZCs>")>;
    %if NumContStates > 0
      %<RTMSet("ContStateDisabled", "contStatesDisabled")>;
    %endif
     
     
    %if NumContStates > 0 && isVarStepSolver
    %<RTMSolverSet("SolverMaxConsecutiveMinStep", "%<VariableStepOpts.MaxConsecutiveMinStep>")>;
    %endif
     
    %if isLinearlyImplicit
      /* global mass matrix */
      {
        int_T *ir = %<LibGetMassMatrixGlobalIr()>;
        int_T *jc = %<LibGetMassMatrixGlobalJc()>;
        real_T *pr = %<LibGetMassMatrixGlobalPr()>;
        %<RTMSet("MassMatrixIr", "ir")>;
        %<RTMSet("MassMatrixJc", "jc")>;
        %<RTMSet("MassMatrixPr", "pr")>;
        (void) %<LibGenMemFcnCall("memset", "(void *)ir", "0", ...
          "%<ModelMassMatrixNzMax>*sizeof(int_T)")>;
        (void) %<LibGenMemFcnCall("memset", "(void *)jc", "0", ...
          "(%<NumContStates>+1)*sizeof(int_T)")>;
        (void) %<LibGenMemFcnCall("memset", "(void *)pr", "0", ...
          "%<ModelMassMatrixNzMax>*sizeof(real_T)")>;
      }
      %endif
  }
 
%endfunction %% SLibDumpModelRegRSimSetup
 
 
%%Function:SLibGetSysRanBCDWork==============================================
%%Abstract:
%%Returnsthedworkentryforthesystemranbreadcrumb,giventhedwork
%%index
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortFcnCall.m
%%
%function SLibGetSysRanBCDWork(dwIdx) void
  %assign dwRec = ::CompiledModel.DWorks.DWork[dwIdx]
  %assign block = System[dwRec.SigSrc[0]].Block[dwRec.SigSrc[2]]
   
  %assert (block.Type == "SubSystem")
 
  %% Update FcnNonRollingDWork
  %createrecord optionalArgs { ...
    IsMode TLC_FALSE ...
    StartIdx 0 ...
    DotName "" ...
    Name SLibGetNameOfSubsysRanBCDWork() ...
  }
  %with FcnLoopInfo("", "", 0)
    %assign dwork = FcnNonRollingDWork(dwRec, dwIdx, SLibDWorkWidth(dwRec), optionalArgs)
  %endwith
  %return dwork
%endfunction %% SLibGetSysRanBCDWork
 
 
%%Function:SLibDumpExtModeReg================================================
%%Abstract:
%%Dumpexternalmoderegistration:
%%-CreatetheRTWExtModeInfoobject
%%-Initializeitsfields
%%-PutRTWExtModeInfointothertModel/SimStruct
%%TopTester:test/toolbox/simulink/blocks/A/assignment/tassign_1.m
%%
%function SLibDumpExtModeReg(bEmitReg, bEmitInit) Output
  %%
  %% Loop through all the systems and cache the active vector locations
  %% so that updown.c can determine if a given system is enabled.
  %%
  %if EXISTS("ExtMode") && ExtMode == 1
    %assign sysRanDWorkLen = SIZE(::CompiledModel.SubsystemRanBC.SysRanDWork, 1)
    %assign needsAlwaysEnabled = TLC_FALSE
    %assign needsAlwaysDisabled = TLC_FALSE
    %openfile buf
    %% Populate the system ran breadcrumb pointers
    %assign contextSysVector = ::CompiledModel.SubsystemRanBC.ContextSysIdx
    %assign sysRanDWork = ::CompiledModel.SubsystemRanBC.SysRanDWork
     
    %% This is similar to what we do for the C-API (see capi.tlc)
    %foreach i = sysRanDWorkLen
      %assign dwIdx = sysRanDWork[contextSysVector[i]]
      %if (dwIdx > -1)
        %assign dwRec = ::CompiledModel.DWorks.DWork[dwIdx]
        %% TODO: Add eliminated globals to removed in IR set
        %if ISFIELD(dwRec, "VarGroupIdx")
          %with ::CompiledModel.System[GetBaseSystemIdx()]
            %assign sysDWork = SLibGetSysRanBCDWork(dwIdx)
          %endwith
          %assert (dwRec.Name == "SubsysRanBC")
          %assign sigAddr = "(sysRanDType *)&"+ sysDWork
        %else
          %assign sigAddr = "&rtAlwaysDisabled"
          %assign needsAlwaysDisabled = TLC_TRUE
        %endif
      %else
        %assign sigAddr = "&rtAlwaysEnabled"
        %assign needsAlwaysEnabled = TLC_TRUE
      %endif
      %if UsingMalloc
        ((const sysRanDType**)rteiGetSubSystemActiveVectorAddresses(%<RTMGet("RTWExtModeInfo")>))[%<i>] = %<sigAddr>;
      %else
        systemRan[%<i>] = %<sigAddr>;
      %endif
    %endforeach
    %closefile buf
    {
      %% rtAlwaysEnabled is int8_T because the extmode active dwork is int8_T.
      %if bEmitInit
        %if needsAlwaysEnabled
          static const sysRanDType rtAlwaysEnabled = SUBSYS_RAN_BC_ENABLE;
        %endif
        %if needsAlwaysDisabled
          static const sysRanDType rtAlwaysDisabled = SUBSYS_RAN_BC_DISABLE;
        %endif
      %endif %% bEmitInit
      %if bEmitReg
        %if UsingMalloc
          RTWExtModeInfo *rt_ExtModeInfo = ...
            (RTWExtModeInfo *) malloc(sizeof(RTWExtModeInfo));
           
          const sysRanDType **systemRan = (const sysRanDType **)malloc( %<sysRanDWorkLen> * sizeof(sysRanDType *) );
     
          %<RTMChkMemAndReturnIfErr("rt_ExtModeInfo")>;
          %<RTMChkMemAndReturnIfErr("systemRan")>;
           
        %else
          static RTWExtModeInfo rt_ExtModeInfo;
          static const sysRanDType *systemRan[%<sysRanDWorkLen>];
        %endif
       
        %assign amps = UsingMalloc ? "" : "&"
        %assign rteiO = "%<amps>rt_ExtModeInfo"
         
        %if ::isRAccel
          gblRTWExtModeInfo = %<rteiO>;
        %endif
       
        %<RTMSet("RTWExtModeInfo", "%<rteiO>")>;
        rteiSetSubSystemActiveVectorAddresses(%<rteiO>, systemRan);
      %endif %% bEmitReg
      %if bEmitInit
      %<buf>
      %endif %% bEmitInit
 
      %if bEmitInit
      %assign amps = UsingMalloc ? "" : "&"
      %assign rteiO = "%<amps>rt_ExtModeInfo"
      rteiSetModelMappingInfoPtr(%<RTMGet("RTWExtModeInfo")>, ...
    &%<RTMGet("ModelMappingInfo")>);
 
      rteiSetChecksumsPtr(%<RTMGet("RTWExtModeInfo")>, ...
    %<RTMGet("Checksums")>);
 
      rteiSetTPtr(%<RTMGet">RTMGet("RTWExtModeInfo")>, %<RTMGet">RTMGet("TPtr")>);
      %endif %% bEmitInit
    }
  %endif
%endfunction %% SLibDumpExtModeReg
 
 
%%Function:SLibDumpModelChecksumReg==========================================
%%Abstract:
%%Dumptheregisrationofthemodelchecksums.
%%
%function SLibDumpModelChecksumReg () Output
  %%
  %% Initialize Model checksum in sizes.
  %%
  %<RTMSetIdxed("ChecksumVal", 0, ModelChecksum[0])>;
  %<RTMSetIdxed("ChecksumVal", 1, ModelChecksum[1])>;
  %<RTMSetIdxed("ChecksumVal", 2, ModelChecksum[2])>;
  %<RTMSetIdxed("ChecksumVal", 3, ModelChecksum[3])>;
%endfunction
 
 
%%Function:FcnDumpSolverInfoObjectCreation===================================
%%Abstract:
%%DumpthecreationofthesolverinfoobjectthatlivesinthertModel.
%%TopTester:test/toolbox/simulink/blocks/lib_MathOperations/Gain/rtw/tdtgain4.m
%%TopTester:test/toolbox/simulink/blocks/sb2sl/tsb2slmdlref.m
%%
%function FcnDumpSolverInfoObjectCreation(bEmitReg, bEmitInit) Output
   
  %if GenRTModel
    {
      /* Setup solver object */
      %if UsingMalloc
    RTWSolverInfo *rt_SolverInfo = ...
      (RTWSolverInfo *) malloc(sizeof(RTWSolverInfo));
 
    %<RTMChkMemAndReturnIfErr("rt_SolverInfo")>;
      %else
        %%TCW: eventually migrate SolverInfo into rtModel for all formats
        %if !SLibIsERTCodeFormat()
          static RTWSolverInfo rt_SolverInfo;
        %endif
      %endif
      %assign amps = UsingMalloc ? "" : "&"
      %if !SLibIsERTCodeFormat() || UsingMalloc
        %<RTMSet("RTWSolverInfo", "%<amps>rt_SolverInfo")>;
      %endif
 
      %if LibIsContinuous(0)
        %assign stptr = "&%<RTMGet("SimTimeStep")>"
        %<RTMSolverSet("SimTimeStepPtr", stptr)>;
      %endif
      %assign tptr = "&%<RTMGet("TPtr")>"
      %<RTMSolverSet("TPtr", tptr)>;
      %if RTMStepSizeForTIDIsReqFcn(0)
        %assign sptr = "&%<RTMGet("StepSize0")>"
        %<RTMSolverSet("StepSizePtr", sptr)>;
      %elseif RTMStepSizeIsReqFcn()
        %assign sptr = "&%<RTMGet("StepSize")>"
        %<RTMSolverSet("StepSizePtr", sptr)>;
      %endif
      %if !SLibIsERTCodeFormat() || NumContStates > 0
        %assign dxptr = "&%<RTMGet("dX")>"
        %<RTMSolverSet("dXPtr", dxptr)>;
        %assign csptr = "(real_T **) &%<RTMGet("ContStates")>"
        %<RTMSolverSet("ContStatesPtr", csptr)>;
        %assign ncsptr = "&%<RTMGet("NumContStates")>"
        %<RTMSolverSet("NumContStatesPtr", ncsptr)>;
        %if NumContStates > 0
          %<RTMSolverSet("NumPeriodicContStatesPtr", "&%<RTMGet("NumPeriodicContStates")>")>;
          %<RTMSolverSet("PeriodicContStateIndicesPtr", "&%<RTMGet("PeriodicContStateIndices")>")>;
          %<RTMSolverSet("PeriodicContStateRangesPtr", "&%<RTMGet("PeriodicContStateRanges")>")>;
        %endif
         
        %%if SolverType == "VariableStep" && NumContStates > 0
          %%<RTMSolverSet("JacobianPerturbationBoundsMinVecPtr", "&%<RTMGet("JacobianPerturbationBoundsMinVec")>")>;
          %%<RTMSolverSet("JacobianPerturbationBoundsMaxVecPtr", "&%<RTMGet("JacobianPerturbationBoundsMaxVec")>")>;
        %%endif
      %endif
      %<RTMSolverSet("ErrorStatusPtr", GetRTMErrorStatusPtr())>;
      %if UsingMalloc && GenerateGRTWrapper
        %assign mmptr = "&%<RTMGet("RTWRTModelMethodsInfo")>"
        %<RTMSolverSet("ModelMethodsPtr", mmptr)>;
      %endif
 
      %if (SLibGetModelIsLinearlyImplicit() == "yes")
        %% Cannot get these from RTM -- not set, yet.
        %assign ir = "%<LibGetMassMatrixGlobalIr()>"
        %assign jc = "%<LibGetMassMatrixGlobalJc()>"
        %assign pr = "%<LibGetMassMatrixGlobalPr()>"
         
        %<RTMSolverSet("SolverMassMatrixIr", ir)>;
        %<RTMSolverSet("SolverMassMatrixJc", jc)>;
        %<RTMSolverSet("SolverMassMatrixPr", pr)>;
      %endif
       
      %<RTMSolverSet("RTModelPtr", "%<GetSimStructExpr(System[GetBaseSystemIdx()], ::tSimStruct)>")>;
    }
  %endif
%endfunction %% FcnDumpSolverInfoObjectCreation
 
 
%%Function:LibCacheModelRegistration=========================================
%%Abstract:
%%Cachethemodelregistrationcode.Supportsthesecodeformats
%%oRealTimeusingSimStruc
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortHighlight.m
%%TopTester:test/toolbox/simulink/blocks/A/assignment/tassign_loop.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/codeGen/tg1375551.m
%%
%function LibDumpModelRegistration(usingStatic) Output
   
  %assert(!UsingMalloc)
  %assert(!IsModelReferenceTarget())
  %%
  %% Solver info
  %%
  %<FcnDumpSolverInfoObjectCreation(usingStatic, TLC_TRUE)>/
  %%
  %% Timing engine
  %%
  %<SLibDumpTimingInfoRegistration()>/
  %%
  %% Initialize internal data
  %%
  %<SLibDumpModelDataInitialization()>/
  %%
  %%
  %% Model mapping info
  %%
  %<SLibDumpModelMappingInfo()>/
 
  %if ::isRAccel
    ssSetIsRapidAcceleratorActive(%<::tSimStruct>, true);
  %endif
   
  %%
  %% Model specifics
  %%
 
  /* Model specific registration */
  %assign rootSSreg = RTMSet("RootSS", RTMGetModelSS())
  %if !WHITE_SPACE(rootSSreg)
    %<rootSSreg>;
  %endif
 
  %assign verStr = RTMSet("Version", "SIMSTRUCT_VERSION_LEVEL2")
  %if !WHITE_SPACE(verStr)
    %<verStr>;
  %endif
  %<RTMSet("ModelName", "/"%<Name>/"")>;
  %<RTMSet("Path", "/"%<Name>/"")>;
   
  %if isRSim && !isRSimWithSolverModule && StartTime < 0
    %assign errTxt = "Start time must be non-negative number: %<StartTime>"
    %<LibReportFatalError(errTxt)>
  %endif
  %<RTMSet("TStart", StartTime)>;
   
  %if isRSimWithSolverModule %%assert !IsModelReferenceTarget
    %assign stopTime = StopTime
  %else
    %if ISINF(StopTime)
      %assign stopTime = "-1"
    %elseif !ISFINITE(StopTime)
      %assign errTxt = "Stop time must be 0.0, inf, or finite: %<StopTime>"
      %<LibReportFatalError(errTxt)>
    %else
      %if isRSim && StopTime < 0
        %assign errTxt = "Stop time must be non-negative number: %<StopTime>"
        %<LibReportFatalError(errTxt)>
      %endif
      %assign stopTime = StopTime
    %endif
  %endif
  %<RTMSet("TFinal", stopTime)>;
   
  %if ::CompiledModel.SolverType == "FixedStep"
    %<RTMSet("StepSize", FixedStepOpts.FixedStep)>;
    %<RTMSolverSet("FixedStepSize", FixedStepOpts.FixedStep)>;
  %endif
  %%
  %if Solver == "ode14x"
    %<RTMSolverSet("SolverExtrapolationOrder", ...
      "%<FixedStepOpts.ExtrapolationOrder>")>;
    %<RTMSolverSet("SolverNumberNewtonIterations", ...
      "%<FixedStepOpts.NumberNewtonIterations>")>;
 
        %% dummy calls to TFL query to invoke proper rt_ function to be included
        %% rt_lu_real(W,nx,pivots);
        %createrecord FcnRec{Name "rt_lu"; NumArgs 3}
        %addtorecord FcnRec ArgList{Expr "W"; TypeId tSS_DOUBLE; IsPtr 1; IsCplx 0; IsConst 0}
        %addtorecord FcnRec ArgList{Expr "nx"; TypeId tSS_INTEGER; IsPtr 0; IsCplx 0; IsConst 0}
        %addtorecord FcnRec ArgList{Expr "pivots"; TypeId tSS_INT32; IsPtr 1; IsCplx 0; IsConst 0}
        %assign dummy_rt_lu = LibGenFcnCall(FcnRec)
 
        %% rt_ForwardSubstitutionRR_Dbl(W,Delta,f1,nx,1,pivots,1);
        %createrecord FcnRec{Name "rt_ForwardSubstitution"; NumArgs 7}
        %addtorecord FcnRec ArgList{Expr "W"; TypeId tSS_DOUBLE; IsPtr 1; IsCplx 0; IsConst 0}
        %addtorecord FcnRec ArgList{Expr "Delta"; TypeId tSS_DOUBLE; IsPtr 1; IsCplx 0; IsConst 0}
        %addtorecord FcnRec ArgList{Expr "f1"; TypeId tSS_DOUBLE; IsPtr 1; IsCplx 0; IsConst 0}
        %addtorecord FcnRec ArgList{Expr "nx"; TypeId tSS_INTEGER; IsPtr 0; IsCplx 0; IsConst 0}
        %addtorecord FcnRec ArgList{Expr "1"; TypeId tSS_INTEGER; IsPtr 0; IsCplx 0; IsConst 0}
        %addtorecord FcnRec ArgList{Expr "pivots"; TypeId tSS_INT32; IsPtr 1; IsCplx 0; IsConst 0}
        %addtorecord FcnRec ArgList{Expr "1"; TypeId tSS_BOOLEAN; IsPtr 0; IsCplx 0; IsConst 0}
        %assign dummy_fs = LibGenFcnCall(FcnRec)
 
        %% rt_BackwardSubstitutionRR_Dbl(W+nx*nx-1,f1+nx-1,Delta,nx,1,0);
        %createrecord FcnRec{Name "rt_BackwardSubstitution"; NumArgs 6}
        %addtorecord FcnRec ArgList{Expr "W+nx*nx-1"; TypeId tSS_DOUBLE; IsPtr 1; IsCplx 0; IsConst 0}
        %addtorecord FcnRec ArgList{Expr "f1+nx-1"; TypeId tSS_DOUBLE; IsPtr 1; IsCplx 0; IsConst 0}
        %addtorecord FcnRec ArgList{Expr "Delta"; TypeId tSS_DOUBLE; IsPtr 1; IsCplx 0; IsConst 0}
        %addtorecord FcnRec ArgList{Expr "nx"; TypeId tSS_INTEGER; IsPtr 0; IsCplx 0; IsConst 0}
        %addtorecord FcnRec ArgList{Expr "1"; TypeId tSS_INTEGER; IsPtr 0; IsCplx 0; IsConst 0}
        %addtorecord FcnRec ArgList{Expr "0"; TypeId tSS_BOOLEAN; IsPtr 0; IsCplx 0; IsConst 0}
        %assign dummy_bs = LibGenFcnCall(FcnRec)
 
  %endif
 
  %if ::isRAccel
    %<SLibDumpServicePortConnectionsInit()>
    %<SLibDumpServicePortSelfInit()>
    %<SLibDumpServicePortRequestersInit()>
  %endif
   
  %%
  %%
  %% Dump calls to model reference registration functions.
  %%
  %assign mdlRefBlks = ISFIELD(::CompiledModel,"ModelReferenceBlocks") ? ...
    ::CompiledModel.ModelReferenceBlocks : []
  %<CallModelrefBlockRegFcns(mdlRefBlks)>
   
  %%
  %% Data logging setup (tell rtwlog or any other entity what we need)
  %%
  %if MatFileLogging
    %<SLibDumpModelRegDataLoggingSetup(TLC_TRUE, TLC_TRUE)>
  %endif
   
  %if NumContStates > 0 || NumZCEvents > 0
    {
      static struct _ssStatesInfo2 statesInfo2;
      %<RTMSolverSet("StatesInfo2", "&statesInfo2")>;
    }
   
    {
      static ssPeriodicStatesInfo periodicStatesInfo;
      %<RTMSolverSet("PeriodicStatesInfo", "&periodicStatesInfo")>;
               
    %if NumPeriodicContStates > 0
            
      %assign copyAddr = "%<LibGetPeriodicContStateIndices()>"
      %<RTMSet("PeriodicContStateIndices", copyAddr)>;
      (void) %<LibGenMemFcnCall("memset", "(void*) %<copyAddr>", "0", "%<NumPeriodicContStates>*sizeof(int_T)")>;
      %assign copyAddr = "%<LibGetPeriodicContStateRanges()>"
      %<RTMSet("PeriodicContStateRanges", copyAddr)>;
      (void) %<LibGenMemFcnCall("memset", "(void*) %<copyAddr>", "0", "%<2*NumPeriodicContStates>*sizeof(real_T)")>;
    %endif
     
    }
     
    {
      static ssJacobianPerturbationBounds jacobianPerturbationBounds;
      %<RTMSolverSet("JacobianPerturbationBounds", "&jacobianPerturbationBounds")>;
    }
  %endif
   
  %%
  %% Setup code for the RSim target.
  %%
  %if isRSimWithSolverModule %%assert !IsModelReferenceTarget
    %<SLibDumpModelRegRSimSetup()>
  %endif
 
  %% PrevZcSigState
  %if NumZCEvents > 0 && !LibPrevZCStatesStructIsEmpty()
    %<LibDumpModelInitializePrevZCStates(TLC_TRUE, TLC_TRUE)>
  %endif
 
  %<SLibDumpModelChecksumReg()>
  %%
  %% Dump external mode registration
  %%
  %<SLibDumpExtModeReg(TLC_TRUE, TLC_TRUE)>
  %%
  %% Cache function pointers, if necessary
  %%
  %if UsingMalloc && GenerateGRTWrapper
 
    %<RTMModelMthsSet("mdlInitializeSizes", "MdlInitializeSizes")>;
    %<RTMModelMthsSet("mdlInitializeSampleTimes", "MdlInitializeSampleTimes")>;
    %<RTMModelMthsSet("mdlStart", "MdlStart")>;
    %<RTMModelMthsSet("mdlOutputs", "MdlOutputs")>;
    %<RTMModelMthsSet("mdlUpdate", "MdlUpdate")>;
    %if NumContStates > 0
      %<RTMModelMthsSet("mdlDerivatives", "MdlDerivatives")>;
      %<RTMModelMthsSet("mdlProjection", "MdlProjection")>;
      %if ModelIsLinearlyImplicit == "yes"
        %<RTMModelMthsSet("mdlMassMatrix", "MdlMassMatrix")>;
        %<RTMModelMthsSet("mdlForcingFunction", "MdlForcingFunction")>;
      %else
        %<RTMModelMthsSet("mdlMassMatrix", SLibGetNullDefinitionFromTfl())>;
        %<RTMModelMthsSet("mdlForcingFunction", SLibGetNullDefinitionFromTfl())>;
      %endif
    %else
      %<RTMModelMthsSet("mdlDerivatives", SLibGetNullDefinitionFromTfl())>;
      %<RTMModelMthsSet("mdlProjection", SLibGetNullDefinitionFromTfl())>;
      %<RTMModelMthsSet("mdlMassMatrix", SLibGetNullDefinitionFromTfl())>;
      %<RTMModelMthsSet("mdlForcingFunction", SLibGetNullDefinitionFromTfl())>;
    %endif
    %<RTMModelMthsSet("mdlTerminate", "MdlTerminate")>;
    %if GenRTModel
      %<RTMModelMthsSet("RTModelPtr", ::tSimStruct)>;
    %endif
  %endif
%endfunction %% LibDumpModelRegistration
 
%function FcnNeedsToSetRTWSfcnInfo() void
  %return (CodeFormat == "S-Function") || GenRTModel
%endfunction
 
%%Function:FcnSetBlkInfo2
%%Abstract:
%%declare/allocateblkInfo2,andhookitupwiththeSimStruct.
%%TopTester:test/toolbox/simulink/blocks/lib_MathOperations/Gain/rtw/tdtgain4.m
%%
%function FcnSetBlkInfo2(childSS, childIdx) void
  %openfile tmpBuffer
  {
  %if !UsingMalloc || SLibIsERTCodeFormat()
    %if !SLibIsERTCodeFormat()
      static struct _ssBlkInfo2 _blkInfo2;
      struct _ssBlkInfo2 *blkInfo2 = &_blkInfo2;
      ssSetBlkInfo2Ptr(%<childSS>, blkInfo2);
    %else
      %assign nonInlSfcns = "%<RTMGet("NonInlinedSFcns")>"
      ssSetBlkInfo2Ptr(%<childSS>, &%<nonInlSfcns>.blkInfo2[%<childIdx>]);
    %endif
  %else
    struct _ssBlkInfo2 *blkInfo2 = ...
      (struct _ssBlkInfo2 *) malloc(sizeof(struct _ssBlkInfo2));
    %<RTMChkMemAndReturnIfErr("blkInfo2")>;
    ssSetBlkInfo2Ptr(%<childSS>, blkInfo2);
  %endif
  }
  %closefile tmpBuffer
   
  %return tmpBuffer
%endfunction
 
%%Function:FcnSetPortInfo2
%%Abstract:
%%declare/allocateportInfo2,andhookitupwiththeSimStruct.
%%TopTester:test/toolbox/simulink/blocks/lib_MathOperations/Gain/rtw/tdtgain4.m
%%
%function FcnSetPortInfo2(childSS, childIdx) void
  %openfile tmpBuffer
  %if !UsingMalloc
    %if !SLibIsERTCodeFormat()
      {
        static struct _ssPortInfo2 _portInfo2;
        struct _ssPortInfo2 *portInfo2 = &_portInfo2;
        _ssSetBlkInfo2PortInfo2Ptr(%<childSS>, portInfo2);
      }
    %else
      %assign nonInlSfcns = "%<RTMGet("NonInlinedSFcns")>"
      _ssSetBlkInfo2PortInfo2Ptr(%<childSS>, &%<nonInlSfcns>.inputOutputPortInfo2[%<childIdx>]);
    %endif
  %else
    {
      struct _ssPortInfo2 *portInfo2 = ...
        (struct _ssPortInfo2 *) malloc(sizeof(struct _ssPortInfo2));
      %<RTMChkMemAndReturnIfErr("portInfo2")>;
      _ssSetBlkInfo2PortInfo2Ptr(%<childSS>, portInfo2);
    }
  %endif
  %closefile tmpBuffer
   
  %return tmpBuffer
%endfunction
 
%%Function:FcnSetupSFcnRTWInfo===============================================
%%Abstract:
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/tVariantSource3.m-tmMultiRateAsyncTask_VC1.m
%%
%function FcnSetupSFcnRTWInfo() Output
  {
    %if UsingMalloc && !SLibIsERTCodeFormat()
      RTWSfcnInfo *sfcnInfo = (RTWSfcnInfo *) ...
    malloc(sizeof(RTWSfcnInfo));
      %<RTMChkMemAndReturnIfErr("sfcnInfo")>;
    %else
      %if SLibIsERTCodeFormat()
        RTWSfcnInfo *sfcnInfo = &%<RTMGet("NonInlinedSFcns")>.sfcnInfo;
      %else
        static RTWSfcnInfo _sfcnInfo;
        RTWSfcnInfo *sfcnInfo = &_sfcnInfo;
      %endif
    %endif
 
    %<RTMSet("RTWSfcnInfo", "sfcnInfo")>;
 
    rtssSetErrorStatusPtr(sfcnInfo, %<GetRTMErrorStatusPtr()>);
    rtssSetNumRootSampTimesPtr(sfcnInfo, &%<RTMGet("NumSampleTimes")>);
    %foreach idx = NumSampleTimes
      %<RTMGet">RTMGet("NonInlinedSFcns")>.taskTimePtrs[%<idx>] = &(%<RTMGet">RTMGet("TPtr")>[%<idx>]);
    %endforeach
    rtssSetTPtrPtr(sfcnInfo,%<RTMGet("NonInlinedSFcns")>.taskTimePtrs);
    rtssSetTStartPtr(sfcnInfo, &%<RTMGet("TStart")>);
    %if RTMTFinalIsReqFcn()
      rtssSetTFinalPtr(sfcnInfo, &%<RTMGet("TFinal")>);
    %endif
    rtssSetTimeOfLastOutputPtr(sfcnInfo, ...
      &%<RTMGet("TimeOfLastOutput")>);
    rtssSetStepSizePtr(sfcnInfo, &%<RTMGet("StepSize")>);
    rtssSetStopRequestedPtr(sfcnInfo, &%<RTMGetStopRequested()>);
    rtssSetDerivCacheNeedsResetPtr(sfcnInfo, ...
      &%<RTMGet("DerivCacheNeedsReset")>);
    rtssSetZCCacheNeedsResetPtr(sfcnInfo, ...
      &%<RTMGet("ZCCacheNeedsReset")>);
    rtssSetContTimeOutputInconsistentWithStateAtMajorStepPtr(sfcnInfo, ...
      &%<RTMGet("ContTimeOutputInconsistentWithStateAtMajorStepFlag")>);
    rtssSetSampleHitsPtr(sfcnInfo, &%<RTMGet("SampleHitPtr")>);
    rtssSetPerTaskSampleHitsPtr(sfcnInfo, ...
      &%<RTMGet("PerTaskSampleHitsPtr")>);
    rtssSetSimModePtr(sfcnInfo, &%<RTMGet("SimMode")>);
    %if SLibIsERTCodeFormat()
      rtssSetSolverInfoPtr(sfcnInfo, &%<RTMGet("RTWSolverInfoPtr")>);
    %else
      rtssSetSolverInfoPtr(sfcnInfo, &%<RTMGet("RTWSolverInfo")>);
    %endif
  }
%endfunction %% FcnSetupSFcnRTWInfo
 
%%Function:SLibSetupTimingInfoForChildSfcn()=================================
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/tVariantSource3.m-tmMultiRateAsyncTask_VC1.m
%%
%function SLibSetupTimingInfoForChildSfcn(s, childIdx, underScore, ...
  usingStatic, nonInlSfcns)
  %openfile retBuf
  /* timing info */
  %assign numSfcnSampleTimes = SIZE(TID, 1)
  %if usingStatic
    static time_T sfcnPeriod[%<numSfcnSampleTimes>];
    static time_T sfcnOffset[%<numSfcnSampleTimes>];
    static int_T sfcnTsMap[%<numSfcnSampleTimes>];
  %elseif SLibIsERTCodeFormat()
    %assign SfcnIdx = "%<nonInlSfcns>.Sfcn%<childIdx>"
    time_T *sfcnPeriod = %<SfcnIdx>.sfcnPeriod;
    time_T *sfcnOffset = %<SfcnIdx>.sfcnOffset;
    int_T *sfcnTsMap = %<SfcnIdx>.sfcnTsMap;
  %else
    time_T *sfcnPeriod;
    time_T *sfcnOffset;
    int_T *sfcnTsMap;
     
    sfcnPeriod = (time_T *) ...
      malloc(%<numSfcnSampleTimes> * sizeof(time_T));
    %<RTMChkMemAndReturnIfErr("sfcnPeriod")>;
    sfcnOffset = (time_T *) ...
      malloc(%<numSfcnSampleTimes> * sizeof(time_T));
    %<RTMChkMemAndReturnIfErr("sfcnOffset")>;
    sfcnTsMap = (int_T *) ...
      malloc(%<numSfcnSampleTimes> * sizeof(int_T ));
    %<RTMChkMemAndReturnIfErr("sfcnTsMap")>;
  %endif
   
  (void) %<LibGenMemFcnCall("memset", "(void*)sfcnPeriod", "0", ...
    "sizeof(time_T)*%<numSfcnSampleTimes>")>;
  (void) %<LibGenMemFcnCall("memset", "(void*)sfcnOffset", "0", ...
    "sizeof(time_T)*%<numSfcnSampleTimes>")>;
  %%
  ssSetSampleTimePtr(%<s>, &sfcnPeriod[0]);
  ssSetOffsetTimePtr(%<s>, &sfcnOffset[0]);
  %<underScore>ssSetSampleTimeTaskIDPtr(%<s>, sfcnTsMap);
  %closefile retBuf
 
  %return retBuf
%endfunction
 
%%Function:SLibSetupMdlInfoForChildSfcn()====================================
%%TopTester:test/toolbox/simulink/blocks/sb2sl/tsb2slmdlref2.m
%%
%function SLibSetupMdlInfoForChildSfcn(s, childIdx, underScore, ...
  usingStatic, nonInlSfcns) void
 
  %assign prefix = "/* Set up the mdlInfo pointer *//n"
  %assign postfix = ""
     
  %if (CodeFormat == "S-Function")
    %assign prefix = prefix + "# ifdef USE_RTMODEL/n"
    %assign postfix = "# else/n" + ...
      "%<underScore>ssSetMdlInfoPtr(%<s>, %<RTMGet("MdlInfoPtr")>);/n" + ...
      "# endif /* USE_RTMODEL *//n"
  %else
    %if GenRTModel
      %if IsModelReferenceForASimstructBasedTarget()
        %assign postfix = ...
          "%<underScore>ssSetMdlInfoPtr(%<s>, ssGetMdlInfoPtr(%<tMdlRefSfcnS>));/n"
      %endif
    %else
      %assign postfix = ...
        "%<underScore>ssSetMdlInfoPtr(%<s>, %<RTMGet("MdlInfoPtr")>);/n"
    %endif
  %endif
 
  %assign setBlkInfo2Str = ""
  %assign setPortInfo2Str = ""
  %assign setSfcnInfoStr = ""
  %%%
  %%% these three strings set up all the fields that bridge the
  %%% gap between a child S-function's SimStruct and the rtModel.
 
     
  %assign setBlkInfo2Str = FcnSetBlkInfo2(s, childIdx)
     
  %assign setPortInfo2Str = FcnSetPortInfo2(s, childIdx)
   
  %if FcnNeedsToSetRTWSfcnInfo()
    %assign setSfcnInfoStr = "ssSetRTWSfcnInfo(%<s>, %<RTMGet("RTWSfcnInfo")>);/n"
  %endif
 
  %return setBlkInfo2Str + setPortInfo2Str + prefix + ...
    setSfcnInfoStr + postfix
%endfunction
 
%%Function:SLibAllocateStatesInfo2MemForChildSfcn===============================
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/codeGen/tg1375551.m
%%
%function SLibAllocateStatesInfo2MemForChildSfcn(s, childIdx, underScore, ...
  usingStatic, nonInlSfcns)
  %openfile retBuf
  %assign numContStates = ContStates[0]
  %if ParamSettings.FunctionLevel == 2
    /* Allocate memory for states auxilliary information */
    {
      %if usingStatic
    static struct _ssStatesInfo2 statesInfo2;
        static ssPeriodicStatesInfo periodicStatesInfo;
        static ssJacobianPerturbationBounds jacPerturbationBounds;
    %%
        %%
        ssSetStatesInfo2(%<s>, &statesInfo2);
        ssSetPeriodicStatesInfo(%<s>, &periodicStatesInfo);
        ssSetJacobianPerturbationBounds(%<s>, &jacPerturbationBounds);
         
        %if SolverType == "VariableStep" && numContStates > 0
          ssSetAbsTolVector(%<s>, %<RTMGet("AbsTolVector")> + %);
          ssSetAbsTolControlVector(%<s>, %<RTMGet("AbsTolControlVector")> + %);
        %endif
         
      %elseif SLibIsERTCodeFormat()
    ssSetStatesInfo2(%<s>, &%<nonInlSfcns>.statesInfo2[%<childIdx>]);
    ssSetPeriodicStatesInfo(%<s>, &%<nonInlSfcns>.periodicStatesInfo[%<childIdx>]);
      %else
    struct _ssStatesInfo2 *statesInfo2 = ...
      (struct _ssStatesInfo2 *) ...
      malloc(sizeof(struct _ssStatesInfo2));
         
        ssPeriodicStatesInfo* periodicStatesInfo = (ssPeriodicStatesInfo*) malloc(sizeof(ssPeriodicStatesInfo));
         
        ssJacobianPerturbationBounds *jacPerturbationBounds = (ssJacobianPerturbationBounds*) malloc(sizeof(ssJacobianPerturbationBounds));
         
        %<RTMChkMemAndReturnIfErr("statesInfo2")>;
    ssSetStatesInfo2(%<s>, statesInfo2);
    %<RTMChkMemAndReturnIfErr("periodicStatesInfo")>;
        ssSetPeriodicStatesInfo(%<s>, periodicStatesInfo);
        %<RTMChkMemAndReturnIfErr("jacPerturbationBounds")>;
        ssSetJacobianPerturbationBounds(%<s>, jacPerturbationBounds);
           
        %if SolverType == "VariableStep" && numContStates > 0
          ssSetAbsTolVector(%<s>, %<RTMGet("AbsTolVector")> + %);
          ssSetAbsTolControlVector(%<s>, %<RTMGet("AbsTolControlVector")> + %);
                   
           %<underScore>ssSetJacobianPerturbationBoundsMinVec(%<s>, %<RTMGet("JacobianPerturbationBoundsMinVec")>);
           %<underScore>ssSetJacobianPerturbationBoundsMaxVec(%<s>, %<RTMGet("JacobianPerturbationBoundsMaxVec")>);
                         
        %endif
         
      %endif
    }
  %endif
  %closefile retBuf
  %return retBuf
%endfunction
 
%%Function:SLibAllocateMethods2MemForChildSfcn===============================
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/codeGen/tg1375551.m
%%
%function SLibAllocateMethods2MemForChildSfcn(s, childIdx, underScore, ...
  usingStatic, nonInlSfcns)
  %openfile retBuf
  %if ParamSettings.FunctionLevel == 2
    /* Allocate memory of model methods 2 */
    {
      %if usingStatic
    static struct _ssSFcnModelMethods2 methods2;
    ssSetModelMethods2(%<s>, &methods2);
      %elseif SLibIsERTCodeFormat()
    ssSetModelMethods2(%<s>, &%<nonInlSfcns>.methods2[%<childIdx>]);
      %else
    struct _ssSFcnModelMethods2 *methods2 = ...
      (struct _ssSFcnModelMethods2 *) ...
      malloc(sizeof(struct _ssSFcnModelMethods2));
    %<RTMChkMemAndReturnIfErr("methods2")>;
    ssSetModelMethods2(%<s>, methods2);
      %endif
    }
    /* Allocate memory of model methods 3 */
    {
      %if usingStatic
    static struct _ssSFcnModelMethods3 methods3;
    ssSetModelMethods3(%<s>, &methods3);
      %elseif SLibIsERTCodeFormat()
    ssSetModelMethods3(%<s>, &%<nonInlSfcns>.methods3[%<childIdx>]);
      %else
    struct _ssSFcnModelMethods3 *methods3 = ...
      (struct _ssSFcnModelMethods3 *) ...
      malloc(sizeof(struct _ssSFcnModelMethods3));
    %<RTMChkMemAndReturnIfErr("methods3")>;
    ssSetModelMethods3(%<s>, methods3);
      %endif
    }
    /* Allocate memory of model methods 4 */
    {
      %if usingStatic
    static struct _ssSFcnModelMethods4 methods4;
    ssSetModelMethods4(%<s>, &methods4);
      %elseif SLibIsERTCodeFormat()
    ssSetModelMethods4(%<s>, &%<nonInlSfcns>.methods4[%<childIdx>]);
      %else
    struct _ssSFcnModelMethods4 *methods4 = ...
      (struct _ssSFcnModelMethods4 *) ...
      malloc(sizeof(struct _ssSFcnModelMethods4));
    %<RTMChkMemAndReturnIfErr("methods4")>;
    ssSetModelMethods4(%<s>, methods4);
      %endif
    }
  %endif
  %closefile retBuf
  %return retBuf
%endfunction
 
%%Function:SLibSetupInputsForChildSfcn======================================
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/tmMultiRateAsyncTask_VC1.m
%%TopTester:test/toolbox/simulink/blocks/sb2sl/tsb2slmdlref2.m
%%
%function SLibSetupInputsForChildSfcn(s, childIdx, underScore, ...
  usingStatic, nonInlSfcns)
  %assign thisBlock = ChildSFunctionList[childIdx]
  %openfile retBuf
  %if (CodeFormat == "S-Function" && UsingMalloc && ...
    ParamSettings.FunctionLevel == 2) || ...
    IsModelReferenceSimTarget()
    %% Always setup function pointer for _mid.h since level 2
    %% child s-f dll will use it.
    ssSetRegNumInputPortsFcn(%<s>, ...
      (_ssRegNumInputPortsFcn)RegNumInputPorts);
    ssSetRegNumInputPortsFcnArg(%<s>,%<s>);
  %endif
  %if NumDataInputPorts > 0
    %assign SfcnIdx = "%<nonInlSfcns>.Sfcn%<childIdx>"
 
    /* inputs */
    %switch ParamSettings.FunctionLevel
      %case 1
    %%
    %% Level 1 S-function
    %%
    %assign uWidth = LibGetRecordWidth(DataInputPort)
    %assign inputsContiguous = ...
      (ParamSettings.InputContiguous == "yes")
    %assign usingUPtrs = (ParamSettings.UsingUPtrs == "yes")
    %if usingUPtrs
      {
        %%
        %% Using UPtrs
        %%
        %if usingStatic
          static real_T const *sfcnUPtrs[%<uWidth>];
        %elseif SLibIsERTCodeFormat()
          real_T const **sfcnUPtrs = /
          (real_T const **) &%<SfcnIdx>.UPtrs;
        %else
          real_T const **sfcnUPtrs =
          (real_T const **) malloc(%<uWidth> * sizeof(real_T *));
          %<RTMChkMemAndReturnIfErr("sfcnUPtrs")>;
        %endif
        %assign rollVars = ["U"]
        %roll idx = RollRegions, lcv = RollThreshold, thisBlock, ...
          "Roller", rollVars
          %assign lhs = LibGetIndexedElement("sfcnUPtrs", ...
        uWidth, lcv, idx)
          %<lhs> = %<LibBlockInputSignalAddr(0, "", lcv, idx)>;
        %endroll
        %<underScore>ssSetUPtrs(%<s>, &sfcnUPtrs[0]);
      }
    %elseif !inputsContiguous
      %assign errTxt = "Level 1 S-function not using uPtrs and " ...
        "inputs are not contiguous"
      %<LibBlockReportFatalError(thisBlock,errTxt)>
    %else
      %%
      %% Not using uPtrs and inputs are contiguous.
      %% Set pointer to start of input signal.
      %%
      %<underScore>ssSetU(%<s>, (void *)...
        %<LibBlockInputSignalAddr(0,"","",0)>);
    %endif
    %break
      %case 2
    %%
    %% Level 2 S-Function
    %%
    {
      %%
      %% InputPortInfo
      %%
      %if usingStatic
        static struct _ssPortInputs inputPortInfo[%<NumDataInputPorts>];
        _ssSetNumInputPorts(%<s>, %<NumDataInputPorts>);
        ssSetPortInfoForInputs(%<s>, &inputPortInfo[0]);
      %elseif SLibIsERTCodeFormat()
        _ssSetNumInputPorts(%<s>, %<NumDataInputPorts>);
        ssSetPortInfoForInputs(%<s>, &%<SfcnIdx>.inputPortInfo[0]);
      %else
        struct _ssPortInputs *inputPortInfo =
        (struct _ssPortInputs *) calloc(%<NumDataInputPorts>, ...
          sizeof(struct _ssPortInputs));
        %<RTMChkMemAndReturnIfErr("inputPortInfo")>;
        _ssSetNumInputPorts(%<s>, %<NumDataInputPorts>);
        ssSetPortInfoForInputs(%<s>, &inputPortInfo[0]);
      %endif
 
          %% Setup the following for each input port
          %% o) Input Port Unit structure
          %%
          %% o) Assign default unit Id to each port
          %if NumDataInputPorts>0
            %if usingStatic
              {
                static struct _ssInPortUnit inputPortUnits[%<NumDataInputPorts>];
                _ssSetPortInfo2ForInputUnits(%<s>, &inputPortUnits[0]);
              }
            %elseif SLibIsERTCodeFormat()
              _ssSetPortInfo2ForInputUnits(%<s>, &%<SfcnIdx>.inputPortUnits[0]);
            %else
              {
                struct _ssInPortUnit *inputPortUnits =
                (struct _ssInPortUnit *) calloc(%<NumDataInputPorts>, ...
                  sizeof(struct _ssInPortUnit));
                %<RTMChkMemAndReturnIfErr("inputPortUnits")>;
                _ssSetPortInfo2ForInputUnits(%<s>, &inputPortUnits[0]);
              }
            %endif
          %endif
          %foreach ipIdx = NumDataInputPorts
            ssSetInputPortUnit(%<s>, %<ipIdx>, %<LibBlockInputSignalUnitId(ipIdx)>);
          %endforeach
           
          %% Setup the following for each input port
          %% o) Input Port CoSimAttribute structure
          %%
          %% o) Assign default cosim attribute to each port
          %if NumDataInputPorts>0
            %if usingStatic
              {
                static struct _ssInPortCoSimAttribute inputPortCoSimAttribute[%<NumDataInputPorts>];
                _ssSetPortInfo2ForInputCoSimAttribute(%<s>, &inputPortCoSimAttribute[0]);
              }
            %elseif SLibIsERTCodeFormat()
              _ssSetPortInfo2ForInputCoSimAttribute(%<s>, &%<SfcnIdx>.inputPortCoSimAttribute[0]);
            %else
              {
                struct _ssInPortCoSimAttribute *inputPortCoSimAttribute =
                (struct _ssInPortCoSimAttribute *) calloc(%<NumDataInputPorts>, ...
                  sizeof(struct _ssInPortCoSimAttribute));
                %<RTMChkMemAndReturnIfErr("inputPortCoSimAttribute")>;
                _ssSetPortInfo2ForInputCoSimAttribute(%<s>, &inputPortCoSimAttribute[0]);
              }
            %endif
          %endif
          %foreach ipIdx = NumDataInputPorts
            ssSetInputPortIsContinuousQuantity(%<s>, %<ipIdx>, %<LibBlockInputPortIsContinuousQuantity(ipIdx)>);
          %endforeach
           
          %%
      %% Setup the following for each input port:
      %%
      %% o) InputSignal or
      %% InputSignalPtrs
      %%
      %% o) InputPortRequiredContiguous
      %%
      %% o) InputPort dimensional data memory and one of
      %% InputPortVectorDimension (info) or
      %% InputPortMatrixDimensions (info)
      %%
          %if FcnBlockHasVarDimsInput()
            %assign num_vardims_input = FcnBlockNumVarDimsInput()
            %if usingStatic
              {
                static struct _ssInPortVarDims inputPortCurrentDims[%<num_vardims_input>];
                _ssSetPortInfo2ForInputs(%<s>, &inputPortCurrentDims[0]);
              }
            %elseif SLibIsERTCodeFormat()
                _ssSetPortInfo2ForInputs(%<s>, &%<SfcnIdx>.inputPortCurrentDims[0]);
            %else
              {
                struct _ssInPortVarDims *inputPortCurrentDims =
                (struct _ssInPortVarDims *) calloc(%<num_vardims_input>, ...
                  sizeof(struct _ssInPortVarDims));
                %<RTMChkMemAndReturnIfErr("inputPortCurrentDims")>;
                _ssSetPortInfo2ForInputs(%<s>, &inputPortCurrentDims[0]);
              }
            %endif
          %endif
           
          %assign vipIdx = 0
          %% vipIdx == 0 means the first variable-dimension input port
          %% vipIdx == 1 means the second variable-dimension input port
          %% ....
             
          %foreach ipIdx = NumDataInputPorts
         
        /* port %<ipIdx> */
        {
          %assign ip = DataInputPort[ipIdx]
          %assign dtype = SLibGetRecordDataTypeName(ip,"")
          %assign width = LibBlockInputSignalWidth(ipIdx)
          %assign dims = LibBlockInputSignalDimensions(ipIdx)
          %assign nDims = LibBlockInputSignalNumDimensions(ipIdx)
          %if ParamSettings.UsingUPtrs[ipIdx] == "yes"
        %if usingStatic
          static %<dtype> const *sfcnUPtrs[%<width>];
          %if %<nDims> >= matrixDimensionThreshhold
            static int_T dimensions[%<nDims>];
          %endif
        %elseif SLibIsERTCodeFormat()
          %<dtype> const **sfcnUPtrs = /
          (%<dtype> const **) &%<SfcnIdx>.UPtrs%<ipIdx>;
          %if nDims >= matrixDimensionThreshhold
            int_T *dimensions = (int_T *) &%<SfcnIdx>.iDims%<ipIdx>;
          %endif
        %else
          %if %<nDims> >= matrixDimensionThreshhold
            %if CodeFormat == "S-Function"
              #if defined(MATLAB_MEX_FILE)
              /* If the child S-function defines its port dimensions
              * as DYNAMIC_DIMENSION Simlulink will free this memory
              * and reallocate it. Therefore it must be allocated
              * using utMalloc .
              */
              int_T *dimensions = (int_T *) ...
            utMalloc(%<nDims> * sizeof(int_T));
              #else
              int_T *dimensions = (int_T *) ...
            malloc(%<nDims> * sizeof(int_T));
              #endif
            %else
              int_T *dimensions = (int_T *) ...
            malloc(%<nDims> * sizeof(int_T));
            %endif %% CodeFormat == "S-Function"
          %endif %% nDims >= matrixDimensionThreshhold
          %<dtype> const **sfcnUPtrs = (%<dtype> const **)
          malloc(%<width> * sizeof(%<dtype> *));
          %if %<nDims> >= matrixDimensionThreshhold
            %<RTMChkMemAndReturnIfErr("dimensions")>;
          %endif
          %<RTMChkMemAndReturnIfErr("sfcnUPtrs")>;
        %endif
        %if CodeFormat == "S-Function"
          %foreach sigIdx = width
            %assign rec = SLibGetSourceMapInfo(ip, sigIdx)
            %if rec.mapSrc == "U"
              %% When setting up Input Pointers for child
              %% s-functions of a parent model being generated as
              %% an s-function,
              %% need to use the Input Ptrs already
              %% setup for the parent. Otherwise, they will get
              %% setup by getting the address of the first Input
              %% Ptr of the parent using
              %% using the External Inputs structure names(via
              %% LibBlockInputSignal) to walk through the
              %% ptrs for
              %% all the child s-functions. That is incorrect
              %% since the inputs ptrs are NOT contiguous in
              %% memory for the parent model, but are setup
              %% according to their ports.
              %assign u = RTMGetIdxed("InputPortSignalPtrs", ...
            rec.mapIdx) + "[%<rec.signalOffset>]"
              sfcnUPtrs[%<sigIdx>] = (%<dtype> const *) %<u>;
            %else
              %assign u = ...
            LibBlockInputSignalAddr(ipIdx, "", "", sigIdx)
              sfcnUPtrs[%<sigIdx>] = (%<dtype> const *) %<u>;
            %endif
          %endforeach %% sigIdx = width
        %else
          %assign rollVars = ["u%<ipIdx>"]
          %with ip
            %assign rollRegion = RollRegions
          %endwith
          %roll idx = rollRegion, lcv = RollThreshold, ...
            thisBlock, "Roller", rollVars
            %assign lhs = LibGetIndexedElement("sfcnUPtrs", ...
              width,lcv,idx)
            %<lhs> = %<LibBlockInputSignalAddr(ipIdx,"",lcv,idx)>;
          %endroll
        %endif
        %<underScore>ssSetInputPortSignalPtrs(%<s>, %<ipIdx>, ...
          (InputPtrsType)&sfcnUPtrs[0]);
          %else %% Level 2, not using uPtrs
        %if ParamSettings.InputContiguous[ipIdx] == "yes"
          %if %<nDims> >= matrixDimensionThreshhold
            %if usingStatic
              %if %<nDims> >= matrixDimensionThreshhold
            static int_T dimensions[%<nDims>];
              %endif
            %elseif SLibIsERTCodeFormat()
              %if nDims >= matrixDimensionThreshhold
            int_T *dimensions = /
            (int_T *) &%<SfcnIdx>.iDims%<ipIdx>;
              %endif
            %else
              %if CodeFormat == "S-Function"
            #if defined(MATLAB_MEX_FILE)
            /* If the child S-function defines its port dimensions
            * as DYNAMIC_DIMENSION Simlulink will free this memory
            * and reallocate it. Therefore it must be allocated
            * using utMalloc.
            */
            int_T *dimensions = (int_T *) ...
              utMalloc(%<nDims> * sizeof(int_T));
            #else
            int_T *dimensions = (int_T *) ...
              malloc(%<nDims> * sizeof(int_T));
            #endif
              %else
            int_T *dimensions = (int_T *) ...
              malloc(%<nDims> * sizeof(int_T));
              %endif
              %<RTMChkMemAndReturnIfErr("dimensions")>;
            %endif
          %endif
          %assign sigAddr = LibBlockInputSignalAddr(ipIdx,"","",0)
          ssSetInputPortRequiredContiguous(%<s>, %<ipIdx>, 1);
          %<underScore>ssSetInputPortSignal(%<s>, %<ipIdx>, ...
            %<sigAddr>);
        %else
          %assign errTxt = "Level 2 S-function not using " ...
            "uPtrs and inputs are not contiguous"
          %<LibBlockReportFatalError(thisBlock,errTxt)>
        %endif
          %endif
          %% Set dimensional info values
          %if %<nDims> >= matrixDimensionThreshhold
        %if %<nDims> >= matrixDimensionThreshhold
                  %foreach Idx = nDims
                    dimensions[%<Idx>] = %;
                  %endforeach
        %endif
        _ssSetInputPortDimensionsPtr(%<s>, %<ipIdx>, dimensions);
          %endif
          _ssSetInputPortNumDimensions(%<s>, %<ipIdx>, %<nDims>);
          ssSetInputPortWidth(%<s>, %<ipIdx>, %<width>);
              %if LibGetIsInputPortVarDims(ipIdx)
                %assign dwork_var = SLibGetCurrentInputPortDimensions(ipIdx, 0)
                _ssSetInputPortVariableDimsPtr(%<s>, ...
                  %<vipIdx>, &%<dwork_var>);
                %assign vipIdx = vipIdx + 1
              %endif
        }
      %endforeach
    }
    %break
    %endswitch
  %endif %% NumDataInputPorts > 0
   
  %closefile retBuf
  %return retBuf
%endfunction
 
%%Function:SLibSetupOutputsForChildSfcn======================================
%%TopTester:test/toolbox/simulink/blocks/sb2sl/tsb2slmdlref2.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/tVariantSource3.m
%%
%function SLibSetupOutputsForChildSfcn(s, childIdx, underScore, ...
  usingStatic, nonInlSfcns)
  %assign thisBlock = ChildSFunctionList[childIdx]
 
  %openfile retBuf
  %if (CodeFormat == "S-Function" && UsingMalloc && ...
    ParamSettings.FunctionLevel == 2) || ...
    IsModelReferenceSimTarget()
    %% Always setup function pointer for _mid.h since level 2
    %% child s-f dll will use it.
    ssSetRegNumOutputPortsFcn(%<s>, ...
      (_ssRegNumOutputPortsFcn)RegNumOutputPorts);
    ssSetRegNumOutputPortsFcnArg(%<s>,%<s>);
  %endif
   
  %if NumDataOutputPorts > 0
    %assign SfcnIdx = "%<nonInlSfcns>.Sfcn%<childIdx>"
 
    /* outputs */
    %switch ParamSettings.FunctionLevel
      %case 1
    %assign op = FcnGetOutputPortRecord(0)
    %assign idNum = IDNUM(op.SignalSrc[0])
    %if idNum[0] == "F" %%FcnCall
      %<underScore>ssSetY(%<s>, %<SLibGetNullDefinitionFromTfl()>);
    %else
      %assign dt = LibBlockOutputSignalDataTypeName(0, "")
      %<underScore>ssSetY(%<s>, ...
        ((%<dt> *) %<LibBlockOutputSignalAddr(0,"","",0)>));
    %endif
    %break
     
      %case 2
    {
      %if usingStatic
        static struct _ssPortOutputs outputPortInfo[%<NumDataOutputPorts>];
        ssSetPortInfoForOutputs(%<s>, &outputPortInfo[0]);
      %elseif SLibIsERTCodeFormat()
        ssSetPortInfoForOutputs(%<s>, &%<SfcnIdx>.outputPortInfo[0]);
      %else
        struct _ssPortOutputs *outputPortInfo = ...
          (struct _ssPortOutputs *)
        calloc(%<NumDataOutputPorts>, ...
          sizeof(struct _ssPortOutputs));
        %<RTMChkMemAndReturnIfErr("outputPortInfo")>;
        ssSetPortInfoForOutputs(%<s>, &outputPortInfo[0]);
      %endif
      _ssSetNumOutputPorts(%<s>, %<NumDataOutputPorts>);
 
           
          %% Setup the following for each output port
          %% o) Output Port Unit structure
          %%
          %% o) Assign default unit Id to each port
          %if NumDataOutputPorts>0
            %if usingStatic
              {
                static struct _ssOutPortUnit outputPortUnits[%<NumDataOutputPorts>];
                _ssSetPortInfo2ForOutputUnits(%<s>, &outputPortUnits[0]);
              }
            %elseif SLibIsERTCodeFormat()
              _ssSetPortInfo2ForOutputUnits(%<s>, &%<SfcnIdx>.outputPortUnits[0]);
            %else
              {
                struct _ssOutPortUnit *outputPortUnits =
                (struct _ssOutPortUnit *) calloc(%<NumDataOutputPorts>, ...
                  sizeof(struct _ssOutPortUnit));
                %<RTMChkMemAndReturnIfErr("outputPortUnits")>;
                _ssSetPortInfo2ForOutputUnits(%<s>, &outputPortUnits[0]);
              }
            %endif
          %endif
           
          %foreach opIdx = NumDataOutputPorts
            ssSetOutputPortUnit(%<s>, %<opIdx>, %<LibBlockOutputSignalUnitId(opIdx)>);
          %endforeach
           
          %% Setup the following for each output port
          %% o) Output Port CoSimAttribute structure
          %%
          %% o) Assign default cosim attribute to each port
          %if NumDataOutputPorts>0
            %if usingStatic
              {
                static struct _ssOutPortCoSimAttribute outputPortCoSimAttribute[%<NumDataOutputPorts>];
                _ssSetPortInfo2ForOutputCoSimAttribute(%<s>, &outputPortCoSimAttribute[0]);
              }
            %elseif SLibIsERTCodeFormat()
              _ssSetPortInfo2ForOutputCoSimAttribute(%<s>, &%<SfcnIdx>.outputPortCoSimAttribute[0]);
            %else
              {
                struct _ssOutPortCoSimAttribute *outputPortCoSimAttribute =
                (struct _ssOutPortCoSimAttribute *) calloc(%<NumDataOutputPorts>, ...
                  sizeof(struct _ssOutPortCoSimAttribute));
                %<RTMChkMemAndReturnIfErr("outputPortCoSimAttribute")>;
                _ssSetPortInfo2ForOutputCoSimAttribute(%<s>, &outputPortCoSimAttribute[0]);
              }
            %endif
          %endif
          %foreach ipIdx = NumDataOutputPorts
            ssSetOutputPortIsContinuousQuantity(%<s>, %<ipIdx>, %<LibBlockOutputPortIsContinuousQuantity(ipIdx)>);
          %endforeach
           
          %if FcnBlockHasVarDimsOutput()
            %assign num_vardims_output = FcnBlockNumVarDimsOutput()
            %if usingStatic
              {
                static struct _ssOutPortVarDims outputPortCurrentDims[%<num_vardims_output>];
                _ssSetPortInfo2ForOutputs(%<s>, &outputPortCurrentDims[0]);
              }
            %elseif SLibIsERTCodeFormat()
                _ssSetPortInfo2ForOutputs(%<s>, &%<SfcnIdx>.outputPortCurrentDims[0]);
            %else
              {
                struct _ssOutPortVarDims* outputPortCurrentDims =
                (struct _ssOutPortVarDims *) calloc(%<num_vardims_output>,
                sizeof(struct _ssOutPortVarDims));
                %<RTMChkMemAndReturnIfErr("outputPortCurrentDims")>;
                _ssSetPortInfo2ForOutputs(%<s>, &outputPortCurrentDims[0]);
              }
            %endif
          %endif
           
          %assign vopIdx = 0
          %% vopIdx tells that this output port is the n'th variable-dimension
          %% output port
           
      %foreach opIdx = NumDataOutputPorts
        /* port %<opIdx> */
        {
          %assign oWidth = LibBlockOutputSignalWidth(opIdx)
          %assign oNumDims = LibBlockOutputSignalNumDimensions(opIdx)
          %assign oDims = LibBlockOutputSignalDimensions(opIdx)
          %if %<oNumDims> >= matrixDimensionThreshhold
        %if usingStatic
          %if %<oNumDims> >= matrixDimensionThreshhold
            static int_T dimensions[%<oNumDims>];
          %endif
        %elseif SLibIsERTCodeFormat()
          %if oNumDims >= matrixDimensionThreshhold
            int_T *dimensions = (int_T *) &%<SfcnIdx>.oDims%<opIdx>;
          %endif
        %else
          %if CodeFormat == "S-Function"
            #if defined(MATLAB_MEX_FILE)
            /* If the child S-function defines its dimensions as
            * DYNAMIC_DIMENSION Simlulink will free this memory
            * and reallocate it. Therefor it must be allocated
            * using utMalloc .
            */
            int_T *dimensions = (int_T *) ...
              utMalloc(%<oNumDims> * sizeof(int_T));
            #else
            int_T *dimensions = (int_T *) ...
              malloc(%<oNumDims> * sizeof(int_T));
            #endif
          %else
            int_T *dimensions = (int_T *) ...
              malloc(%<oNumDims> * sizeof(int_T));
          %endif
        %endif
                %foreach Idx = oNumDims
                  dimensions[%<Idx>] = %;
                %endforeach
        _ssSetOutputPortDimensionsPtr(%<s>, %<opIdx>, dimensions);
          %endif
          _ssSetOutputPortNumDimensions(%<s>, %<opIdx>, %<oNumDims>);
          ssSetOutputPortWidth(%<s>, %<opIdx>, %<oWidth>);
          %assign op = FcnGetOutputPortRecord(opIdx)
          %assign idNum = IDNUM(op.SignalSrc[0])
          %if idNum[0] == "F" %%FcnCall
        %<underScore>ssSetOutputPortSignal(%<s>, %<opIdx>, %<SLibGetNullDefinitionFromTfl()>);
          %else
        %assign dt = LibBlockOutputSignalDataTypeName(opIdx, "")
        %assign yAddr = LibBlockOutputSignalAddr(opIdx, "", "", 0)
        %<underScore>ssSetOutputPortSignal(%<s>, ...
          %<opIdx>, ((%<dt> *) %<yAddr>));
          %endif
               
              %if LibGetIsOutputPortVarDims(opIdx)
                %assign dwork_var = SLibGetCurrentOutputPortDimensions(opIdx, 0)
                _ssSetOutputPortVariableDimsPtr(%<s>, ...
                  %<vopIdx>, &%<dwork_var>);
                %assign vopIdx = vopIdx + 1
              %endif
        }
      %endforeach
    }
    %break
    %endswitch
  %endif %% NumDataOutputPorts
  %closefile retBuf
   
  %return retBuf
%endfunction
 
 
%%Function:SLibSetupStatesForChildSfcn=======================================
%%TopTester:test/toolbox/simulink/blocks/sb2sl/tsb2slmdlref.m
%%
%function SLibSetupStatesForChildSfcn(s, childIdx, underScore, ...
  usingStatic, nonInlSfcns)
  %openfile retBuf
  %assign numDiscStates = DiscStates[0]
  %assign numContStates = ContStates[0]
  %assign nStates = numDiscStates + numContStates
  %if nStates > 0
    %assign SfcnIdx = "%<nonInlSfcns>.Sfcn%<childIdx>"
 
    /* states */
    %switch ParamSettings.FunctionLevel
      %case 1
    %%
    %% Level 1 S-Function
    %%
    %if StatesDiscontiguous == 1
      %% states are discontiguous
      {
        %if usingStatic
          static real_T sfcnX[%<nStates>];
        %elseif SLibIsERTCodeFormat()
          real_T *sfcnX = (real_T *) &%<SfcnIdx>.X[0];
        %else
          real_T *sfcnX = (real_T *) ...
        malloc(%<nStates> * sizeof(real_T));
          %<RTMChkMemAndReturnIfErr("sfcnX")>;
        %endif
        (void) %<LibGenMemFcnCall("memset", "(void*)sfcnX", "0", ...
          "sizeof(real_T)*%<nStates>")>;
        %<underScore>ssSetContStates(%<s>, &sfcnX[0]);
      }
    %elseif numContStates > 0
      %% s-function has only continuous states
      %<underScore>ssSetContStates(%<s>, ...
        &%<LibBlockContinuousState("", "", 0)>);
          %if(ISEQUAL(::CompiledModel.SolverType, "VariableStep"))
            %<underScore>ssSetContStateDisabled(%<s>, ...
              &%<LibBlockContStateDisabled("", "", 0)>);
            {
              real_T* minVec = %<"&"+ LibBlockContStatePerturbMin("", "", 0)>;
              real_T* maxVec = %<"&"+ LibBlockContStatePerturbMax("", "", 0)>;
              %<underScore>ssSetJacobianPerturbationBoundsMinVec(%<s>, minVec);
              %<underScore>ssSetJacobianPerturbationBoundsMaxVec(%<s>, maxVec);
            }
                         
          %endif
    %else
      %% s-function has only discrete states
      %<underScore>ssSetContStates(%<s>, ...
        &%<LibBlockDiscreteState("", "", 0)>);
    %endif
    %break
     
      %case 2
    %%
    %% Level 2 S-Function
    %%
    %if numContStates > 0
      %% s-function has only continuous states
      %<underScore>ssSetContStates(%<s>, ...
        &%<LibBlockContinuousState("", "", 0)>);
          %if(ISEQUAL(::CompiledModel.SolverType, "VariableStep"))
            %<underScore>ssSetContStateDisabled(%<s>, ...
              &%<LibBlockContStateDisabled("", "", 0)>);
            {
              real_T* minVec = %<"&"+ LibBlockContStatePerturbMin("", "", 0)>;
              real_T* maxVec = %<"&"+ LibBlockContStatePerturbMax("", "", 0)>;
              %<underScore>ssSetJacobianPerturbationBoundsMinVec(%<s>, minVec);
              %<underScore>ssSetJacobianPerturbationBoundsMaxVec(%<s>, maxVec);
            }
             
          %endif
    %endif
    %if numDiscStates > 0
      %% s-function has only discrete states
      %<underScore>ssSetDiscStates(%<s>, ...
        (real_T *) &%<LibBlockDiscreteState("", "", 0)>);
    %endif
    %break
    %endswitch
  %endif %% nStates > 0
  %closefile retBuf
   
  %return retBuf
%endfunction
 
 
%%Function:SLibSetupPathInfoForChildSfcn=====================================
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/tmMultiRateAsyncTask_VC1.m
%%TopTester:test/toolbox/simulink/blocks/sb2sl/tsb2slmdlref2.m
%%
%function SLibSetupPathInfoForChildSfcn(s, childIdx, underScore, ...
  usingStatic, nonInlSfcns)
  %assign thisBlock = ChildSFunctionList[childIdx]
   
  %assign raccelUseMexFile = ...
    ::isRAccel && ParamSettings.WillBeDynamicallyLoaded == "yes"
 
  %openfile retBuf
  /* path info */
  %if CodeFormat == "S-Function" || IsModelReferenceSimTarget() || raccelUseMexFile
    %<underScore>ssSetModelName(%<s>, ...
      "%<thisBlock.ParamSettings.FunctionName>");
  %else
    %if ISFIELD(thisBlock,"SLName")
      %assign sysName = SYSNAME(SLName)
    %else
      %if BlockCommentType == "BlockSIDComment"
        %assign rtwName = FEVAL("coder.internal.convertBlockSIDNameToRTWName", "%<LibGetModelName()>", Name)
        %assign sysName = SYSNAME(rtwName)
      %else
        %assign sysName = SYSNAME(Name)
      %endif
    %endif
    %<underScore>ssSetModelName(%<s>, "%<STRING(sysName[1])>");
  %endif
  %assign pathName = LibGetFormattedBlockPath(thisBlock)
  %<underScore>ssSetPath(%<s>, "%<pathName>");
  %if GenRTModel
    %if !IsModelReferenceSimTarget()
      %%
      %% There is no root SimStruct
      %%
      ssSetRTModel(%<s>,%<GetSimStructExpr(System[GetBaseSystemIdx()], ::tSimStruct)>);
      %<underScore>ssSetParentSS(%<s>, %<SLibGetNullDefinitionFromTfl()>);
      %<underScore>ssSetRootSS(%<s>, %<s>);
    %else
      ssSetRTModel(%<s>,%<GetSimStructExpr(System[GetBaseSystemIdx()], ::tSimStruct)>);
      %<underScore>ssSetParentSS(%<s>, %<tMdlRefSfcnS>);
      %<underScore>ssSetRootSS(%<s>, ssGetRootSS(%<tMdlRefSfcnS>));
    %endif
  %else
    if (ssGetRTModel(%<::tSimStruct>) == %<SLibGetNullDefinitionFromTfl()>) {
      %<underScore>ssSetParentSS(%<s>, %<RTMGetModelSS()>);
      %<underScore>ssSetRootSS(%<s>, %<RTMGet("RootSS")>);
    } else {
      ssSetRTModel(%<s>,ssGetRTModel(%<::tSimStruct>));
      %<underScore>ssSetParentSS(%<s>, %<SLibGetNullDefinitionFromTfl()>);
      %<underScore>ssSetRootSS(%<s>, %<s>);
    }
  %endif
  %if ParamSettings.FunctionLevel == 1
    ssSetVersion(%<s>, SIMSTRUCT_VERSION_LEVEL1);
  %else
    ssSetVersion(%<s>, SIMSTRUCT_VERSION_LEVEL2);
  %endif
  %closefile retBuf
   
  %return retBuf
%endfunction
 
%%Function:SLibSetupSfcnParamsForChildSfcn==================================
%%TopTester:test/toolbox/simulink/blocks/sb2sl/tsb2slmdlref.m
%%TopTester:test/toolbox/simulink/blocks/sb2sl/tsb2slmdlref2.m
%function SLibSetupSfcnParamsForChildSfcn(s, childIdx, underScore, ...
  usingStatic, nonInlSfcns)
  %openfile retBuf
  %%
  %% S-Function parameters
  %%
  %assign numArgs = Parameters[0] / 2
  %if numArgs > 0
    %assign SfcnIdx = "%<nonInlSfcns>.Sfcn%<childIdx>"
    %%
    %% Set S-function parameters to point to model rtP / rtcP parameters
    %%
    %openfile tmpBuffer
    %foreach argIdx = numArgs
      %assign paramIdx = argIdx + 1
      %assign paramName = "P%<paramIdx>Size"
      %assign paramAddr = LibBlockParameterAddr(%<paramName>,"","",0)
      %<underScore>ssSetSFcnParam(%<s>, %<argIdx>, (mxArray*)%<paramAddr>);
    %endforeach
    %closefile tmpBuffer
    %%
    %%
     
    /* parameters */
    {
      %if usingStatic
    static mxArray *sfcnParams[%<numArgs>];
      %elseif SLibIsERTCodeFormat()
    mxArray **sfcnParams = /
    (mxArray **) &%<SfcnIdx>.params;
      %else
    mxArray **sfcnParams = (mxArray **) malloc(%<numArgs> * sizeof(mxArray *));
    %<RTMChkMemAndReturnIfErr("sfcnParams")>;
      %endif
       
      %<underScore>ssSetSFcnParamsCount(%<s>, %<numArgs>);
      %<underScore>ssSetSFcnParamsPtr(%<s>, &sfcnParams[0]);
 
%if CodeFormat == "S-Function" || IsModelReferenceSimTarget()
    %%
    %% This is a non-inlined user (hand-written) S-Function that
    %% is being embedded into an generated S-Function.
    %%
    %% Need to setup the support structure _ssSFcnParams
    %% so that the underlying (level 2) S-functions can make
    %% calls to ssSetSFcnParamNotTunable, etc.
    %%
    %if LibSFunctionLevel() == "Level2"
      #if defined(MATLAB_MEX_FILE)
      {
        %if usingStatic
          static uint_T attribs[%<numArgs>];
        %elseif SLibIsERTCodeFormat()
          uint_T *attribs = (uint_T *) &%<SfcnIdx>.attribs;
        %else
          uint_T *attribs;
          attribs = (uint_T *) ...
        mxCalloc(%<numArgs>, sizeof(uint_T));
          mexMakeMemoryPersistent(attribs);
        %endif
         
        ssSetSFcnParamAttribsPtr(%<s>, &attribs[0]);
        (void) %<LibGenMemFcnCall("memset", "(void *)&attribs[0]", ...
          " 0", " %<numArgs> * sizeof(uint_T)")>;
      }
      #endif
    %endif
    %%
    %% For non-inlined user s-functions need to make pararmeters an
    %% MATLAB mxArray, not the simplified mxArray version of used in
    %% code generation. Only when MATLAB_MEX_FILE since the dll has
    %% been compiled for the MATLAB version of an mxArray.
    %%
        %<SLibWriteSFunctionGuards("if")>
          mxArray *param;
      int_T i;
      real_T *vals;
       
      %foreach argIdx = numArgs
        %assign paramIdx = argIdx + 1
        %assign paramVal = "P%<paramIdx>"
            %assign prmValue = SLibGetValueFromParamRec(Parameter[argIdx*2], TLC_FALSE)
        %assign mSize = CAST("Number", prmValue[0])
        %assign nSize = CAST("Number", prmValue[1])
            %assign bufferLen = mSize * nSize
        %if LibGetRecordIsComplex(Parameter[argIdx*2+1])
          %assign nSize = 2*nSize
        %endif
         
        %assign data = ...
          LibBlockMatrixParameterAddr(%<paramVal>, "", "", ...
          0, "", "", 0)
        %if SLibGetBlockParameterStorageClass(%<paramVal>) == "Auto_SFCN"
          %% Point this childs parameter to the tunable parameter
          %% directly. This is only when the child s-function in not
          %% an expression.
          %assign tunableParam = ...
        SLibGetBlockParameterIdentifier(%<paramVal>)
          %<underScore>ssSetSFcnParam(%<s>, %<argIdx>, /
          %<tunableParam>(%<RTMGetModelSS()>));
        %else
          param = mxCreateDoubleMatrix(%<mSize>,%<nSize>,mxREAL);
          mexMakeArrayPersistent(param);
          %if mSize*nSize > 0
        vals = (real_T *) %<data>;
        for (i = 0; i < %<bufferLen>; i++) {
          mxGetPr(param)[i] = vals[i];
        }
          %endif
          %<underScore>ssSetSFcnParam(%<s>, %<argIdx>, param);
        %endif
         
      %endforeach
        %<SLibWriteSFunctionGuards("else")>
        %<tmpBuffer>/
        %<SLibWriteSFunctionGuards("endif")>
      %else
    %%
    %% Not S-Function code format
    %%
    %<tmpBuffer>/
 
      %endif
    }
  %endif %% numArgs > 0
  %closefile retBuf
   
  %return retBuf
%endfunction
 
%%Function:SLibSetupWorksForChildSfcn=======================================
%%TopTester:test/toolbox/simulink/blocks/sb2sl/tsb2slmdlref.m
%%
%function SLibSetupWorksForChildSfcn(s, childIdx, underScore, ...
  usingStatic, nonInlSfcns)
  %%
  %% RWork, IWork, PWork, DWork and Mode
  %%
  %assign thisBlock = ChildSFunctionList[childIdx]
  %assign numRWorks = RWork[0]
  %assign numIWorks = IWork[0]
  %assign numPWorks = PWork[0]
  %assign numDWorks = thisBlock.NumDWork
  %assign numModes = ModeVector[0]
  %openfile tmpBuffer
  %if numRWorks > 0
    %<underScore>ssSetRWork(%<s>, (real_T *) ...
      &%<LibBlockRWork(RWork, "", "", 0)>);
  %endif
  %if numIWorks > 0
    %<underScore>ssSetIWork(%<s>, (int_T *) ...
      &%<LibBlockIWork(IWork, "", "", 0)>);
  %endif
  %if numPWorks > 0
    %<underScore>ssSetPWork(%<s>, (void **) ...
      &%<LibBlockPWork(PWork, "", "", 0)>);
  %endif
  %if numDWorks > 0
    {
      %assign SfcnIdx = "%<nonInlSfcns>.Sfcn%<childIdx>"
 
      %if usingStatic
    static struct _ssDWorkRecord dWorkRecord[%<numDWorks>];
    static struct _ssDWorkAuxRecord dWorkAuxRecord[%<numDWorks>];
      %elseif SLibIsERTCodeFormat()
    struct _ssDWorkRecord *dWorkRecord = /
    (struct _ssDWorkRecord *) &%<SfcnIdx>.dWork;
    struct _ssDWorkAuxRecord *dWorkAuxRecord = /
    (struct _ssDWorkAuxRecord *) &%<SfcnIdx>.dWorkAux;
      %else
    struct _ssDWorkRecord *dWorkRecord = ...
      (struct _ssDWorkRecord *) malloc(%<numDWorks> * sizeof(struct _ssDWorkRecord));
    struct _ssDWorkAuxRecord *dWorkAuxRecord = ...
      (struct _ssDWorkAuxRecord *) calloc(%<numDWorks>, sizeof(struct _ssDWorkAuxRecord));
    %<RTMChkMemAndReturnIfErr("dWorkRecord")>;
    %<RTMChkMemAndReturnIfErr("dWorkAuxRecord")>;
      %endif
       
      ssSetSFcnDWork(%<s>, dWorkRecord);
      ssSetSFcnDWorkAux(%<s>, dWorkAuxRecord);
      _ssSetNumDWork(%<s>, %<numDWorks>);
       
      %foreach idx = numDWorks
    %assign dwork = DWork[idx]
    %assign dtIdCurDWork = LibGetDataTypeIdAliasedThruToFromId(...
      LibBlockDWorkDataTypeId(dwork))
    %assign dwRec = ::CompiledModel.DWorks.DWork[dwork.FirstRootIdx]
     
    /* %<dwork.Name> */
    ssSetDWorkWidth(%<s>, %<idx>, ...
      %<LibBlockDWorkWidth(dwork)>);
    %%
    %if LibIsBuiltInDataType(dtIdCurDWork)
      %assign dtEnum = LibGetDataTypeEnumFromId(dtIdCurDWork)
      ssSetDWorkDataType(%<s>, %<idx>,%<dtEnum>);
    %elseif LibIsHalfDataType(dtIdCurDWork)
      DTypeId halfID = ssRegisterDataTypeHalfPrecision(
        %<s>,
        0 /* 0 means do NOT obey data type override setting for this subsystem */ );
       ssSetDWorkDataType( %<s>, %<idx>, halfID );
    %else
      %%
      %assign curDT = FixPt_GetDataTypeFromIndex(dtIdCurDWork)
      %%
      %if curDT.IsFixedPoint
        {
          DTypeId dataTypeIdReg =
          %if FixPt_DataTypeIsFloat(curDT)
        ssRegisterDataTypeFxpScaledDouble(
          %else
        ssRegisterDataTypeFxpFSlopeFixExpBias(
          %endif
          %<s>,
          %<curDT.IsSigned>,
          %<curDT.RequiredBits>,
          %<curDT.FracSlope>,
          %<curDT.FixedExp>,
          %<curDT.Bias>,
          0 /* false means do NOT obey data type override setting for this subsystem */ );
           
          ssSetDWorkDataType( %<s>, %<idx>, dataTypeIdReg );
        }
          %else
            %assign dtEnum = LibGetDataTypeEnumFromId(dtIdCurDWork)
            %%
            %if dtEnum == "SS_POINTER" || dtEnum == "SS_INTEGER"
              ssSetDWorkDataType(%<s>, %<idx>,%<dtEnum>);
            %elseif LibSFunctionLevel() != "RTWLevel2"
               
              %assign raccelUseMexFile = ...
                ::isRAccel && ParamSettings.WillBeDynamicallyLoaded == "yes"
               
              %if !raccelUseMexFile
                %assign errTxt = "User-defined data type " ...
                  "%<LibGetDataTypeNameFromId(dtIdCurDWork)> is required " ...
                  "for DWork %<idx>, but the information needed to define this " ...
                  "data type is unknown. The generated code that normally " ...
                  "specifies the data type of this DWork is being omitted. " ...
                  "If additional custom code does not register this user-define data type " ...
                  "and set the data type of this DWork, then the generated code " ...
                  "will be incomplete."
                %<LibBlockReportWarning(thisBlock, errTxt)>
              %endif
               
            %endif
          %endif
        %endif
    ssSetDWorkComplexSignal(%<s>, %<idx>, ...
      %<LibBlockDWorkIsComplex(dwork)>);
    %if dwRec.UsedAs == "DSTATE"
      ssSetDWorkUsedAsDState(%<s>, %<idx>, 1);
    %endif
    %<underScore>ssSetDWork(%<s>, %<idx>, ...
      %<LibBlockDWorkAddr(dwork, "", "", 0)>);
      %endforeach
    }
  %endif
  %if numModes > 0
    %<underScore>ssSetModeVector(%<s>, (int_T *) ...
      &%<LibBlockMode("", "", 0)>);
  %endif
  %closefile tmpBuffer
  %openfile retBuf
  %if !WHITE_SPACE(tmpBuffer)
     
    /* work vectors */
    %<tmpBuffer>/
  %endif
  %closefile retBuf
   
  %return retBuf
%endfunction
 
%%Function:SLibSetupCallSysForChildSfcn======================================
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/tVariantSource3.m-tmMultiRateAsyncTask_VC1.m
%%
%function SLibSetupCallSysForChildSfcn(s, childIdx, underScore, ...
  usingStatic, nonInlSfcns)
  %openfile retBuf
  %%
  %% Function calls
  %%
  %if NumSFcnSysOutputCalls > 0
    %assign SfcnIdx = "%<nonInlSfcns>.Sfcn%<childIdx>"
 
    /* register function-calls */
    {
      %assign pZeroWidth = LibBlockOutputSignalWidth(0)
      %if usingStatic
    static int_T callSysOutputs[%<pZeroWidth>];
    static void *callSysArgs1[%<pZeroWidth>];
    static int_T callSysArgs2[%<pZeroWidth>];
    static SysOutputFcn callSysFcns[%<4*pZeroWidth>];
      %elseif SLibIsERTCodeFormat()
    int_T *callSysOutputs = (int_T *) &%<SfcnIdx>.callSysOutputs;
    void **callSysArgs1 = (void **) &%<SfcnIdx>.callSysArgs1;
    int_T *callSysArgs2 = (int_T *) &%<SfcnIdx>.callSysArgs2;
    SysOutputFcn *callSysFcns = (SysOutputFcn *) &%<SfcnIdx>.callSysFcns;
      %else
    int_T *callSysOutputs;
    void **callSysArgs1;
    int_T *callSysArgs2;
    SysOutputFcn *callSysFcns;
     
    callSysOutputs = (int_T *) ...
      malloc(%<LibBlockOutputSignalWidth(0)> ...
      * sizeof(int_T));
    %<RTMChkMemAndReturnIfErr("callSysOutputs")>;
     
    callSysArgs1 = (void **) ...
      malloc(%<pZeroWidth> * sizeof(void *));
    %<RTMChkMemAndReturnIfErr("callSysArgs1")>;
     
    callSysArgs2 = (int_T *) ...
      malloc(%<pZeroWidth> * sizeof(int_T));
    %<RTMChkMemAndReturnIfErr("callSysArgs2")>;
     
    callSysFcns = (SysOutputFcn *) ...
      malloc(%<4*pZeroWidth> * sizeof(SysOutputFcn));
    %<RTMChkMemAndReturnIfErr("callSysFcns")>;
     
      %endif
      %assign loopCode = SLibEmitForLoopCounterCode(pZeroWidth, "i")
      {
        %
        % {
          callSysOutputs[i] = 0;
          callSysFcns[i] = (SysOutputFcn) %<SLibGetNullDefinitionFromTfl()>;
          callSysFcns[%<pZeroWidth>+i] = (SysOutputFcn) %<SLibGetNullDefinitionFromTfl()>;
          callSysFcns[2*%<pZeroWidth>+i] = (SysOutputFcn) %<SLibGetNullDefinitionFromTfl()>;
          %if IsModelReferenceSimTarget()
            %% The Model Reference Simulation Target doesn't support
            %% Initialization function pointers
            %assign enableFcnIdx = 1
            %assign disableFcnIdx = 2
          %else
            %assign enableFcnIdx = 2
            %assign disableFcnIdx = 3
            callSysFcns[3*%<pZeroWidth>+i] = (SysOutputFcn) %<SLibGetNullDefinitionFromTfl()>;
          %endif
        }
      }
      %<underScore>ssSetCallSystemOutputPtr(%<s>, &callSysOutputs[0]);
      %<underScore>ssSetCallSystemOutputArg1List(%<s>, ...
    &callSysArgs1[0]);
      %<underScore>ssSetCallSystemOutputArg2List(%<s>, ...
    &callSysArgs2[0]);
      %<underScore>ssSetCallSystemOutputFcnList(%<s>, ...
    &callSysFcns[0]);
      %assign portEl = -1
      %foreach fcnCallIdx = NumSFcnSysOutputCallDsts
        %if portEl == SFcnSystemOutputCall[fcnCallIdx].OutputElement
          %continue
        %else
          %assign portEl = SFcnSystemOutputCall[fcnCallIdx].OutputElement
        %endif
        %with SFcnSystemOutputCall[fcnCallIdx]
      %if STRING(BlockToCall) != "unconnected"
        %assign sysIdx = BlockToCall[0]
        %assign blkIdx = BlockToCall[1]
        %assign ssBlock = ::CompiledModel.System[sysIdx].Block[blkIdx]
            %assign ppIf = ssBlock.VariantCondition
            %<SLibIfVariantConditionForm(ppIf)>
        %assign tidVal = ParamSettings.SampleTimesToSet[0][1]
        callSysArgs1[%<OutputElement>] = (void *)%<RTMGetModelSS()>;
        callSysArgs2[%<OutputElement>] = %<FcnPortElement>;
        %assign fcnCallFNI = LibGetFcnCallFNI(ssBlock,FcnPortElement,tidVal)
            %assign fcnInitializeFNI = LibGetFcnSystemResetFNI(ssBlock,FcnPortElement,tidVal)
        %assign fcnEnableFNI = LibGetFcnEnableFNI(ssBlock,FcnPortElement,tidVal)
        %assign fcnDisableFNI = LibGetFcnDisableFNI(ssBlock,FcnPortElement,tidVal)
        %assert fcnCallFNI != ""
        callSysFcns[%<OutputElement>] = (SysOutputFcn) %<fcnCallFNI>;
        %if !IsModelReferenceSimTarget()
          %if fcnInitializeFNI != ""
        callSysFcns[%<pZeroWidth>+%<OutputElement>] = (SysOutputFcn) /
        %<fcnInitializeFNI>;
          %else
        callSysFcns[%<pZeroWidth>+%<OutputElement>] = (SysOutputFcn) %<SLibGetNullDefinitionFromTfl()>;
          %endif
        %endif
        %if fcnEnableFNI != ""
          callSysFcns[%+%<OutputElement>] = (SysOutputFcn) /
          %<fcnEnableFNI>;
        %else
          callSysFcns[%+%<OutputElement>] = (SysOutputFcn) %<SLibGetNullDefinitionFromTfl()>;
        %endif
        %if fcnDisableFNI != ""
          callSysFcns[%+%<OutputElement>] = (SysOutputFcn) /
          %<fcnDisableFNI>;
        %else
          callSysFcns[%+%<OutputElement>] = (SysOutputFcn) %<SLibGetNullDefinitionFromTfl()>;
        %endif
            %<SLibEndIfVariantConditionForm(ppIf)>
        callSysOutputs[%<OutputElement>] = 1;
      %else
        /* Unconnected function-call */
        callSysArgs1[%<OutputElement>] = (void *)%<SLibGetNullDefinitionFromTfl()>;
        callSysArgs2[%<OutputElement>] = 0;
        callSysFcns[%<OutputElement>] = (SysOutputFcn) %<SLibGetNullDefinitionFromTfl()>;
        callSysFcns[%<pZeroWidth>+%<OutputElement>] = (SysOutputFcn) %<SLibGetNullDefinitionFromTfl()>;
        callSysFcns[2*%<pZeroWidth>+%<OutputElement>] = (SysOutputFcn) %<SLibGetNullDefinitionFromTfl()>;
        %if !IsModelReferenceSimTarget()
          callSysFcns[3*%<pZeroWidth>+%<OutputElement>] = (SysOutputFcn) %<SLibGetNullDefinitionFromTfl()>;
        %endif
      %endif
    %endwith
      %endforeach
      %undef sysIdx, blkIdx, ssIdx
    }
  %endif %% NumSFcnSysOutputCalls > 0
  %closefile retBuf
   
  %return retBuf
%endfunction
 
%%Function:SLibAdjustStInfoForChildSfcn=====================================
%%TopTester:test/toolbox/simulink/blocks/sb2sl/tsb2slmdlref2.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/tmMultiRateAsyncTask_VC1.m
%%
%function SLibAdjustStInfoForChildSfcn(s, childIdx, underScore, ...
  usingStatic, nonInlSfcns)
  %%
  %% May need to adjust the sample times
  %%
  %openfile tempBuffer
  %foreach idx = SIZE(ParamSettings.SampleTimesToSet, 0)
    %assign sfcnTID = ParamSettings.SampleTimesToSet[idx][0]
    %assign mdlTID = ParamSettings.SampleTimesToSet[idx][1]
    %if mdlTID < 0
      %assign period = LibRealNonFinite(inf)
      %assign offset = 0
    %else
      %assign period = ...
        CAST("Real",::CompiledModel.SampleTime[mdlTID].PeriodAndOffset[0])
      %assign offset = ...
        CAST("Real",::CompiledModel.SampleTime[mdlTID].PeriodAndOffset[1])
    %endif
    ssSetSampleTime(%<s>, %<sfcnTID>, %<period>);
    ssSetOffsetTime(%<s>, %<sfcnTID>, %<offset>);
  %endforeach
  %foreach idx = SIZE(ParamSettings.SampleTimesToSet, 0)
    %assign sfcnTID = ParamSettings.SampleTimesToSet[idx][0]
    %assign mdlTID = ParamSettings.SampleTimesToSet[idx][1]
    %if mdlTID <0
      sfcnTsMap[%<sfcnTID>] = %<mdlTID>;
    %else
      %% If this is model reference, we need to get the global
      %% TID from a parent model, which is passed in to the reg
      %if IsModelReferenceTarget()
        %% Guard against using the mdlref_TID when its not defined
        %if (!MdlRefIsConstSampleBlock() || MdlRefHasParameterRate()) && ...
          MdlRefDisallowSampleTimeInheritance()
          sfcnTsMap[%<sfcnTID>] = mdlref_TID%<mdlTID>;
        %else
          %assert SIZE(ParamSettings.SampleTimesToSet, 0) == 1
          sfcnTsMap[%<sfcnTID>] = 0;
        %endif
        %% If this is sfcn target, we need to get the
        %% TID from the SampleTimeTaskIDPtr of its parent model.
        %% TID at root model will be passed in throught SampleTimeTaskIDPtr
        %% of each sfcn simstruct.
      %elseif CodeFormat == "S-Function" || GenerateErtSFunction
        %% SampleTimeTaskIDPtr doesn't include asyncTid yet.
        %% Non-inlined sfcn can not get correct TID value in
        %% parent model through SampleTimeTaskIDPtr. However,
        %% since we only support single rate non-inlined sfcn running
        %% at async rate, any async task always get task time from base rate
        %% in Sfcn target, it's okay to force map async ts to TaskIdx 0 in
        %% parent model.
        %%
        %if LibAsynchronousTriggeredTID(mdlTID)
          sfcnTsMap[%<sfcnTID>] = 0;
          %assert (SIZE(ParamSettings.SampleTimesToSet, 0) == 1)
        %else
          sfcnTsMap[%<sfcnTID>] = %<RTMGet("SampleTimeTaskIDPtr")>[%<mdlTID>];
        %endif
      %else
        sfcnTsMap[%<sfcnTID>] = %<mdlTID>;
      %endif
    %endif
  %endforeach
  %closefile tempBuffer
   
  %openfile retBuf
  %if !WHITE_SPACE(tempBuffer)
     
    /* adjust sample time */
    %<tempBuffer>/
  %endif
  %closefile retBuf
   
  %return retBuf
%endfunction
 
 
%%Function:SLibCallChildSfcnInitializationFcn===============================
%%TopTester:test/toolbox/simulink/blocks/sb2sl/tsb2slmdlref2.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/tmMultiRateAsyncTask_VC1.m
%function SLibCallChildSfcnInitializationFcn(s, childIdx, underScore, ...
  usingStatic, nonInlSfcns)
  %assign sfuncName = ParamSettings.FunctionName
   
  %assign thisBlock = ChildSFunctionList[childIdx]
 
  %openfile retBuf
  %%
  %% Call child's initialization routines
  %%
  /* registration */
  %if (CodeFormat == "S-Function" && !usingStatic) || IsModelReferenceSimTarget()
    %<SLibWriteSFunctionGuards("if")>
 
      int_T i;
      mxArray *plhs[1];
      mxArray *prhs[4];
      double *pr;
      %% Make this variable volatile to workaround a possible bug
      %% in the VS2012 optimizer, see g1042819 and g1056052.
      volatile int_T *intS = (int_T *)&%<s>;
      int_T addrlen = sizeof(SimStruct *);
      int_T m = addrlen/sizeof(int_T) + 1;
       
      prhs[0] = mxCreateDoubleMatrix(0,0,mxREAL);
      prhs[1] = mxCreateDoubleMatrix(m,1,mxREAL);
       
      pr = mxGetPr(prhs[1]);
      for (i = 0; i < m - 1; i++) {
    pr[i] = (double)intS[i];
      }
      pr[i] = (double)SIMSTRUCT_VERSION_LEVEL2;
       
      prhs[2] = mxCreateDoubleMatrix(0,0,mxREAL);
      prhs[3] = mxCreateDoubleMatrix(1,1,mxREAL);
       
      /* Reset port dimensions info functions because the S-function
      * and accelerator mex-files explicitly set their dimensions,
      * i.e., they are not dynamically sized. For this case, the
      * mex-file is responsible for the dimensions info memory
      * and Simulink should not free it. This is achieved by
      * setting the following two methods to NULL.
      */
       
      ssSetRegInputPortDimensionInfoFcn(%<s>, %<SLibGetNullDefinitionFromTfl()>);
      ssSetRegOutputPortDimensionInfoFcn(%<s>, %<SLibGetNullDefinitionFromTfl()>);
       
      /*
      * Setup function pointers and call mdlInitializeSizes via
      * simulink.c
      */
       
      mexCallMATLAB(1, plhs, 4, prhs, "%<sfuncName>");
       
      mxDestroyArray(plhs[0]);
      mxDestroyArray(prhs[0]);
      mxDestroyArray(prhs[1]);
      mxDestroyArray(prhs[2]);
      mxDestroyArray(prhs[3]);
       
    %<SLibWriteSFunctionGuards("else")>
 
    %assign simTargetWillUseSFcnMexFile = ...
      IsModelReferenceSimTarget() && ParamSettings.WillBeDynamicallyLoaded == "yes"
     
    %if simTargetWillUseSFcnMexFile
       
      sfcnLoader_callSFcn("%<sfuncName>", "%<thisBlock.TLCBlockSID>", %<s>);
       
    %else
 
      %<sfuncName>(%<s>);
      sfcnInitializeSizes(%<s>);
    %endif
 
    %<SLibWriteSFunctionGuards("endif")>
     
    %if PortBasedSampleTimes == "no"
      sfcnInitializeSampleTimes(%<s>);
    %endif
  %else
    %assign raccelUseMexFile = ...
    ::isRAccel && ParamSettings.WillBeDynamicallyLoaded == "yes"
     
    %% dynamically loaded level 1 s-functions are not supported in rapid accelerator
    %assert !(raccelUseMexFile && ParamSettings.FunctionLevel == 1)
     
    %if raccelUseMexFile
      {
        raccelLoadSFcnMexFile("%<sfuncName>", "%<thisBlock.TLCBlockSID>", %<s>, %<childIdx>);
        if (ssGetErrorStatus(rtS)) {
          return rtS;
        }
      }
    %else
      %<sfuncName>(%<s>);
    %endif
     
    %% rapid-accelerator calls mexFunction in the simulink.c that is included
    %% in mex'd s-functions; that mexFunction in turn calls the s-function's mdlInitializeSizes
    %% method, so the call isn't needed here in rapid-accelerator
    %if !raccelUseMexFile
      sfcnInitializeSizes(%<s>);
    %endif
       
    %if PortBasedSampleTimes == "no"
          sfcnInitializeSampleTimes(%<s>);
    %endif
     
  %endif
  %closefile retBuf
   
  %return retBuf
%endfunction
 
%%Function:SLibResetDynSizedFieldsForChildSfcn==============================
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/tVariantSource3.m
%%
%function SLibResetDynSizedFieldsForChildSfcn(s, childIdx, underScore, ...
  usingStatic, nonInlSfcns)
  %assign thisBlock = ChildSFunctionList[childIdx]
  %assign numDiscStates = DiscStates[0]
  %assign numContStates = ContStates[0]
    
  %openfile retBuf
  %%
  %% Need to explicitly reset anything that was dynamically sized
  %%
  %assign dsSize = SIZE(ParamSettings.DynamicallySizedVectors,1)
  %if dsSize > 0
 
    /* set compiled values of dynamic vector attributes */
    %if ParamSettings.FunctionLevel == 1
      %foreach idx = dsSize
    %assign dsVar = ParamSettings.DynamicallySizedVectors[idx]
    %switch dsVar
      %case "U"
        %if isRSimWithSolverModule %% assert !IsModelReferenceTarget()
          ssSetNumU(%<s>, %<LibBlockInputSignalWidth(0)>);
        %else
          ssSetNumInputs(%<s>, %<LibBlockInputSignalWidth(0)>);
        %endif
        %break
      %case "Y"
        %if isRSimWithSolverModule %% assert !IsModelReferenceTarget()
          ssSetNumY(%<s>, %<LibBlockOutputSignalWidth(0)>);
        %else
          ssSetNumOutputs(%<s>, %<LibBlockOutputSignalWidth(0)>);
        %endif
        %break
      %case "Xc"
        ssSetNumContStates(%<s>, %<numContStates>);
        %break
      %case "Xd"
        ssSetNumDiscStates(%<s>, %<numDiscStates>);
        %break
      %case "RWork"
        ssSetNumRWork(%<s>, %);
        %break
      %case "IWork"
        ssSetNumIWork(%<s>, %);
        %break
      %case "PWork"
        ssSetNumPWork(%<s>, %);
        %break
      %case "Modes"
        ssSetNumModes(%<s>, %);
        %break
      %case "NonsampledZCs"
        ssSetNumNonsampledZCs(%<s>, %<NumNonsampledZCs>);
        %break
      %default
        %assign errTxt = "No case for dynamically sizing: %<dsVar>"
        %<LibReportFatalError(errTxt)>
    %endswitch
      %endforeach
    %else
      %foreach idx = dsSize
    %assign dsVar = ParamSettings.DynamicallySizedVectors[idx]
    %assign idNum = IDNUM(dsVar)
    %assign num = idNum[1]
     
    %switch idNum[0]
      %case "U"
        %assign u = DataInputPort[num]
        ssSetInputPortWidth(%<s>, %<num>, %<LibGetRecordWidth(u)>);
        %%
        %assign dtIdCurInput = LibGetDataTypeIdAliasedThruToFromId(...
          SLibGetRecordDataTypeId(u))
        %%
        %if LibIsBuiltInDataType(dtIdCurInput)
          %assign dtEnum = LibGetDataTypeEnumFromId(dtIdCurInput)
          ssSetInputPortDataType(%<s>, %<num>, %<dtEnum>);
        %elseif LibIsHalfDataType(dtIdCurInput)
          DTypeId halfID = ssRegisterDataTypeHalfPrecision(
          %<s>,
          0 /* 0 means do NOT obey data type override setting for this subsystem */ );
          ssSetInputPortDataType( %<s>, %<num>, halfID );
        %else
          %%
          %assign curDT = FixPt_GetDataTypeFromIndex(dtIdCurInput)
          %%
          %if curDT.IsFixedPoint
        {
          DTypeId dataTypeIdReg =
          %if FixPt_DataTypeIsFloat(curDT)
            ssRegisterDataTypeFxpScaledDouble(
          %else
            ssRegisterDataTypeFxpFSlopeFixExpBias(
          %endif
          %<s>,
          %<curDT.IsSigned>,
          %<curDT.RequiredBits>,
          %<curDT.FracSlope>,
          %<curDT.FixedExp>,
          %<curDT.Bias>,
          0 /* false means do NOT obey data type override setting for this subsystem */ );
           
          ssSetInputPortDataType(%<s>, %<num>, dataTypeIdReg );
        }
          %else
        %assign dtEnum = LibGetDataTypeEnumFromId(dtIdCurInput)
        %%
                %if dtEnum == "SS_POINTER" || dtEnum == "SS_INTEGER"
                  ssSetInputPortDataType(%<s>, %<num>, %<dtEnum>);
                %else
                   
                  %assign raccelUseMexFile = ...
                    ::isRAccel && ParamSettings.WillBeDynamicallyLoaded == "yes"
                   
                  %if !raccelUseMexFile
                    %assign errTxt = "User-defined data type " ...
                      "%<LibGetDataTypeNameFromId(dtIdCurInput)> is required " ...
                      "for Root Level Input %<num>, but the information needed to define this " ...
                      "data type in the generated S-Function code format is unknown."
                    %<LibBlockReportError(thisBlock, errTxt)>
                  %endif
                %endif
                 
          %endif
        %endif
        %%
        ssSetInputPortComplexSignal(%<s>, %<num>, ...
          %<SLibGetRecordIsComplex(u)>);
        ssSetInputPortFrameData(%<s>, %<num>, ...
          %<LibBlockInputSignalIsFrameData(num)>);
            %if NumDataInputPorts>0
              ssSetInputPortUnit(%<s>, %<num>, ...
                %<LibBlockInputSignalUnitId(num)>);
            %endif
            ssSetInputPortIsContinuousQuantity(%<s>, %<num>, ...
              %<LibBlockInputPortIsContinuousQuantity(num)>);
        %break
      %case "Y"
        %assign yWidth = LibBlockOutputSignalWidth(num)
        %assign op = FcnGetOutputPortRecord(num)
        %assign sigRec = SLibGetSourceRecord(op, 0)
        ssSetOutputPortWidth(%<s>, %<num>, %<yWidth>);
        %if !ISEMPTY(sigRec)
          %%
          %assign dtIdCurOutput = LibGetDataTypeIdAliasedThruToFromId(...
        SLibGetRecordDataTypeId(sigRec))
          %%
          %if LibIsBuiltInDataType(dtIdCurOutput)
        %assign dtEnum = LibGetDataTypeEnumFromId(dtIdCurOutput)
        ssSetOutputPortDataType(%<s>, %<num>, %<dtEnum>);
          %elseif LibIsHalfDataType(dtIdCurOutput)
        DTypeId halfID = ssRegisterDataTypeHalfPrecision(
        %<s>,
        0 /* 0 means do NOT obey data type override setting for this subsystem */ );
        ssSetOutputPortDataType(%<s>, %<num>, halfID);
          %else
        %%
        %assign curDT = FixPt_GetDataTypeFromIndex(dtIdCurOutput)
        %%
        %if curDT.IsFixedPoint
          {
            DTypeId dataTypeIdReg =
            %if FixPt_DataTypeIsFloat(curDT)
              ssRegisterDataTypeFxpScaledDouble(
            %else
              ssRegisterDataTypeFxpFSlopeFixExpBias(
            %endif
            %<s>,
            %<curDT.IsSigned>,
            %<curDT.RequiredBits>,
            %<curDT.FracSlope>,
            %<curDT.FixedExp>,
            %<curDT.Bias>,
            0 /* false means do NOT obey data type override setting for this subsystem */ );
             
            ssSetOutputPortDataType(%<s>, %<num>, dataTypeIdReg);
          }
        %else
                  %assign dtEnum = LibGetDataTypeEnumFromId(dtIdCurOutput)
                  %%
                  %if dtEnum == "SS_POINTER" || dtEnum == "SS_INTEGER"
                    ssSetOutputPortDataType(%<s>, %<num>,%<dtEnum>);
                  %else
                     
                    %assign raccelUseMexFile = ...
                      ::isRAccel && ParamSettings.WillBeDynamicallyLoaded == "yes"
                     
                    %if !raccelUseMexFile
                      %assign errTxt = "User-defined data type " ...
                        "%<LibGetDataTypeNameFromId(dtIdCurOutput)> is required " ...
                        "for Root Level Output %<num>, but the information needed to define this " ...
                        "data type in the generated S-Function code format is unknown."
                      %<LibBlockReportError(thisBlock, errTxt)>
                    %endif
                  %endif
                   
        %endif
          %endif
          %%
          ssSetOutputPortComplexSignal(%<s>, %<num>, ...
        %<SLibGetRecordIsComplex(sigRec)>);
          ssSetOutputPortFrameData(%<s>, %<num>, ...
        %<LibBlockOutputSignalIsFrameData(num)>);
              %if NumDataOutputPorts>0
                ssSetOutputPortUnit(%<s>, %<num>, ...
                  %<LibBlockOutputSignalUnitId(num)>);
              %endif
              ssSetOutputPortIsContinuousQuantity(%<s>, %<num>, ...
              %<LibBlockOutputPortIsContinuousQuantity(num)>);
        %endif
        %break
      %case "Xc"
        ssSetNumContStates(%<s>, %<numContStates>);
        %break
      %case "Xd"
        ssSetNumDiscStates(%<s>, %<numDiscStates>);
        %break
      %case "RWork"
        ssSetNumRWork(%<s>, %);
        %break
      %case "IWork"
        ssSetNumIWork(%<s>, %);
        %break
      %case "PWork"
        ssSetNumPWork(%<s>, %);
        %break
      %case "DWork"
        _ssSetNumDWork(%<s>, %<numDWorks>);
        %break
      %case "D"
        %assign dwork = thisBlock.DWork[num]
        ssSetDWorkWidth(%<s>, %<num>, ...
          %<LibBlockDWorkWidth(dwork)>);
        %%
        %assign dtIdCurDWork = LibGetDataTypeIdAliasedThruToFromId(...
          LibBlockDWorkDataTypeId(dwork))
        %%
        %if LibIsBuiltInDataType(dtIdCurDWork)
          %assign dtEnum = LibGetDataTypeEnumFromId(dtIdCurDWork)
          ssSetDWorkDataType(%<s>, %<num>, %<dtEnum>);
        %elseif LibIsHalfDataType(dtIdCurDWork)
          DTypeId halfID = ssRegisterDataTypeHalfPrecision(
          %<s>,
          0 /* 0 means do NOT obey data type override setting for this subsystem */ );
          ssSetDWorkDataType( %<s>, %<num>, halfID );
        %else
          %%
          %assign curDT = FixPt_GetDataTypeFromIndex(dtIdCurDWork)
          %%
          %if curDT.IsFixedPoint
        {
          DTypeId dataTypeIdReg =
          %if FixPt_DataTypeIsFloat(curDT)
            ssRegisterDataTypeFxpScaledDouble(
          %else
            ssRegisterDataTypeFxpFSlopeFixExpBias(
          %endif
          %<s>,
          %<curDT.IsSigned>,
          %<curDT.RequiredBits>,
          %<curDT.FracSlope>,
          %<curDT.FixedExp>,
          %<curDT.Bias>,
          0 /* false means do NOT obey data type override setting for this subsystem */ );
           
          ssSetDWorkDataType(%<s>, %<num>, dataTypeIdReg );
        }
          %else
        %assign dtEnum = LibGetDataTypeEnumFromId(dtIdCurDWork)
        %%
                %if dtEnum == "SS_POINTER" || dtEnum == "SS_INTEGER"
                  ssSetDWorkDataType(%<s>, %<num>,%<dtEnum>);
                %else
                   
                  %assign raccelUseMexFile = ...
                    ::isRAccel && ParamSettings.WillBeDynamicallyLoaded == "yes"
                   
                  %if !raccelUseMexFile
                    %assign errTxt = "User-defined data type " ...
                      "%<LibGetDataTypeNameFromId(dtIdCurDWork)> is required " ...
                      "for DWork %<num>, but the information needed to define this " ...
                      "data type in the generated S-Function code format is unknown. " ...
                      "The generated code that normally " ...
                      "specifies the data type of this DWork is being omitted. " ...
                      "If additional custom code does not register this user-define data type " ...
                      "and set the data type of this DWork, then the generated code " ...
                      "will be incomplete."
                    %<LibBlockReportWarning(thisBlock, errTxt)>
                  %endif
                %endif
                 
          %endif
        %endif
        %%
        ssSetDWorkComplexSignal(%<s>, %<num>, ...
          %<LibBlockDWorkIsComplex(dwork)>);
        %break
      %case "Modes"
        ssSetNumModes(%<s>, %);
        %break
      %case "NonsampledZCs"
        ssSetNumNonsampledZCs(%<s>, %<NumNonsampledZCs>);
        %break
      %default
        %assign errTxt = "No case for dynamically sizing: %<dsVar>"
        %<LibReportFatalError(errTxt)>
    %endswitch
      %endforeach
    %endif %% FunctionLevel == 1
  %endif %% dsSize > 1
  %closefile retBuf
   
  %return retBuf
%endfunction
   
%%Function:SLibUpdatePortConnectivityForChildSfcn============================
%%
%function SLibUpdatePortConnectivityForChildSfcn(s, childIdx, underScore, ...
  usingStatic, nonInlSfcns)
  %openfile retBuf
  %%
  %% Update connectivity flags for each port
  %%
  %if ParamSettings.FunctionLevel == 2
    /* Update connectivity flags for each port */
    %foreach ipIdx = NumDataInputPorts
      _ssSetInputPortConnected(%<s>, %<ipIdx>, ...
    %<LibBlockInputSignalConnected(ipIdx)>);
    %endforeach
    %foreach ipIdx = NumDataOutputPorts
      _ssSetOutputPortConnected(%<s>, %<ipIdx>, ...
    %<LibBlockOutputSignalConnected(ipIdx)>);
    %endforeach
    %foreach ipIdx = NumDataOutputPorts
      _ssSetOutputPortBeingMerged(%<s>, %<ipIdx>, ...
    %<LibBlockOutputSignalBeingMerged(ipIdx)>);
    %endforeach
    /* Update the BufferDstPort flags for each input port */
    %foreach ipIdx = NumDataInputPorts
      %assign bufDst = LibBlockInputSignalBufferDstPort(ipIdx)
      %<underScore>ssSetInputPortBufferDstPort(%<s>, %<ipIdx>, %<bufDst>);
    %endforeach
    %if PortBasedSampleTimes == "yes"
      /* Update port-based sample time attributes */
      %foreach ipIdx = NumDataInputPorts
    _ssSetInputPortSampleTimeIndex(%<s>, %<ipIdx>, ...
      %<LibBlockInputSignalLocalSampleTimeIndex(ipIdx)>);
    ssSetInputPortSampleTime(%<s>, %<ipIdx>, ...
      %<LibBlockInputSignalSampleTime(ipIdx)>);
    ssSetInputPortOffsetTime(%<s>, %<ipIdx>, ...
      %<LibBlockInputSignalOffsetTime(ipIdx)>);
      %endforeach
      %foreach opIdx = NumDataOutputPorts
    _ssSetOutputPortSampleTimeIndex(%<s>, %<opIdx>, ...
      %<LibBlockOutputSignalLocalSampleTimeIndex(opIdx)>);
    ssSetOutputPortSampleTime(%<s>, %<opIdx>, ...
      %<LibBlockOutputSignalSampleTime(opIdx)>);
    ssSetOutputPortOffsetTime(%<s>, %<opIdx>, ...
      %<LibBlockOutputSignalOffsetTime(opIdx)>);
      %endforeach
      sfcnInitializeSampleTimes(%<s>);
    %endif
  %endif %% FunctionLevel == 2
  %closefile retBuf
   
  %return retBuf
%endfunction
 
%%Function:SLibInitRegDataTypeFcnToErrFcn===================================
%%Abstract:
%%SincemacrosusingregDataTypefielddonotworkwithmdlrefsimtarget
%%andsfcntarget,weinitializethefunctionpointeraccessingthisfield
%%toafunction,i.e.,FcnSetErrorStatus,thatreportsanerrormessage.
%%TopTester:test/toolbox/simulink/blocks/sb2sl/tsb2slmdlref2.m
%%
%function SLibInitRegDataTypeFcnToErrFcn(s, childIdx, underScore, ...
  usingStatic, nonInlSfcns)
  %openfile retBuf
  %if (CodeFormat == "S-Function" && UsingMalloc && ParamSettings.FunctionLevel == 2) || ...
    IsModelReferenceSimTarget()
    %% Always setup function pointer for _mid.h since level 2
    %% child s-f dll will use it.
    (%<s>)->regDataType.arg1 = ((void *)(%<s>));
    (%<s>)->regDataType.registerFcn = ((OldRegisterDataType)FcnSetErrorStatus);
    (%<s>)->regDataType.getSizeFcn = ((GetDataTypeSize)FcnSetErrorStatus);
    (%<s>)->regDataType.getZeroFcn = ((GetDataTypeZero)FcnSetErrorStatus);
    (%<s>)->regDataType.getNameFcn = ((GetDataTypeName)FcnSetErrorStatus);
    (%<s>)->regDataType.getIdFcn = ((GetDataTypeId)FcnSetErrorStatus);
  %endif
  %closefile retBuf
  %return retBuf
%endfunction
 
%%TopTester:test/toolbox/simulink/blocks/sb2sl/-tsb2slmdlref.m
%function SLibCacheBranchedSysCalledByNonInlinedSfcn() void
  %foreach childIdx = NumChildSFunctions
    %assign thisBlock = ChildSFunctionList[childIdx]
    %if SLibSfcnHasBranchFcnCall(thisBlock)
      %% Go over all output function-call signals
      %foreach callIdx = thisBlock.NumSFcnSysOutputCalls
 
        %assign recIdx = thisBlock.SFcnSystemOutputCallMappingInfo[callIdx].StartingIdx
        %assign nCalledFC = thisBlock.SFcnSystemOutputCallMappingInfo[callIdx].NumOfCalledFC
         
        %if nCalledFC > 1 %% This element invokes a branched function-call
          %% mark the first subsystem called the element
          %assign fcOutPortEl = thisBlock.SFcnSystemOutputCall[recIdx].OutputElement
          %assign firstBlkToCall = thisBlock.SFcnSystemOutputCall[recIdx].BlockToCall
          %assign callPort = thisBlock.SFcnSystemOutputCall[recIdx].FcnPortIdx
          %assert STRING(firstBlkToCall) != "unconnected"
           
          %assign sysIdx = firstBlkToCall[0]
          %assign blkIdx = firstBlkToCall[1]
          %assign fcnCallBlock = ::CompiledModel.System[sysIdx].Block[blkIdx]
          %if fcnCallBlock.Type == "SubSystem"
            %with fcnCallBlock
              %assert (Type == "SubSystem")
              %assign sysIdx = LibBlockParamSetting("Subsystem", "SystemIdx")
            %endwith
            %assign fcnCallSys = System[sysIdx]
            %if !LibIsSystemField(fcnCallSys, "CallerBlkIdx")
              %<LibAddToSystem(fcnCallSys, "CallerBlkIdx", thisBlock.BlockIdx)>
              %<LibAddToSystem(fcnCallSys, "CallerBlkPortEl", fcOutPortEl)>
            %else
              %% System has multiple callers, Set CallerBlkIdx to invalid value
              %<LibSetSystemField(fcnCallSys, "CallerBlkIdx",[-1 -1 -1])>
              %<LibSetSystemField(fcnCallSys, "CallerBlkPortEl",-1)>
            %endif
          %elseif fcnCallBlock.Type == "ModelReference"
            %if !ISFIELD(fcnCallBlock, "CallerBlkInfo")
              %assign numInputPorts = fcnCallBlock.NumDataInputPorts
              %if ISFIELD(fcnCallBlock.ParamSettings, "ModelEventPortNames")
                %assign numInputPorts = numInputPorts + ...
                  SIZE(fcnCallBlock.ParamSettings.ModelEventPortNames, 1)
              %endif
              %foreach inputPort = numInputPorts
                %addtorecord fcnCallBlock CallerBlkInfo { ...
                  CallerBlkIdx []; ...
                  CallerBlkPortEl -1}
              %endforeach
            %endif
             
            %assign fcnCallBlock.CallerBlkInfo[callPort].CallerBlkIdx = thisBlock.BlockIdx
            %assign fcnCallBlock.CallerBlkInfo[callPort].CallerBlkPortEl = fcOutPortEl
          %endif
        %endif %% if nCalledFC > 1
      %endforeach %% callIdx = thisBlock.NumSFcnSysOutputCalls
       
    %endif %% if SLibSfcnHasBranchFcnCall(thisBlock)
  %endforeach
%endfunction
 
 
%%Function:LibCacheChildSFunctionRegistration================================
%%Abstract:
%%CachethechildS-Functionregistrationcode.Supportsthesecode
%%formats.
%%
%%oRealTime
%%oRealTimeMalloc
%%oS-Function
%%TopTester:test/toolbox/simulink/blocks/lib_MathOperations/Gain/rtw/tdtgain4.m
%%TopTester:test/toolbox/simulink/blocks/sb2sl/tsb2slmdlref2.m
%%TopTester:test/toolbox/simulink/blocks/sb2sl/tsb2slmdlref.m
%%
%function LibCacheChildSFunctionRegistration(s, modelName) void
  %% No S-functions to register in this model, or any child models
  %if NumChildSFunctions == 0 && ::CompiledModel.ModelBlocksHaveNonInlinedSfcns == 0
    %assign ::CompiledModel.SFunctionRegistration = ""
    %return ""
  %endif
   
  %% Check code format
  %assign usingStatic = !UsingMalloc && (!SLibIsERTCodeFormat())
  %if CodeFormat == "S-Function" || IsModelReferenceSimTarget()
    %assign underScore = "_"
  %else
    %assign underScore = ""
  %endif
 
  %%
  %% Declare all child SimStructs
  %%
  %assign baseSysIdx = GetBaseSystemIdx()
  %with System[baseSysIdx]
  %openfile sfunctionRegBuffer
  %%
  %% Setup RTWSfcnInfo for cases where rtModel is being generated
  %%
  %if GenRTModel
    %if !IsModelReferenceTarget()
      %<FcnSetupSFcnRTWInfo()>
    %elseif !IsModelReferenceForASimstructBasedTarget() && ...
      NumChildSFunctions > 0 && !GenerateClassInterface
      %<RTMSet("RTWSfcnInfo", "rt_sfcnInfo")>;
    %endif
  %endif
 
  %if NumChildSFunctions > 0
    %<RTMSet("NumSFunctions", NumChildSFunctions)>;
 
    /* register each child */
    {
      %assign nonInlSfcns = ""
      %if usingStatic
        static SimStruct childSFunctions[%<NumChildSFunctions>];
        static SimStruct *childSFunctionPtrs[%<NumChildSFunctions>];
 
        (void) %<LibGenMemFcnCall("memset", "(void *)&childSFunctions[0]", ...
          "0", "sizeof(childSFunctions)")>;
        %if CodeFormat == "S-Function"
          %<RTMuSet("SFunctions", "&childSFunctionPtrs[0]")>;
        %else
          %<RTMSet("SFunctions", "&childSFunctionPtrs[0]")>;
        %endif
      %elseif SLibIsERTCodeFormat()
        %assign nonInlSfcns = "%<RTMGet("NonInlinedSFcns")>"
        (void) %<LibGenMemFcnCall("memset", ...
          "(void *)&%<nonInlSfcns>.childSFunctions[0]", "0", ...
          "%<NumChildSFunctions>*sizeof(SimStruct)")>;
        %<RTMSet("SFunctions", "&%<nonInlSfcns>.childSFunctionPtrs[0]")>;
      %else
        SimStruct *childSFunctions;
        SimStruct **childSFunctionPtrs;
 
        childSFunctions = (SimStruct *) ...
          malloc(%<NumChildSFunctions> * sizeof(SimStruct));
        %<RTMChkMemAndReturnIfErr("childSFunctions")>;
        (void) %<LibGenMemFcnCall("memset", "(void *)childSFunctions", "0", ...
          "%<NumChildSFunctions>*sizeof(SimStruct)")>;
 
        childSFunctionPtrs = (SimStruct **) ...
          malloc(%<NumChildSFunctions> * sizeof(SimStruct *));
        %<RTMChkMemAndReturnIfErr("childSFunctionPtrs")>;
 
        %if CodeFormat == "S-Function"
          %<RTMuSet("SFunctions", "childSFunctionPtrs")>;
        %else
          %<RTMSet("SFunctions", "childSFunctionPtrs")>;
        %endif
      %endif
      %%
      %if NumChildSFunctions >= RollThreshold
        %% use a loop
        {
          int_T i;
           
          for (i = 0; i < %<NumChildSFunctions>; i++) {
            %if CodeFormat == "S-Function"
              %<RTMuSetIdxed("SFunction", "i", "&childSFunctions[i]")>;
            %elseif SLibIsERTCodeFormat()
              %<RTMSetIdxed("SFunction", "i", "&%<nonInlSfcns>.childSFunctions[i]")>;
            %else
              %<RTMSetIdxed("SFunction", "i", "&childSFunctions[i]")>;
            %endif
          }
        }
      %elseif NumChildSFunctions >= 1
        %% do no use a loop
        %foreach childIdx = NumChildSFunctions
          %assign childSfunLabel = "childSFunctions[" + "%<childIdx>" + "]"
          %assign childSfunAddrLabel = "&%<childSfunLabel>"
          %if CodeFormat == "S-Function"
            %<RTMuSetIdxed("SFunction", childIdx, childSfunAddrLabel)>;
          %elseif SLibIsERTCodeFormat()
            %assign childSfunLabel = "&%<nonInlSfcns>." + "%<childSfunLabel>"
            %<RTMSetIdxed("SFunction", childIdx, childSfunLabel)>;
          %else
            %<RTMSetIdxed("SFunction", childIdx, childSfunAddrLabel)>;
          %endif
        %endforeach
        %%
      %endif
      %%
      %% Initialize each child SimStruct
      %%
      %foreach childIdx = NumChildSFunctions
        %assign thisBlock = ChildSFunctionList[childIdx]
        %with thisBlock
          %assign sfuncName = ParamSettings.FunctionName
          %openfile tmpChildRegBuffer
          %%
          %% Timing Info
          %%
          %<SLibSetupTimingInfoForChildSfcn(s, childIdx, underScore, ...
            usingStatic, nonInlSfcns)>
          %%
          %% mdlInfo
          %%
          %<SLibSetupMdlInfoForChildSfcn(s, childIdx, underScore, ...
            usingStatic, nonInlSfcns) >
          %%
          %% allocate memory for ModelMethods2, ModelMethods3, ModelMethods4
          %%
          %<SLibAllocateMethods2MemForChildSfcn(s, childIdx, underScore, ...
            usingStatic, nonInlSfcns) >
          %%
          %% allocate memory for stateInfo2
          %%
          %<SLibAllocateStatesInfo2MemForChildSfcn(s, childIdx, underScore, ...
            usingStatic, nonInlSfcns) >
          %% Inputs
          %%
          %<SLibSetupInputsForChildSfcn(s, childIdx, underScore, ...
            usingStatic, nonInlSfcns) >
          %%
          %% Outputs
          %%
          %<SLibSetupOutputsForChildSfcn(s, childIdx, underScore, ...
            usingStatic, nonInlSfcns) >
          %%
          %% States
          %%
          %<SLibSetupStatesForChildSfcn(s, childIdx, underScore, ...
            usingStatic, nonInlSfcns) >
          %%
          %% Path, model name, parent SimStruct, and root SimStruct
          %%
          %<SLibSetupPathInfoForChildSfcn(s, childIdx, underScore, ...
            usingStatic, nonInlSfcns) >
          %%
          %% S-Function parameters
          %%
          %<SLibSetupSfcnParamsForChildSfcn(s, childIdx, underScore, ...
            usingStatic, nonInlSfcns) >
          %%
          %% RWork, IWork, PWork, DWork and Mode
          %%
          %<SLibSetupWorksForChildSfcn(s, childIdx, underScore, ...
            usingStatic, nonInlSfcns) >
          %%
          %% Function calls
          %%
          %<SLibSetupCallSysForChildSfcn(s, childIdx, underScore, ...
            usingStatic, nonInlSfcns) >
          %%
          %% Registered Data Type
          %%
          %<SLibInitRegDataTypeFcnToErrFcn(s, childIdx, underScore, ...
            usingStatic, nonInlSfcns)>
          %%
          %% Call child's initialization routines
          %%
          %<SLibCallChildSfcnInitializationFcn(s, childIdx, underScore, ...
            usingStatic, nonInlSfcns) >
          %%
          %% May need to adjust the sample times
          %%
          %<SLibAdjustStInfoForChildSfcn(s, childIdx, underScore, ...
            usingStatic, nonInlSfcns) >
          %%
          %% Need to explicitly reset anything that was dynamically sized
          %%
          %<SLibResetDynSizedFieldsForChildSfcn(s, childIdx, underScore, ...
            usingStatic, nonInlSfcns) >
          %%
          %% Update connectivity flags for each port
          %%
          %<SLibUpdatePortConnectivityForChildSfcn(s, childIdx, underScore, ...
            usingStatic, nonInlSfcns) >
          %%
          %% Generated S-Function's require data instance
          %%
          %assign raccelUseMexFile = ...
            ::isRAccel && ParamSettings.WillBeDynamicallyLoaded == "yes"
           
          %if LibSFunctionLevel() == "RTWLevel2" && !raccelUseMexFile
            %% ModelRef doesn't support Generated
            %% non-inline s-function. We should have already
            %% errored out during compilation.
            %assert !IsModelReferenceTarget()
            %if !UsingMalloc
              %assign funcName = STRING(ParamSettings.FunctionName)
              %assign end = SIZE(funcName,1) - 3
              %assign origName = ""
              %foreach idx = end
                %assign origName = origName + funcName[idx]
              %endforeach
              %assign sidInc = "%<origName>_sfcn_rtw/%<origName>_sid.h"
              /* Instance data for generated S-Function: %<origName> */
              %if CodeFormat == "S-Function"
                {
                  SimStruct *rts = childS;
                  #include "%<sidInc>"
                }
              %else
                #include "%<sidInc>"
              %endif
            %endif %% !UsingMalloc
          %endif %% RTWLevel2
          %closefile tmpChildRegBuffer
 
          %%
          %% Ensure the childsfcn does not have the same name
          %%
          %if CodeFormat == "S-Function" && (sfuncName == ::CompiledModel.Name)
            %assign errTxt = "/n/nDetected duplicate name '%<sfuncName>' for this generated " ...
              "S-function and the noninlined S-function name from block '%<thisBlock.Name>'." ...
              " Please choose another name for this generated S-function. "
            %<LibReportError(errTxt)>
          %endif
 
          %% Adding one record each to CompiledModel everytime we cache an
          %% sfunction extern prototype
          %assign varName = "SFcn_%<ParamSettings.FunctionName>_PrototypeCached"
 
          %if !EXISTS("::CompiledModel.%<varName>")
            %addtorecord ::CompiledModel %<varName> 1
            %openfile fcnPrototype
            %assign flag = LibExternInFcnDecls()
            %if GenCPP
              %assign flag = "extern /"C/""
            %endif
            %<flag> void %<ParamSettings.FunctionName>(SimStruct *%<s>);
            %closefile fcnPrototype
            %<LibCacheFunctionPrototype(fcnPrototype)>/
          %endif
 
          %% TopTester: test/toolbox/simulink/variants/inlineVariants/variantSource/codeGen/tGlobalGuardingGecks1.m -testspec:verifyG1396962
          %assign thisSystem = ::CompiledModel.System[thisBlock.BlockIdx[0]]
          %<SLibIfSystemVariantCondition(thisSystem)>
          %<SLibIfVariantCondition(thisBlock)>
          /* %<TypeLevel> Block: %<modelName>%<"/">%<Name> (%<sfuncName>) */
          {
            SimStruct *%<s> = %<RTMGetIdxed("SFunction", childIdx)>;
            %<tmpChildRegBuffer>/
          }
      %<SLibEndIfVariantCondition(thisBlock)>
          %<SLibEndIfSystemVariantCondition(thisSystem)>
        %endwith %% thisBlock
      %endforeach %% NumChildSFunctions
      %%
      %% cache registration code
      %%
    }
  %endif
  %closefile sfunctionRegBuffer
  %endwith %% System[NumSystems-1]
  %assign ::CompiledModel.SFunctionRegistration = sfunctionRegBuffer
 
%endfunction %% LibCacheChildSFunctionRegistration
 
 
%%Function:LibSFunctionRegistrationIsEmpty===================================
%%Abstract:
%function LibSFunctionRegistrationIsEmpty() void
  %<LibTrapCacheAssert(SFunctionRegistration)>
  %return WHITE_SPACE(SFunctionRegistration)
%endfunction
 
 
%%Function:LibDumpSFunctionRegistration======================================
%%Abstract:
%function LibDumpSFunctionRegistration() Output
  %<LibTrapCacheAssert(SFunctionRegistration)>/
  %if !WHITE_SPACE(SFunctionRegistration)
 
    /* child S-Function registration */
    %<SFunctionRegistration>/
  %endif
%endfunction
 
 
%%Function:GenStandaloneRegistrationFunction=================================
%%Abstract:
%%Generatethefollowinginformation:
%%-Standalonesubsystemmemoryinitializationfunction,i.e.,registration
%%-Ifthefunctionsaregeneratedindifferentfiles,declarethemin
%%subsystemheaderfile.
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/codeGen/-tg1375551.m
%%
%function GenStandaloneRegistrationFunction() void
  %assign rootFile = GetBaseFileName()
  %assign callBuf = ""
  %foreach sysIdx = NumSystems
    %assign system = System[sysIdx]
    %if LibIsSystemField(system, "CachedInitializeDataBody") && ...
      !WHITE_SPACE(LibGetSystemField(system, "CachedInitializeDataBody"))
      %openfile regBuf
      %assign fcnName = system.StandaloneInitializeFcn
      %if LibSystemIsInlined(system)
        %<SLibGetFcnComment(system,"Initialize")>/
      %else
        %assign fcnAbstract = SLibGetFcnCommentContents(system,"Initialize")
        %assign fcnBlockDescription = SLibGetBlockDescriptionForSS(system,"Initialize")
        %assign fcnReturns = "void"
        %assign fcnParams = "void"
        %createrecord fcnRec {Name fcnName; Returns fcnReturns; Params fcnParams; Abstract fcnAbstract; ...
          Category "model"; GeneratedBy "commonreglib.tlc"; Type "Initialize"; ...
          GeneratedFor FcnGeneratedFor(system); BlockDescription fcnBlockDescription}
        %<SLibDumpFunctionBanner(fcnRec)>
        %undef fcnRec
      %endif
      %<SLibIfSystemVariantCondition(system)>
      %<SLibGetFcnMemSecPragmaForSystem(fcnName, "MemSecFuncInitTerm", "Pre", system)>/
      %<fcnReturns> %<fcnName>(%<fcnParams>) {
        %<LibGetSystemField(system, "CachedInitializeDataBody")>
      }
      %<SLibGetFcnMemSecPragmaForSystem(fcnName, "MemSecFuncInitTerm", "Post", system)>/
      %<SLibEndIfSystemVariantCondition(system)>
       
      %closefile regBuf
      %% Check if the file exists
      %<SLibCacheSystemCodeToFile("sys_fcn_defn", system, regBuf)>
       
      %assign fileBaseName = SLibGetFileNameForSystemCode("mdl_src", system)
        %openfile extRegBuf
        %<SLibGetFcnMemSecPragmaForSystemOnDecl(fcnName, "MemSecFuncInitTerm", "Pre", system)>/
        %<LibExternInFcnDecls()> void %<fcnName>(void);
        %<SLibGetFcnMemSecPragmaForSystemOnDecl(fcnName, "MemSecFuncInitTerm", "Post", system)>/
        %closefile extRegBuf
      %if fileBaseName != rootFile
        %<SLibCacheSystemCodeToFile("sys_standalone_reg_fcn_decl", system, extRegBuf)>
      %else
        %<SLibCacheCodeToFile("mdl_priv_fcn_decl",extRegBuf)>
      %endif
 
      %assign callBuf = callBuf + SLibIfSystemVariantCondition(system) + "/n"
      %assign callBuf = callBuf + "%<fcnName>();/n"
      %assign callBuf = callBuf + SLibEndIfSystemVariantCondition(system) + "/n"
       
    %endif
  %endforeach
  %if !WHITE_SPACE(callBuf)
    %assign callBuf = "/* Initialize subsystem data *//n" + callBuf
  %endif
  %% Testing
  %return callBuf
%endfunction
 
%%Function:SigSrcLivesInStandaloneSS=========================================
%%Abstract:
%%GivenaSigSrcofarecord(likeBlockOutputs,DWork,...,)doesitlive
%%inastandalonesubsystem?
%%
%%sigSrc[0]=systemIdx
%%sigSrc[1]=instanceIdx
%%
%%NOTE:TheinstanceindexofaSigSrcforarecordmayhave-1ifthesystem
%%isroot.Sinceweusethistoindexintoanarray,changeitto0since
%%weknowtheroothasonlyoneinstance.
%%
%function SigSrcLivesInStandaloneSS(sigSrc) void
 
  %% If the instance index is -1, we know it is root and
  %% not a standalone system.
  %assign retVal = TLC_FALSE
 
  %if ((sigSrc[1] != -1) && System[sigSrc[0]].LivesInStandaloneSS[sigSrc[1]])
    %assign retVal = TLC_TRUE
  %endif
   
  %return retVal
%endfunction
 
 
%%Function:StandaloneParentSysIdxOfSigSrc====================================
%%Abstract:
%%GivenaSigSrcofarecord(likeBlockOutputs,DWork,...,)returnthe
%%standaloneparentsystemIdx.
%%
%%sigSrc[0]=systemIdx
%%sigSrc[1]=instanceIdx
%%
%%NOTE:TheinstanceindexofaSigSrcforarecordmayhave-1ifthesystem
%%isroot.Sinceweusethistoindexintoanarray,changeitto0since
%%weknowtheroothasonlyoneinstance.
%%
%function StandaloneParentSysIdxOfSigSrc(sigSrc) void
 
  %% If the instance index is -1, we know it is root and
  %% not a standalone system.
  %assign retVal = -1
  %if ((sigSrc[1] != -1) && System[sigSrc[0]].LivesInStandaloneSS[sigSrc[1]])
    %assign retVal = System[sigSrc[0]].StandaloneParentSysIdx[sigSrc[1]]
  %endif
   
  %return retVal
%endfunction
 
%function StandaloneParentSysIdxOfDataRec(dataRec) void
  %assert !ISEMPTY(dataRec.SigSrc)
  %return StandaloneParentSysIdxOfSigSrc(SLibGetSystemAndCallSideIndex(dataRec))
%endfunction
 
%%Function:SLibInitBlockIOHelperOld============================================
%%Abstract:
%%ThisisahelperfunctionforSLibInitBlockIOthatcollectsfieldsforan
%%optimizedinitializationloopthatmaynotbeMISRA-Ccompliant
%function SLibInitBlockIOHelperOld(ptrBlockIOLabel, startIdx, standaloneSSIdx) Output
  %assign withSysIdx = standaloneSSIdx ? GetBaseSystemIdx() : standaloneSSIdx
  %assign ::CurrentModuleIdx = System[withSysIdx].CGIRModuleIdx
  %assign blkioIsEmpty = ::CompiledModel.DWorkAndBlockIOCombined ? ...
    SLibModelDWorkStructIsEmpty() : SLibModelBlockIOStructIsEmpty()
  %if !blkioIsEmpty
    %%
    %assign memsetToZeroNeeded = 0
    %%
    %openfile csgInitBuffer %% for invariant, or signal object InitialValue
    %openfile straightInitBuffer
    %openfile useLoopVarInitBuffer
    %%
    %assign baseSystemIdx = GetBaseSystemIdx()
    %%
    %assign numElemInMemoryChunk = 0
    %%
    %assign prevSysIdx = -1
    %assign prevInstIdx = -1
    %assign prevDataTypeId = -1
    %assign prevMemsetToZeroSuffice = -1
    %%
    %assign numOutputsPlusOne = BlockOutputs.NumGlobalBlockOutputs + 1
    %assign changeInMemoryChunk = 0
    %%
    %assign localVoidPointerName = "pVoidBlockIORegion"
    %%
    %foreach loopIdx = (numOutputsPlusOne - startIdx)
      %assign boIdx = loopIdx + startIdx
 
      %if boIdx != BlockOutputs.NumGlobalBlockOutputs && ...
        ISEMPTY(BlockOutputs.GlobalBlockOutput[boIdx].SigSrc)
        %continue
      %endif
 
      %assign fInfo = GetFinalPassAndNextTransitionIndex(boIdx, standaloneSSIdx)
      %assign finalPass = fInfo[0]
      %assign skipRecord = fInfo[1]
      %assign nextStdIdx = fInfo[2]
      %assign nextStartIdx = fInfo[3]
       
      %if skipRecord
        %continue
      %endif
 
      %if !finalPass
        %%
        %assign bo = BlockOutputs.GlobalBlockOutput[boIdx]
        %assign curSysIdx = System[bo.SigSrc[0]].HStructDeclSystemIdx
        %assign curInstIdx = bo.SigSrc[1]
        %assign curDataTypeId = LibGetDataTypeIdAliasedThruToFromId(LibGetRecordDataTypeId(bo))
        %%
        %if !ISEMPTY(bo.InitialValue)
          %if !FcnSkipDataInitialValueInReg(bo)
            %%
            %% If a non-empty initial value is provided for this block output
            %% then initialize it to that value. Initial values are provided
            %% for:
            %%
            %% - block output signals that have constant sample time but (for
            %% various reasons) could not be declared invariant and placed
            %% in the ConstBlockIO structure
            %%
            %% - non-imported-storage-class signals that have signal object
            %% InitialValue applied on them
            %%
            %% For constant sample time signals, we always generate code for
            %% InitialValue regardless of remove zero initialization option.
            %% For non-constant sample time signals, we still check the option
            %%
            %if (bo.Invariant != "yes")
              %if SLibRemoveZeroInitForData(bo, bo.InitialValue)
                %continue
              %endif
            %endif
            %%
            %assign id = SLibGetBlockOutputIdentifierFromRecord(bo,baseSystemIdx)
            %selectfile csgInitBuffer
            %<FcnInitDataInitialValue(bo, id)>
          %endif
          %continue
        %endif
        %%
        %% InitialValue is empty. Use default initial value then.
        %%
        %if SLibRemoveZeroInitForDataDefault(bo)
          %continue
        %endif
        %%
        %assign nterms = LibGetRecordWidth(bo)
        %if LibGetRecordIsComplex(bo)
          %assign nterms = 2*nterms
        %endif
        %%
        %%if IndividualBlockIOInit || ...
        %if ...
         (curSysIdx != prevSysIdx ) || ...
          (curInstIdx != prevInstIdx ) || ...
          (curDataTypeId != prevDataTypeId )
          %%
          %assign changeInMemoryChunk = 1
        %else
          %assign changeInMemoryChunk = 0
        %endif
        %%
        %if changeInMemoryChunk
          %%
          %assign curMemsetToZeroSuffice = FcnMemsetToZeroInitSuffice(curDataTypeId)
          %%
          %if curMemsetToZeroSuffice
            %%
            %assign memsetToZeroNeeded = 1
          %endif
        %endif
      %endif %% if !finalPass
      %%
      %if changeInMemoryChunk || finalPass
        %%
        %% output code to initialize prior chunk of memory
        %%
        %if ( numElemInMemoryChunk > 0 ) && ...
             !prevMemsetToZeroSuffice
          %%
          %assign prevDataTypeDefaultInitValue = ...
        SLibGetDefaultInitialValueFromId(prevDataTypeId)
          %assign prevDataTypeName = ...
        LibGetDataTypeNameFromId(prevDataTypeId)
          %%
          %if FcnSuitableForMemset(prevDataTypeDefaultInitValue, prevDataTypeId, "") && ...
            FcnPreferMemsetToAssignment(numElemInMemoryChunk, prevDataTypeId)
            %%
            %selectfile straightInitBuffer
            %assign sanitizedInitValue = ...
              FcnCastValueForMemsetUse(prevDataTypeId, prevDataTypeDefaultInitValue)
            (void) %<LibGenMemFcnCall("memset", prevStartAddr, sanitizedInitValue, ...
              "%<numElemInMemoryChunk>*sizeof(%<prevDataTypeName>)")>;
          %else
            %if numElemInMemoryChunk > 1
              %%
              %selectfile useLoopVarInitBuffer
              %<localVoidPointerName> = (void *)(%<prevStartAddr>);
              for (i = 0; i < %<numElemInMemoryChunk>; i++) {
                ((%<prevDataTypeName>*)%<localVoidPointerName>)[i] = ...
          %<prevDataTypeDefaultInitValue>;
              }
            %else
              %selectfile straightInitBuffer
              ((%<prevDataTypeName>*)%<prevStartAddr>)[0] = ...
        %<prevDataTypeDefaultInitValue>;
            %endif
          %endif
        %endif
        %%
        %if !finalPass
          %assign prevSysIdx = curSysIdx
          %assign prevInstIdx = curInstIdx
          %assign prevDataTypeId = curDataTypeId
          %assign prevMemsetToZeroSuffice = curMemsetToZeroSuffice
          %%
          %assign numElemInMemoryChunk = 0
          %%
          %if prevMemsetToZeroSuffice
            %assign prevStartAddr = "#error do not use address: memset zero sufficient"
          %else
            %% Caution: don't get address unless it will be used. The act of getting
            %% the address marks BlockIO as being accessed. Based on this mark,
            %% code generation will declare a BlockIO variable. These declaration
            %% could even occur in some other function unrelated to BlockIO
            %% initialization such as mdlTerminate.
            %%
            %assign prevStartAddr = SLibGetBlockOutputFromRecord(bo,baseSystemIdx)
          %endif
        %endif
      %endif %% if changeInMemoryChunk || finalPass
      %%
      %if !finalPass
        %assign numElemInMemoryChunk = numElemInMemoryChunk + nterms
      %endif
 
      %if finalPass
        %break
      %endif
    %endforeach %% for each boIdx
    %%
    %closefile csgInitBuffer
    %closefile straightInitBuffer
    %closefile useLoopVarInitBuffer
    %%
    %if memsetToZeroNeeded
      %if standaloneSSIdx == -1
        %assign blockIOType = IsModelReferenceTarget() ? ...
          System[NumSystems-2].Interface.tsysBlockIOType : ::tBlockIOType
        (void) %<LibGenMemFcnCall("memset", ptrBlockIOLabel, "0", ...
          "sizeof(%<blockIOType>)")>;
        %<SLibAccessArgHelper(System[baseSystemIdx].Interface.BlockIOArgDef,"","")>
      %else
        %assign type = System[standaloneSSIdx].Interface.tsysBlockIOType
        %assign var = "(void *) &" + System[standaloneSSIdx].Interface.tsysBlockIO
  
        (void) %<LibGenMemFcnCall("memset", var, "0", "sizeof(%<type>)")>;
      %endif
    %endif
    %%
    %if !WHITE_SPACE(csgInitBuffer) ...
      || !WHITE_SPACE(straightInitBuffer) ...
      || !WHITE_SPACE(useLoopVarInitBuffer)
      %% SLibGetBlockOutputFromRecord above took care of LibAccessArg
      {
        %if !WHITE_SPACE(useLoopVarInitBuffer)
          int_T i;
          void *%<localVoidPointerName>;
          %<useLoopVarInitBuffer>/
        %endif
        %<straightInitBuffer>/
        %<csgInitBuffer>/
      }
    %endif
  %endif
  %assign ::CurrentModuleIdx = -1
  %return [%<nextStdIdx>, %<nextStartIdx>]
%endfunction %% SLibInitBlockIOHelperOld
 
%%Function:LocalInitDworkVectorOld==============================================
%%Abstract:
%%Doesnotcheckremovezeroinitializationoption.Callershoulddothat.
%%ThisisonlycalledbytheoldDWorkinitializationcode(pre-2008b)
%%
%function LocalInitDworkVectorOld(stdSSBuf, stdIdx, ...
  initCount, contents, initValue, dType, baseAddr, ppIf, ppFi) void
   
  %openfile tmpBuf
  %<ppIf>
  %if initCount == 1
    %<contents> = %<initValue>;
  %elseif initCount >= RollThreshold
    %% use a loop
    {
      int_T i;
      %<dType> *dwork_ptr = (%<dType> *) %<baseAddr>;
       
      for (i = 0; i < %<initCount>; i++) {
    dwork_ptr[i] = %<initValue>;
      }
    }
  %else
    %% do not use loop
    {
      %<dType> *dwork_ptr = (%<dType> *) %<baseAddr>;
      %foreach initIdx = initCount
    dwork_ptr[%<initIdx>] = %<initValue>;
      %endforeach
    }
    %%
  %endif
  %<ppFi>
  %closefile tmpBuf
 
  %% Add the initialization code to the right buffer
  %assign stdSSBuf.DWorkBuff[stdIdx].initBuffer = ...
    stdSSBuf.DWorkBuff[stdIdx].initBuffer + tmpBuf
   
  %return stdSSBuf
%endfunction %%LocalInitDworkVectorOld
 
%%Function:SLibInitDWorkOld=====================================================
%%Abstract:
%%InitializeDWorkstructure(ie.thosewithinternalstorage)tozero
%%MemsetentireDWorkstructureto0ifnon-floatingelementsexist.
%%Assigndoubleandsinglefloating-pointelementsto0.0
%%
%%Thisfunctionreturnsvectorwiththreevalues[numeric,numeric,string]:
%%haveFloat-foundatleastonefloating-pointregion
%%needMemset-foundatleastonenon-floating-pointregion
%%initBuffer-bufferwithfloating-pointassignmentsto0.0
%%
%function SLibInitDWorkOld(stdSSBuf) void
  %assign prevDataTypeIdx = -1
  %assign prevStdIdx = -1
  %assign initCount = 0
 
  %foreach dwIdx = ::CompiledModel.DWorks.NumNonLocalDWorks
    %assign dwRec = ::CompiledModel.DWorks.DWork[dwIdx]
    %if SLibOmitRecord(dwRec) || dwRec.StorageClass != "Auto"
      %continue
    %endif
 
    %assign idx = SLibGetSystemAndCallSideIndex(dwRec)
    %if SigSrcLivesInStandaloneSS(idx)
      %assign baseSystemIdx = StandaloneParentSysIdxOfDataRec(dwRec)
    %else
      %assign baseSystemIdx = GetBaseSystemIdx()
    %endif
    %assign stdIdx = System[baseSystemIdx].IndexInStandaloneSubsystemArray
 
    %% InitialValue is not provided. Use default initial value then.
    %if SLibRemoveZeroInitForDataDefault(dwRec)
      %continue
    %endif
    %% Skip zero initialization for shared data initialized flag
    %if dwRec.SharedLocalDSMForHasBeenInit
      %continue
    %endif
    %%
    %assign nterms = SLibDWorkWidth(dwRec)
    %assign isComplex = SLibDWorkIsComplex(dwRec)
    %assign vcRecord = SLibGetDataInlineVariantNetConditions(dwRec)
    %assign vcRecord = FcnAddSharedDataInitProtection(dwRec, vcRecord)
    %assign ifCond = vcRecord.ifCond
    %assign ifEndCond = vcRecord.endIfCond
  
    %% Data type transition or standalone subsystem transition
    %if prevDataTypeIdx != SLibDWorkDataTypeId(dwRec) || prevStdIdx != stdIdx
       
      %if initCount > 0
        %assign stdSSBuf.DWorkBuff[prevStdIdx].haveFloat = 1
        %% Need to set floating-point dworks explicitly to 0.0
        %assign dType = LibGetDataTypeNameFromId(prevDataTypeIdx)
        %assign defaultInitialValue = SLibGetDefaultInitialValueFromId(prevDataTypeIdx)
        %%
        %assign stdSSBuf = ...
          LocalInitDworkVectorOld(stdSSBuf, prevStdIdx, ...
          initCount, contents, defaultInitialValue, dType, baseAddr, ifCond, ifEndCond)
        %%
        %assign initCount = 0
      %endif
      %assign prevDataTypeIdx = SLibDWorkDataTypeId(dwRec)
      %assign prevStdIdx = stdIdx
      %if (LibGetDataTypeIdAliasedThruToFromId(prevDataTypeIdx) == tSS_DOUBLE || ...
        LibGetDataTypeIdAliasedThruToFromId(prevDataTypeIdx) == tSS_SINGLE)
        %if InitFltsAndDblsToZero
          %assign name = FcnGetDWorkIdentifier(dwRec, baseSystemIdx)
          %assign dataLayout = SLibGetDataLayout(dwRec)
          %assign reim = isComplex ? ".%<tRealPart>" : ""
          %assign initCount = isComplex ? nterms * 2 : nterms
          %assign contents = "%<name>%%<reim>"
          %assign baseAddr = "&%<contents>"
        %elseif SLibZeroMemory("DWork")
          %assign stdSSBuf.DWorkBuff[stdIdx].needMemset = 1
        %endif
      %elseif (prevDataTypeIdx>1) && SLibZeroMemory("DWork")
        %assign stdSSBuf.DWorkBuff[stdIdx].needMemset = 1
      %endif
    %else
      %if LibGetDataTypeIdAliasedThruToFromId(prevDataTypeIdx) == tSS_DOUBLE ||...
        LibGetDataTypeIdAliasedThruToFromId(prevDataTypeIdx) == tSS_SINGLE
        %if InitFltsAndDblsToZero
          %assign nterms = isComplex ? nterms * 2 : nterms
          %assign initCount = initCount + nterms
        %elseif SLibZeroMemory("DWork")
          %assign stdSSBuf.DWorkBuff[stdIdx].needMemset = 1
        %endif
      %endif
    %endif
  %endforeach
  %if initCount > 0
    %assert(prevStdIdx == stdIdx)
    %assign stdSSBuf.DWorkBuff[prevStdIdx].haveFloat= 1
    %% Need to set floating-point dworks explicitly to 0.0
    %assign dType = LibGetDataTypeNameFromId(prevDataTypeIdx)
    %assign defaultInitialValue = SLibGetDefaultInitialValueFromId(prevDataTypeIdx)
    %assign stdSSBuf = ...
      LocalInitDworkVectorOld(stdSSBuf,prevStdIdx, ...
      initCount, contents, defaultInitialValue, dType, baseAddr, ifCond, ifEndCond)
  %endif
   
  %if stdSSBuf.DWorkBuff[0].needMemset
    %assert(!IsModelReferenceTarget())
    %assign baseSystemIdx = GetBaseSystemIdx()
    %<SLibAccessArgHelper(System[baseSystemIdx].Interface.DWorkArgDef,"","")>
  %endif
  %% SLibGetDataLayout above took care of LibAccessArg for what's in initBuffer
  %return stdSSBuf
 
%endfunction %% SLibInitDWorkOld
 
%function SLibIsSimulinkFunctionArginReused(fcnRec, arginIdx) void
  %assign isInout = TLC_FALSE
  %foreach inoutIdx = (SIZE(fcnRec.InoutArgs)[1])/2
    %if fcnRec.InoutArgs[ inoutIdx * 2 ] == arginIdx
      %assign isInout = TLC_TRUE
      %break
    %endif
  %endforeach
  %return isInout
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/inlineVariants/wiperexample/twipervariant.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/simulinkFunction/tmMdlScopedAISFAndSSFTop_VC1.m
%%
%function FcnSlFcnInputArgTypeStrAuto(typeName, argName, fcnRec, argIdx, width, cgTypeIdx, slTypeIdx, isAutosarRteActive)
  %if isAutosarRteActive
    %% AUTOSAR uses const for certain schemas
    %assign constPrefix = SLibAutosarGetPtrConstPrefix()
  %else
    %assign constPrefix = "const"
  %endif
   
  %if LibCGTypeIsMatrix(cgTypeIdx) && "1"!=width
    %if isAutosarRteActive
      %assign arg = "%<constPrefix> %<typeName>* %<argName>"
      %assign isPtrType = TLC_TRUE
    %else
      %assign argName = "%<argName>[%<width>]"
      %assign arg = "%<constPrefix> %<typeName> %<argName>"
      %assign isPtrType = TLC_FALSE
    %endif
    %assign isConstData = ISEQUAL(constPrefix,"const")
  %elseif LibCGTypeIsStruct(cgTypeIdx) && ...
    !LibIsDataTypeMultiWordFixpt(slTypeIdx) && ...
    !LibCGTypeIsComplex(cgTypeIdx)
    %assign arg = "%<constPrefix> %<typeName> *%<argName>"
    %assign isPtrType = TLC_TRUE
    %assign isConstData = ISEQUAL(constPrefix,"const")
  %else
    %assign arg = "%<typeName> %<argName>"
    %assign isConstData = TLC_FALSE
    %assign isPtrType = TLC_FALSE
  %endif
   
  %if SLibAutosarCompilerAbstractionRequired()
    %assign retType = SLibAutosarCompilerAbstractionForDataDecl(isConstData, typeName, isPtrType, TLC_FALSE, argName, "DataAutomatic")
  %else
    %assign retType = arg
  %endif
 
  %return retType
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/inlineVariants/simulinkFunction/tmMdlScopedAISFAndSSFTop_VC1.m
%%
%function FcnSlFcnInputArgTypeStr(typeName, argName, fcnRec, argIdx, width, cgTypeIdx, slTypeIdx, isAutosarRteActive)
  %assign passByType = fcnRec.ArginPassByType[argIdx]
   
  %if passByType==eSLFARG_PASSBYTYPE.AUTO
    %return FcnSlFcnInputArgTypeStrAuto(typeName, argName, fcnRec, argIdx, width, cgTypeIdx, slTypeIdx,isAutosarRteActive)
  %else
    %assign isaVoidPtr = passByType==eSLFARG_PASSBYTYPE.POINTER_VOID || passByType==eSLFARG_PASSBYTYPE.POINTER_CONST_VOID
    %if isaVoidPtr
      %assign typeName = "void"
    %endif
    %assign typeStr = typeName
     
    %assign isArrSizeOne = passByType==eSLFARG_PASSBYTYPE.ARR_SIZEONE || passByType==eSLFARG_PASSBYTYPE.CONST_ARR_SIZEONE
    %assign isMatrix = !isaVoidPtr && ...
      ( isArrSizeOne || (LibCGTypeIsMatrix(cgTypeIdx) && "1"!=width) )
    %if isMatrix
      %assign typeStr = "%<typeStr> %<argName>[%<width>]"
      %assign isPtrType = TLC_FALSE
    %else
      %% handle pointer type
      %switch passByType
        %case eSLFARG_PASSBYTYPE.POINTER
        %case eSLFARG_PASSBYTYPE.POINTER_VOID
        %case eSLFARG_PASSBYTYPE.POINTER_CONST_VOID
        %case eSLFARG_PASSBYTYPE.POINTER_CONST_DATA
          %assign typeStr = "%<typeStr> *%<argName>"
          %assign isPtrType = TLC_TRUE
          %break
        %case eSLFARG_PASSBYTYPE.CONST_POINTER_CONST_DATA
          %assign typeStr = "%<typeStr> * const %<argName>"
          %assign isPtrType = TLC_TRUE
          %break
        %default
          %assign typeStr = "%<typeStr> %<argName>"
          %assign isPtrType = TLC_FALSE
      %endswitch
    %endif
     
    %% handle const data
    %switch passByType
      %case eSLFARG_PASSBYTYPE.CONST_DATA
      %case eSLFARG_PASSBYTYPE.CONST_ARR_SIZEONE
      %case eSLFARG_PASSBYTYPE.POINTER_CONST_DATA
      %case eSLFARG_PASSBYTYPE.POINTER_CONST_VOID
      %case eSLFARG_PASSBYTYPE.CONST_POINTER_CONST_DATA
        %assign typeStr = "const %<typeStr>"
        %assign isConstData = TLC_TRUE
        %break
      %default
        %assign isConstData = TLC_FALSE
    %endswitch
     
    %if SLibAutosarCompilerAbstractionRequired()
      %if isMatrix
        %assign argName = "%<argName>[%<width>]"
      %endif
      %assign retType = SLibAutosarCompilerAbstractionForDataDecl(isConstData, typeName, isPtrType, TLC_FALSE, argName, "DataAutomatic")
    %else
      %assign retType = typeStr
    %endif
     
    %return retType
  %endif
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/inlineVariants/simulinkFunction/tmMdlScopedAISFAndSSFTop_VC1.m
%%
%function FcnSlFcnOutputArgTypeStrAuto(typeName, argName, width, cgTypeIdx, isAutosarRteActive)
    %assign isMatrix = LibCGTypeIsMatrix(cgTypeIdx) && "1"!=width
    %if isMatrix
      %if isAutosarRteActive
        %assign arg = "%<typeName>* %<argName>"
        %assign isPtrType = TLC_TRUE
      %else
        %assign argName = "%<argName>[%<width>]"
        %assign arg = "%<typeName> %<argName>"
        %assign isPtrType = TLC_FALSE
      %endif
    %else
      %assign arg = "%<typeName> *%<argName>"
      %assign isPtrType = TLC_TRUE
    %endif
     
    %if SLibAutosarCompilerAbstractionRequired()
      %assign retType = SLibAutosarCompilerAbstractionForDataDecl(TLC_FALSE, typeName, isPtrType, TLC_FALSE, argName, "DataAutomatic")
    %else
      %assign retType = arg
    %endif
 
    %return retType
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/inlineVariants/simulinkFunction/tmMdlScopedAISFAndSSFTop_VC1.m
%%
%function FcnSlFcnOutputArgTypeStr(typeName, argName, fcnRec, argIdx, width, cgTypeIdx, isAutosarRteActive)
  %assign passByType = fcnRec.ArgoutPassByType[argIdx]
   
  %if passByType==eSLFARG_PASSBYTYPE.AUTO
    %return FcnSlFcnOutputArgTypeStrAuto(typeName, argName, width, cgTypeIdx, isAutosarRteActive)
  %else
    %assign isaVoidPtr = passByType==eSLFARG_PASSBYTYPE.POINTER_VOID || passByType==eSLFARG_PASSBYTYPE.POINTER_CONST_VOID
    %if isaVoidPtr
      %assign typeName = "void"
    %endif
    %assign typeStr = typeName
     
    %assign isArrSizeOne = passByType==eSLFARG_PASSBYTYPE.ARR_SIZEONE
    %assign isMatrix = !isaVoidPtr && ...
      ( isArrSizeOne || (LibCGTypeIsMatrix(cgTypeIdx) && "1"!=width) )
    %if isMatrix
      %assign typeStr = "%<typeStr> %<argName>[%<width>]"
      %assign isPtrType = TLC_FALSE
    %else
      %switch passByType
        %case eSLFARG_PASSBYTYPE.POINTER
        %case eSLFARG_PASSBYTYPE.POINTER_VOID
          %assign typeStr = "%<typeStr> *%<argName>"
           %assign isPtrType = TLC_TRUE
          %break
        %default
          %assign errTxt = "Invalid type specified for output argument '%<argName>' of Simulink Function '%<fcnRec.Name>'"
          %<LibReportFatalError(errTxt)>
      %endswitch
    %endif
     
    %if SLibAutosarCompilerAbstractionRequired()
      %if isMatrix
        %assign argName = "%<argName>[%<width>]"
      %endif
      %assign retType = SLibAutosarCompilerAbstractionForDataDecl(TLC_FALSE, typeName, isPtrType, TLC_FALSE, argName, "DataAutomatic")
    %else
      %assign retType = typeStr
    %endif
     
    %return retType
  %endif
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortFcnCall3.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/simulinkFunction/tVariantSimulinkFunctionAutoInherit.m
%%
%function FcnDeclareSimulinkFunctionArg(fcnRec, argType, argIdx, arg, args, sep, isAutosarRteActive, stripAlias) void
  %if argType == "I"
    %assign cgTypeIdx = fcnRec.ArginCGTypeIdxFlat[argIdx]
    %assign slTypeIdx = LibCGTypeToSLType(cgTypeIdx)
    %assign argType = stripAlias ? LibAliasedThruCGTypeName(cgTypeIdx) : LibCGTypeName(cgTypeIdx)
    %assign width = LibCGTypeSymbolicWidth(cgTypeIdx)
     
    %assign arg = FcnSlFcnInputArgTypeStr(argType, arg, fcnRec, argIdx, width, cgTypeIdx, slTypeIdx, isAutosarRteActive)
     
    %assign args = "%<args>%<sep>%<arg>"
    %assign sep = ", "
  %else
    %assert argType == "O"
    %assign cgTypeIdx = fcnRec.ArgoutCGTypeIdxFlat[argIdx]
    %assign argType = stripAlias ? LibAliasedThruCGTypeName(cgTypeIdx) : LibCGTypeName(cgTypeIdx)
    %assign width = LibCGTypeSymbolicWidth(cgTypeIdx)
     
    %assign arg = FcnSlFcnOutputArgTypeStr(argType, arg, fcnRec, argIdx, width, cgTypeIdx, isAutosarRteActive)
     
    %assign args = "%<args>%<sep>%<arg>"
    %assign sep = ", "
  %endif
  %return args
%endfunction
 
%%Function:SLibDeclareSimulinkFunction=============================
%%Abstract:
%function SLibDeclareSimulinkFunction(fcnRec, stripAlias, useSlArgNames) Output
  %if SuppressSimulinkFunctionArgumentControl == "yes"
    %assign fcnDecl = SLibDeclareSimulinkFunctionIgnoreArgMap(fcnRec, stripAlias)
  %else
    %assign fcnDecl = SLibDeclareSimulinkFunctionUseArgMap(fcnRec, stripAlias, useSlArgNames)
  %endif
 
  %return fcnDecl
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/inlineVariants/simulinkFunction/-tVariantSimulinkFunctionAutoInherit.m
%%
%function SLibDeclareSimulinkFunctionIgnoreArgMap(fcnRec, stripAlias) Output
  %% We don't need to always extern the Simulink function in the top model,
  %% if it was already externed in a referenced model. We are restricting this
  %% for now to rapid-accel to fix g1085730, although it could apply for
  %% any top model. We need this because rapid-accel can change the names
  %% of bus objects when they have external header files. Externs with different
  %% types cause compiler errors for gcc and clang (but not Visual).
  %if ::isRAccel && ...
    (((fcnRec.IsCalled == "yes") && (fcnRec.IsCalledInThisModel == "no")) || ...
    ((fcnRec.IsDefined == "yes") && (fcnRec.IsDefinedInThisModel == "no")))
    %return
  %endif
   
  %if !SLibSimulinkFunctionNeedsDeclaration(fcnRec)
    %return
  %endif
   
  %assign args = ""
  %assign sep = ""
  %assign isAutosarRteActive = TLC_FALSE
  %foreach idx = SIZE(fcnRec.ArginCGTypeIdxFlat)[1]
    %assign argType = "I"
    %assign arg = "argin%<idx>"
    %assign args = FcnDeclareSimulinkFunctionArg(fcnRec, argType, idx, arg, args, sep, isAutosarRteActive, stripAlias)
    %assign sep = ","
  %endforeach
  %foreach idx = SIZE(fcnRec.ArgoutCGTypeIdxFlat)[1]
    %assign argType = "O"
    %assign arg = "argout%<idx>"
    %assign args = FcnDeclareSimulinkFunctionArg(fcnRec, argType, idx, arg, args, sep, isAutosarRteActive, stripAlias)
    %assign sep = ","
  %endforeach
  %assign fcnPrototype = "extern void %<fcnRec.CGFunctionName>("
  %assign comma = ""
  %assign needsContext = (fcnRec.IsMultiInstance == "yes") && !::GenerateClassInterface
  %if needsContext
    %assign fcnPrototype = fcnPrototype + "%<tSimStructType> * const %<tSimStruct>"
    %assign comma = ","
  %endif
  %if args != ""
    %assign fcnPrototype = fcnPrototype + "%<comma>%<args>);//"
  %else
    %if needsContext
      %assign fcnPrototype = fcnPrototype + ");//"
    %else
      %assign fcnPrototype = fcnPrototype + "void);//"
    %endif
  %endif
  %openfile buffer
  %<fcnPrototype>
  %closefile buffer
  %return buffer
%endfunction
 
%function SLibDeclareSimulinkFunctionUseArgMap(fcnRec, stripAlias, useSlArgNames) Output
     
  %if !SLibSimulinkFunctionNeedsDeclaration(fcnRec)
    %return
  %endif
  %assign fcnLHS = SLibSimulinkFunctionDeclarationGetLHS(fcnRec)
  %assign isAutosarRteActive = TLC_FALSE
  %assign fcnRHS = SLibSimulinkFunctionDeclarationGetRHS(fcnRec, isAutosarRteActive, stripAlias, useSlArgNames)
  %assign extern = ::GenerateClassInterface ? "" : "extern"
  %openfile buffer
   %<extern> %<fcnLHS> %<fcnRec.CGFunctionName>(%<fcnRHS>);/
  %closefile buffer
  %return buffer
 
%endfunction
 
%%Function:SLibSimulinkFunctionDeclarationGetRHS========================
%%Abstract:returnrighthandsideargumentsforsimulinkfunctionprototype
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortFcnCall3.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/simulinkFunction/tVariantSimulinkFunctionAutoInherit.m
%function SLibSimulinkFunctionDeclarationGetRHS(fcnRec, isAutosarRteActive, stripAlias, useSlArgNames)
  %assign argIndices = fcnRec.ArgIndices
  %assign argNames = fcnRec.ArgNames
  %assign numArgs = SIZE(argIndices)[1]
  %if numArgs == 0
    %assign args = "void"
  %else
    %assign args = ""
    %assign sep = ""
  %endif
  %if !::GenerateClassInterface && ...
    (fcnRec.IsDefinedInThisModel == "yes" && ...
      (MultiInstanceERTCode || (IsModelReferenceTarget() && ::CompiledModel.OkToMultiInstanceModelref)))
    %assign arg = "%<tSimStructType> * const %<tSimStruct>"
    %assign args = "%<arg>%<sep>%<args>"
    %assign sep = ", "
  %endif
  %foreach idx = numArgs
    %assign argIdNum = IDNUM(argIndices[idx])
    %assign argType = argIdNum[0]
    %assign argIdx = argIdNum[1]
    %if useSlArgNames
      %if argType == "I"
        %assign arg = fcnRec.SlArginNames[argIdx]
      %else
        %assert argType == "O"
        %assign arg = fcnRec.SlArgoutNames[argIdx]
      %endif
    %else
      %assign arg = argNames[idx]
    %endif
    %assign args = FcnDeclareSimulinkFunctionArg(fcnRec, argType, argIdx, arg, args, sep, isAutosarRteActive, stripAlias)
    %assign sep = ", "
  %endforeach
  %return args
%endfunction
 
%%Function:SLibSimulinkFunctionDeclarationGetLHS========================
%%Abstract:%%Abstract:returnlegthandsideargumentsforsimulinkfunctionprototype
%function SLibSimulinkFunctionDeclarationGetLHS(fcnRec)
  %assign retIdx = fcnRec.ReturnArgIndex
  %if retIdx < 0
    %assign retType = "void"
  %else
    %assign cgTypeIdx = fcnRec.ArgoutCGTypeIdxFlat[retIdx]
    %assign retType = LibCGTypeName(cgTypeIdx)
  %endif
   
  %% Add AUTOSAR compiler abstraction macro to function declaration return type if required
  %if SLibAutosarCompilerAbstractionRequired()
    %assign retType = SLibAutosarCompilerAbstractionForFcnDeclRtnType(retType, "FuncCalledByRTE", "")
  %endif
 
%return retType
%endfunction
 
%%Function:SLibSimulinkFunctionNeedsDeclaration=========================
%function SLibSimulinkFunctionNeedsDeclaration(fcnRec)
  %if (fcnRec.IsConstUncalledFunction == "yes" || ...
       (fcnRec.IsCalledInThisModel == "no") && ...
       (fcnRec.IsDefinedInThisModel == "no")) || ...
      ISEMPTY(fcnRec.FullPathToFunction) || ...
      (fcnRec.FullPathToFunction[0] != "G" && fcnRec.FullPathToFunction[0] != "P" ) || ...
      (fcnRec.IsMultiInstance == "yes")
    %assign needsDecalartion = TLC_FALSE
  %else
    %assign needsDecalartion = TLC_TRUE
  %endif
%return needsDecalartion
%endfunction
 
%function SLibRateGroupedSimulinkFunctionNeedsDeclaration(system, aFcnType, aTID)
  %if SLibIsRateGroupedSLFcn(system, aFcnType, aTID)
    %foreach fcnIdx = NumSimulinkFunctions
      %assign fcn = SimulinkFunction[fcnIdx]
      %if fcn.CGFunctionName == SampleTime[aTID].EntryFcnName && ...
        SLibSimulinkFunctionNeedsDeclaration(fcn) && ...
        !(GenerateClassInterface && fcn.FullPathToFunction != "G") && ...
        !IsModelReferenceSimTarget()
        %return TLC_TRUE
      %endif
    %endforeach
  %endif
  %return TLC_FALSE
%endfunction
 
%%Function:SLibGetRateGroupedSimulinkFunctionName============================
%%Abstract
%%GetSimulinkFunctionnameforasysteminanexportfunctionmodel.
%%NOTE:ForGlobalandexported-Publicfunctionsonly.
%%
%function SLibGetRateGroupedSimulinkFunctionName(system, aFcnType, aTID)
  %assign fcnName = ""
  %if SLibIsRateGroupedSLFcn(system, aFcnType, aTID)
    %foreach fcnIdx = NumSimulinkFunctions
      %assign fcn = SimulinkFunction[fcnIdx]
      %if fcn.CGFunctionName == SampleTime[aTID].EntryFcnName
        %return fcn.Name
      %endif
    %endforeach
  %endif
  %return fcnName
%endfunction
 
%%Function:SLibGetSimulinkFunctionNameInNonExportFcnModel====================
%%Abstract
%%GetSimulinkFunctionnameforasysteminanon-exportfunctionmodel
%%NOTE:ForGlobalandexported-Publicfunctionsonly.
%%
%function SLibGetSimulinkFunctionNameInNonExportFcnModel(system)
  %assign fcnName = ""
  %if LibIsGlobalServer(system) || SLibIsModelScopedServer(system)
    %foreach fcnIdx = NumSimulinkFunctions
      %assign fcn = SimulinkFunction[fcnIdx]
      %if fcn.CGFunctionName == system.Identifier
        %return fcn.Name
      %endif
    %endforeach
  %endif
  %return fcnName
%endfunction
 
%%Function:SLibWriteSFunctionGuards=====================================
%%Abstract
%%FormodelreferenceSIMtarget,wesometimeneedtobranchbasedon
%%whetherornotrapidacceleratorissimulation.Fornon-SIMtargets
%%(i.e.,generatingS-Functioncode),thesamedecisionneedstobe
%%made,butitdependsonwhetherornotwearecompilingfora
%%Mexfile(i.e.,MATLAB_MEX_FILEisdefinedornot).Thismethod
%%helpswriteoutthecorrectguardsinthecorrectsituations.
%function SLibWriteSFunctionGuards(sectionName) Output
 
   
  %switch sectionName
      %case "if"
        %assign preprocessorVal = "#if defined(MATLAB_MEX_FILE)"
        %assign codeVal = "if(! slIsRapidAcceleratorSimulating())"
 
        %assign startBrace = "{"
        %assign stopBrace = ""
        %break
         
      %case "else"
        %assign preprocessorVal = "#else"
        %assign codeVal = "else"
 
        %assign startBrace = "{"
        %assign stopBrace = "}"
        %break
         
      %case "endif"
        %assign preprocessorVal = "#endif"
        %assign codeVal = ""
 
        %assign startBrace = ""
        %assign stopBrace = "}"
        %break
         
      %default
        %assert TLC_FALSE
    %endswitch
     
     
    %<stopBrace>
     
    %% Embed the decision in the code itself for model reference SIM targets.
    %% Otherwise, use the preprocessor
    %if IsModelReferenceTarget()
      %<codeVal>
    %else
      %<preprocessorVal>
    %endif
       
    %<startBrace>
%endfunction
 
%%Function:IsConfiguredForConditionalMATFileCode============================
%%Abstract:
%%ChecksifMATFileloggingforoutputsisswitchedon,andtheoutputports
%%areconditional.ThiscanhappenwhenthemodelhasVariantSource/Sinkblocks.
%%TopTester:test/toolbox/simulink/variants/outputWhenUnconnected/tOutWhenUnconnected.m
%%TopTester:test/toolbox/simulink/variants/string/tStringSupport.m
%%
%function IsConfiguredForConditionalMATFileCode() void
 
%assign isConditionalLoggingCodeNeeded = TLC_FALSE
%assign dlo = ::CompiledModel.DataLoggingOpts
%if MatFileLogging && FcnIsOutputLoggingEnabled(dlo)
  %% Get the table of unique variant conditions for the model.
  %if ISFIELD(VariantConditions, "CGVCEList")
   %assign cgvceList = VariantConditions.CGVCEList
 %else
   %assign cgvceList = ""
 %endif
 %assign nOutportBlks = ExternalOutputs.NumExternalOutputs
  %foreach idx = nOutportBlks
    %assign extOut = ExternalOutputs.ExternalOutput[idx]
    %assign sysIdx = extOut.Block[0]
    %assign blkIdx = extOut.Block[1]
    %assign outportBlock = System[sysIdx].Block[blkIdx]
    %if !FcnExtOutLoggable(extOut)
      %continue
    %endif
 
    %if ISFIELD(extOut, "LocalCGVCEIdx") && (extOut.LocalCGVCEIdx != -1)
      %assign variantCondition = cgvceList[extOut.LocalCGVCEIdx]
    %else
      %continue
    %endif
     
    %if ISFIELD(outportBlock, "Inactive")
      %continue
    %endif
    %if !ISEMPTY(variantCondition)
     %assign isConditionalLoggingCodeNeeded = TLC_TRUE
     %break
    %endif
 %endforeach
%endif
 
%return isConditionalLoggingCodeNeeded
%endfunction %% IsConfiguredForConditionalMATFileCode
 
 
 
%%Function:SLibDeclareExternalSimulinkFunctions=============================
%%Abstract:
%%DeclareSimulinkFunctionsformodelreferencing.Thedefinitionof
%%thefunctioniscontainedinanothermodelwithinthemodelhierarchy.
%function SLibDeclareExternalSimulinkFunctions() Output
 
  %% Necessary for simulation of model reference accelerator targets
  %if !(IsModelReferenceSimTarget() || isRAccel)
    %return
  %endif
   
  %with ::CompiledModel
    %openfile tmpBuf
    %foreach fcnIdx = NumSimulinkFunctions
      %assign fcnRec = SimulinkFunction[fcnIdx]
      %if SLibSimulinkFunctionNeedsDeclaration(fcnRec) && fcnRec.IsRateGrouped == "no"
        %<SLibDeclareSimulinkFunction(fcnRec, TLC_FALSE, TLC_FALSE)>
      %endif
    %endforeach
    %closefile tmpBuf
    %if !WHITE_SPACE(tmpBuf)
      %<SLibCacheCodeToFile("mdl_hdr_userBottom", tmpBuf)>
    %endif
  %endwith
   
%endfunction
 
 
%function SLibSimulinkFunctionCtx(tType, tArg) void
  %if tType == "tSimStruct"
    %return RTMGet("MdlRefSfcnS")
  %elseif tType == "tFunction"
    %return "/"%<tArg>/""
  %else
    %assign errTxt = "Unknown option tType in SLibSimulinkFunctionCtx"
    %<LibReportFatalError(errTxt)>
  %endif
%endfunction
 
%function SLibInitLegacyStorageClassVarGroup(varGroupIdx) void
  %openfile returnBuffer
  %assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
  %foreach elIdx = varGroup.NumVarGroupElements
    %assign idnum = IDNUM(SLibVarGroupElementSource(varGroupIdx, elIdx))
    %assign recType = idnum[0]
    %assign recIdx = idnum[1]
    %if SLibIsLocalVariableRecordType(varGroupIdx, elIdx)
      %continue
    %endif
 
    %if recType == "VG"
      %assign subGroupBuff = SLibInitLegacyStorageClassVarGroup(recIdx)
      %<subGroupBuff>
      %continue
    %endif
     
    %assign dataRec = SLibGetDataRecForVarGroupMember(recType, recIdx)
    %assign cscDefn = dataRec.CSCDefn
    %assign dataInit = SLibGetDataInitForData(cscDefn, dataRec)
    %if ((dataInit == "Static" || dataInit == "None") || ...
      (ISFIELD(dataRec, "RecordType") && dataRec.RecordType == "ModelParameter" && dataInit == "Auto"))
      %continue
    %endif
 
    %if !ISEMPTY(SLibDataTypeConstructFcnName(LibGetRecordDataTypeId(dataRec)))
      %continue
    %endif
     
    %assign dataScope = SLibGetDataScope(dataRec.CSCDefn, dataRec)
    %if dataScope == "Imported"
      %continue
    %endif
 
    %assign isExtOut = (ISFIELD(dataRec, "RecordType") && dataRec.RecordType == "ExternalOutput")
    %% If we ignore external outputs for initialization, or we shouldn't initialize
    %% it, skip it.
    %if isExtOut && (FcnIgnoreExtOutForInit(dataRec) || !FcnInitializeExternalOutput(dataRec))
      %continue
    %endif
 
    %assign vcRecord = SLibGetDataInlineVariantNetConditions(dataRec)
    %assign ifCond = vcRecord.ifCond
    %assign ifEndCond = vcRecord.endIfCond
 
    %% If the initializaation is going into a different file, cache it
    %% separately in stdSSBuffer
    %assign stdSSIdx = -1
    %assign sysIdx = -1
 
    %if (ISFIELD(dataRec, "RecordType") && ...
      (dataRec.RecordType == "BlockOutput" || dataRec.RecordType == "DWork"))
      %assign sysIdx = StandaloneParentSysIdxOfDataRec(dataRec)
      %if sysIdx == -1 && dataScope == "File"
        %assign sysIdx = FcnGetNonRootFileFunctionOwner(dataRec, sysIdx)
      %endif
    %endif
 
    %if sysIdx != -1
      %assign stdSSIdx = sysIdx
      %assign stdSSBuffer = ""
    %endif
 
    %openfile initCode
    %if isExtOut
      %% If this is an external output, then scope the external outport block
      %% Calls within SLibEmitLibCustomInitCode() rely on this.
      %assign sysIdx = dataRec.Block[0]
      %assign blkIdx = dataRec.Block[1]
      %assign outportBlock = System[sysIdx].Block[blkIdx]
      %with outportBlock
        %<SLibEmitLibCustomInitCode(dataRec, LibGetRecordSymbolicWidth(dataRec), LibGetRecordIsComplex(dataRec))>
      %endwith
    %else
      %<SLibEmitLibCustomInitCode(dataRec, LibGetRecordSymbolicWidth(dataRec), LibGetRecordIsComplex(dataRec))>
    %endif
    %closefile initCode
 
    %if !WHITE_SPACE(initCode)
      %if stdSSIdx != -1
        %% If this is going to a subsystem file, push it into a temp buffer
        %openfile tmpBuffer
      %endif
      %<ifCond>
      %<initCode>
      %<ifEndCond>
      %if stdSSIdx != -1
        %closefile tmpBuffer
        %assign stdSSBuffer = stdSSBuffer + tmpBuffer
      %endif
    %endif
 
    %% Cache away the separate file init code in a temp buffer
    %if stdSSIdx != -1 && !WHITE_SPACE(stdSSBuffer)
      %<LibAddToSystemField(System[stdSSIdx],"TempInitBuffer",...
        stdSSBuffer)>
    %endif
  %endforeach
  %closefile returnBuffer
 
  %% Grab the temporarily cached code for each system and add it to
  %% the initialize for the system.
  %<FcnCacheStandaloneSubsyInitFromTempBuffers("/* Storage classes */")>
 
  %return returnBuffer
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants6.m-tcodevariants9.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%
%function SLibInitBlockIOForVarGroup(varGroupIdx, initBuffers)
  %assign retBuffers = initBuffers
  %assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
  %foreach elIdx = varGroup.NumVarGroupElements
    %assign idnum = IDNUM(varGroup.VarGroupElements[elIdx])
    %assign recType = idnum[0]
    %assign recIdx = idnum[1]
    %if recType == "B"
      %assign bo = ::CompiledModel.BlockOutputs.GlobalBlockOutput[recIdx]
      %assign ret = SLibInitBlockIOForBufferHelper(bo, baseSystemIdx, TLC_TRUE)
      %if !bo.InitInStart
        %% Take the init code only for buffers not initialized in start function
        %assign retBuffers.buffers[0] = retBuffers.buffers[0] + ret[0]
        %assign retBuffers.buffers[1] = retBuffers.buffers[1] + ret[1]
        %assign retBuffers.buffers[2] = retBuffers.buffers[2] + ret[2]
      %endif
      %if ret[3]
        %% If memset flag is set for any buffer, do memset
        %assign retBuffers.buffers[3] = ret[3]
      %endif
      %% Additional initialization of string data in Model Reference Accelerator mode
      %% NOTE: memset flag is ignored in this mode, see comment below the call-site
      %% of this function in SLibDumpERTAndModelrefInitMemoryCode
      %if IsModelReferenceSimTarget() || ::isRAccel
        %assign boDataTypeId = LibGetRecordDataTypeId(bo)
        %assign boWidth = LibGetRecordWidth(bo)
        %assign id = SLibGetBlockOutputIdentifierFromRecord(bo, baseSystemIdx)
        %openfile stringInitBuffer
        %<SlibInitStringData(boDataTypeId, id, boWidth)>
        %closefile stringInitBuffer
        %assign retBuffers.buffers[1] = retBuffers.buffers[1] + stringInitBuffer
      %endif
    %elseif recType == "W"
      %assign dwRec = ::CompiledModel.DWorks.DWork[recIdx]
      %% Skip zero initialization for shared data initialized flag
      %if dwRec.SharedLocalDSMForHasBeenInit
        %continue
      %endif
      %assign idx = SLibGetSystemAndCallSideIndex(dwRec)
      %if SigSrcLivesInStandaloneSS(idx)
        %assign sysIdxToUse = StandaloneParentSysIdxOfDataRec(dwRec)
      %else
        %assign sysIdxToUse = GetBaseSystemIdx()
      %endif
      %assign cross = System[sysIdxToUse].CrossNoArgFcnBound
     
      %assign vcRecord = SLibGetDataInlineVariantNetConditions(dwRec)
      %assign vcRecord = FcnAddSharedDataInitProtection(dwRec, vcRecord)
      %assign ifCond = vcRecord.ifCond
      %assign ifEndCond = vcRecord.endIfCond
 
      %assign stdIdx = System[sysIdxToUse].IndexInStandaloneSubsystemArray
      %assign retBuffers.ssBuf = SLibInitDWorkHelper(retBuffers.ssBuf, stdIdx, sysIdxToUse, ...
        cross, dwRec, TLC_FALSE, ifCond, ifEndCond)
    %elseif recType == "VG"
      %assign retBuffers = SLibInitBlockIOForVarGroup(recIdx, retBuffers)
    %endif
  %endforeach
  %return retBuffers
%endfunction
 
%endif %% _REGLIB_
 
%%[EOF]commonreglib.tlc