%%
%%Copyright1994-2019TheMathWorks,Inc.
%%
%%Abstract:
%%ThisTLClibraryfilecontainsalltheblockI/Ofunctions.
%%
 
%if EXISTS("_BLKIOLIB_") == 0
%assign _BLKIOLIB_ = 1
 
%include "blkio_api.tlc"
%include "blkio_internalapi.tlc"
 
%function PassExtInpByRef(extInp)
  %if extInp.RecordType != "ExternalInput" || ...
    extInp.StorageClass != "Auto"
    %<LibReportFatalError("invalid record type or storage class")>
  %endif
  %assign dataType = LibGetRecordDataTypeId(extInp)
  %assign passByRef = MultiInstanceERTCode && !RootIOStructures && ...
    (::BlockFcn == "Registration" || ...
     ::BlockFcn == "Start" || ...
     ::BlockFcn == "Initialize" || ...
     ::BlockFcn == "Enable" || ...
     ::BlockFcn == "RegistrationAndStart" || ...
     SLibDeclareDataAsPointer(dataType)) && ...
     !LibGetRecordIsMatrix(extInp)
  %return passByRef
%endfunction
 
%function PassExtOutpByRef(extOutp)
  %assign passByRef = MultiInstanceERTCode && !RootIOStructures && ...
    !LibGetRecordIsMatrix(extOutp)
  %return passByRef
%endfunction
 
%%DocFunction{InputSignalFunctions}:LibBlockInputSignal====================
%%Abstract:
%%Basedontheinputportnumber(portIdx),theusercontrolvariable
%%(ucv),theloopcontrolvariable(lcv),thesignalindex(sigIdx),and
%%wherethisinputsignaliscomingfrom,LibBlockInputSignalreturns
%%theappropriatereferencetoablockinputsignal.
%%
%%Thereturnedstringvalueisavalidrvalue(righthandsideassignment
%%value)foranexpression.Theblockinputsignalmaybecomingfrom
%%anotherblock,astatevector,anexternalinput,agroundvariable,
%%aparameter,specialmemorylocation,oritcanbealiteralconstant
%%(e.g.5.0).
%%
%%Sincethereturnedvaluecanbealiteralconstant,youshouldnotusethis
%%functiontoaccesstheaddressofaninputsignal.Toaccesstheaddressof
%%aninputsignal,useLibBlockInputSignalAddr.Accessingtheaddressofthe
%%signalviaLibBlockInputSignalmayresultinareferencetoaliteral
%%constant(e.g.,5.0).
%%
%%Forexample,
%%-InC,thefollowingwouldnotwork:
%%%assignu=LibBlockInputSignal(0,"",lcv,sigIdx)
%%x=&%<u>;
%%
%%If%<u>referstoainvariantsignalwithavalueof4.95,the
%%statement(afterbeingprocessedbythepre-processor)wouldbe
%%generatedas
%%
%%x=&4.95;
%%
%%or,iftheinputsignalsourcestoground,thestatementcould
%%comeoutas
%%
%%x=&0.0;
%%
%%neitherofthesewouldcompile.
%%
%%-YouavoidanysuchsituationsbyusingLibBlockInputSignalAddr():
%%
%%%assignuAddr=LibBlockInputSignalAddr(0,"",lcv,sigIdx)
%%x=%<uAddr>;
%%
%%SimulinkCodertrackssignalsandparametersaccessedbytheir
%%addressanddeclarestheminaddressablememory.
%%
%%Inputarguments:
%%portIdx-Anintegerspecifyingtheinputportindexstartingat0.
%%Note,forcertainbuild-inblocksthiscanbeastring
%%identifyingtheport(e.g.,"enable","trigger",etc.).
%%ucv-mustbeastring,either""oranindexingexpression.
%%lcv-mustbeastring,either""oranindexingexpression
%%generatedbythe%rollconstruct.Seethe%rollconstruct.
%%sigIdx-eitheranintegerliteralorastringoftheform
%%%<tRealPart>Integer
%%%<tImagPart>Integer
%%Forexample:
%%"%<tRealPart>5"therealpartofthesignalstartingat
%%index5.
%%"%<tImagPart>5"theimaginarypartofthesignalstarting
%%atindex5.
%%
%%Generalusage:
%%1)Directindexing.Ifucv==""andlcv=="",thenreturnan
%%indexingexpressionfortheelementspecifiedbysigIdx.
%%
%%2)Looprolling/unrollingusingthe%rolldirectiveandthe"Roller"
%%TLCfile.
%%
%%Inthiscase,lcvandsigIdxaregeneratedbythe%rolldirective,
%%anducvmustbe"".Anon-emptyvalueforlcvisonly
%%allowedwhengeneratedbythe%rolldirectiveandwhenusing
%%theRollerTLCfile(orausersuppliedRollerTLCfilethatconforms
%%tothesamevariable/signaloffsethandling).Inaddition,callsto
%%LibBlockInputSignalwithlcvshouldonlyoccurwhen"U"oraspecific
%%inputport(e.g."u0")ispassedtothe%rolldirectiveviatheroll
%%variablesargument.Anexamplethatisappropriateforasingle
%%input/singleoutputportS-function:
%%
%%%assignrollVars=["U","Y","P"]
%%%rollsigIdx=RollRegions,lcv=RollThreshold,block,...
%%"Roller",rollVars
%%%assignu=LibBlockInputSignal(0,"",lcv,sigIdx)
%%%assigny=LibBlockOutputSignal(0,"",lcv,sigIdx)
%%%assignp=LibBlockParameter(0,"",lcv,sigIdx)
%%%<y>=%<p>*%<u>;
%%%endroll
%%
%%Withthe%rolldirective,sigIdxisalwaysthestartingindex
%%ofthecurrentrollregionandlcvwillbe""oraindexing
%%variable,thusthefollowingarevalidvaluesexamples:
%%
%%
%%LibBlockInputSignal(0,"",lcv,sigIdx)rtB.blockname[0]
%%LibBlockInputSignal(0,"",lcv,sigIdx)u[i]
%%
%%
%%ThefirstLibBlockInputSignalcallreturnsrtB.blockname[2]when
%%inputportisconnectedtotheoutputofanotherblockand
%%a)theloopcontrolvariable(lcv)generatedbythe%roll
%%directiveisempty,indicatingthatthecurrentrollregion
%%isbelowtherollthresholdandsigIdxis0.IfsigIdx
%%wasnon-zero(say3),thenrtB.blockname[3].
%%b)thewidthoftheinputportis1indicatingthatthis
%%portisbeingscalarexpanded.
%%
%%ThesecondLibBlockInputSignalcallreturnsu[i]whenthe
%%currentrollregionisabovetherollthresholdandtheinput
%%portwidthisnon-scalar(wide).Inthiscase,theRoller
%%TLCfilesetsupalocalvariable,u,topointtotheinput
%%signalandthecodeinthecurrent%rolldirectiveisplaced
%%withinaforloop.
%%
%%
%%Foranotherexample,supposewehaveablockwithmultipleinput
%%portswhereeachporthaswidth>=1andatleastoneporthaswidth
%%equalto1.Letssettheoutputsignaltothesumofthesquaresof
%%alltheinputsignals.
%%
%%%assigny=LibBlockOutputSignal(0,"","",0)
%%y=0;
%%
%%%assignrollVars=["U"]
%%%foreachport=block.NumDataInputPorts-1
%%%rollsigIdx=RollRegions,lcv=RollThreshold,block,...
%%"Roller",rollVars
%%%assignu=LibBlockInputSignal(port,"",lcv,sigIdx)
%%y+=%<u>*%<u>;
%%%endroll
%%%endforeach
%%
%%SincethefirstparameterofLibBlockInputSignalis0-indexed,you
%%mustindextheforeachlooptostartfrom0andendat
%%NumDataInputPorts-1.
%%
%%3)ucvhandling.Thisisanadvancedmodeandgenerallynotneededby
%%S-functionauthors.
%%
%%Ifucv!="",thenreturnarvaluefortheinputsignalusingthe
%%usercontrolvariableindexingexpressionoftheform:
%%
%%rvalue_id[%<ucv>]%<optional_real_or_imag_part>
%%
%%o)rvalue_idisobtainedbylookingattheintegerpartofsigIdx.
%%SpecifyingsigIdxisrequiredbecausetheinputtothisblockcan
%%bediscontiguousmeaningthattheinputcomesfromseveral
%%differentmemoryareas(signalsources)andsigIdxisusedto
%%identifytheareaofinterestfortheucv.AlsosigIdxisused
%%todetermineifweareaccessingtherealorimaginarypartof
%%asignal.
%%
%%o)optional_real_or_imag_partisobtainedbythestringpartof
%%sigIdx(i.e."re",or"im",or"").
%%
%%Note,thevalueforlcvisignoredandsigIdxmustpointtothesame
%%elementintheinputsignalthattheucvinitiallypointsto.
%%
%%ThehandlingofucvwithLibBlockInputSignalrequiresalotofcare.
%%Consideradiscontiguousinputsignalfeedinganinputportasin:
%%
%%.------..-----.
%%|sin1|------->||
%%`------'||.-------.
%%|mux|--------->|block|
%%.------.||`-------'
%%|sin2|------->||
%%`------'`-----'
%%
%%Touseucvinarobustmanner,youmustusethe%rolldirectivewith
%%arollthresholdof1andarollertlcfilethathasnoloop
%%header/trailersetupforthisinputsignal.Inaddition,youneedto
%%useROLL_ITERATIONStodeterminethewidthofthecurrentroll
%%region.SomeexampleCTLCcode:
%%
%%{
%%inti;
%%
%%%assignrollVars=[""]
%%%assignthreshold=1
%%%rollsigIdx=RollRegions,lcv=threshold,block,...
%%"FlatRoller",rollVars
%%%assignu=LibBlockInputSignal(0,"i","",sigIdx)
%%%assigny=LibBlockOutputSignal(0,"i+%<sigIdx>","",sigIdx)
%%%assignp=LibBlockParameter(0,"i+%<sigIdx>","",sigIdx)
%%for(i=0;i<%<ROLL_ITERATIONS()>;i++){
%%%<y>=%<p>*%<u>;
%%}
%%%endroll
%%}
%%
%%Note,theFlatRollerhasnoloopheader/trailersetup(rollVars
%%isignored).It'spurposeistowalktheRollRegionsofthe
%%block.
%%
%%Alternatively,youcanforceacontiguousinputsignaltoyourblock
%%byspecifying
%%ssSetInputPortRequiredContiguous(S,port,true)
%%inyourS-functionandthenyourTLCcodesimplifiesto:
%%
%%{
%%%assignu=LibBlockInputSignal(0,"i","",0)
%%%assigny=LibBlockOutputSignal(0,"i","",0)
%%%assignp=LibBlockParameter(0,"i","",0)
%%
%%for(i=0;i<%<LibGetRecordWidth(DataInputPort[0])>;i++){
%%%<y>=%<p>*%<u>;
%%}
%%}
%%
%%Ifyoucreateyourownrollerandtheindexingdoesn'tconform
%%tothewaytheRollerTLCfileworks,thenyouwillneedtouseucv
%%insteadoflcv.
%%
%%
%%Reviewofinputarguments(ucv,lcv,andsigIdx)handling:
%%
%%Functioncalls(case1,2,3,4):Examplereturnvalue
%%-----------------------------------------------------------
%%LibBlockInputSignal(0,"i","",sigIdx)rtB.blockname[i]
%%LibBlockInputSignal(0,"i","",sigIdx)rtU.signame[i]
%%LibBlockInputSignal(0,"",lcv,sigIdx)u0[i1]
%%LibBlockInputSignal(0,"",lcv,sigIdx)rtB.blockname[0]
%%
%%Thevaluereturneddependsonwhattheinputsignalis
%%connectedtointheblockdiagramandhowthefunctionisbeing
%%invoked(e.g.ina%rollordirectly).Intheaboveexample,
%%-Case1&2occurswhenanexplicitcallismadewiththeucvsetto
%%"i".
%%-Case1occurswhensigIdxpointingtotheblockI/Ovector,i.e.,
%%thefirstelementthat"i"startswith.Forexample,ifyou
%%initialize"i"tobestartingatoffset5,thenyoushouldspecify
%%sigIdx==5.
%%-Case2occurswhensigIdxpointingtotheexternalinputvector,
%%i.e.,thefirstelementthat"i"startswith.Forexample,ifyou
%%initialize"i"tobestartingatoffset20,thenyoushouldspecify
%%sigIdx==20.
%%-Cases3and4receivethesamearguments,lcvandsigIdxhowever
%%theyproducedifferentreturnvalues.
%%-Case3occurswhenLibBlockInputSignaliscalledwithina
%%%rolldirectiveandthecurrentrollregionisbeingrolled
%%(lcv!="").
%%-Case4occurswhenLibBlockInputSignaliscalledwithina
%%%rolldirectiveandthecurrentrollregionisnotbeingrolled
%%(lcv=="").
%%
%%Whencalledwithina%rolldirective,thisfunctionlooksatucv,
%%lcv,andsigIdx,thecurrentrollregion,andthecurrentroll
%%thresholdtodeterminethereturnvalue.Thevariableucvhashighest
%%precedence,lcvhasthenexthighestprecedence,andsigIdxhasthe
%%lowestprecedence.Thatis,ifucvisspecified,itwillbeused
%%(thus,whencalledina%rolldirectiveitisusually"").Ifucvis
%%notspecifiedandlcvandsigIdxarespecified,thereturnedvalue
%%dependsonwhetherornotthecurrentrollregionisbeingplacedin
%%aforlooporbeingexpanded.Iftherollregionisbeingplacedina
%%loopthen,lcvisused,otherwisesigIdxisused.
%%
%%Adirectcalltothisfunction(insideoroutsideofa%roll
%%directive)willusesigIdxwhenucvandlcvarespecifiedas"".
%%
%%Foranexampleuseofthisfunction,see
%%matlabroot/toolbox/simulink/blocks/tlc_c/sfun_multiport.tlc.
%%
%function LibBlockInputSignal(portIdx, ucv, lcv, sigIdx) void
 
  %% Optionally recurse on input
  %if LibBlockInputSignalIsExpr(portIdx)
    %assign ip = FcnGetInputPortRecord(portIdx)
    %assign srcSys = System[ip.SrcIdx[0]]
    %assign srcBlk = srcSys.Block[ip.SrcIdx[1]]
    %assign srcPort = ip.SrcIdx[2]
 
    %% Move lcv to ucv to prevent usage of rolling tmp vars
    %if lcv != ""
      %if ucv != ""
        %<LibReportFatalError("invalid indexing into output expression")>
      %endif
      %assign ucv = lcv
      %assign lcv = ""
    %endif
 
    %with srcSys %% switch system context if needed
      %% Update expression comment
      %<FcnAddToExprCommentList(srcBlk, srcPort)>
 
      %assign cast = LibOutputExprCast(srcBlk, srcPort)
      %assign retSignal = SLibBlockOutputSignal(srcBlk,srcSys,srcPort,ucv,lcv,sigIdx,"Signal")
      %if cast != ""
        %assign retSignal = "(%<cast>%<retSignal>)"
      %endif
 
    %endwith %% srcSys
 
    %% We don't clear (set to -1) these until after SLibBlockOutputSignal
    %% because we want their info during the possible recursion in
    %% SLibBlockOutputSignal.
 
    %assign srcBlk.ExprCommentSrcIdx.SysIdx = -1
    %assign srcBlk.ExprCommentSrcIdx.BlkIdx = -1
 
    %return SLibProcessSafeExpression(srcBlk.Name, retSignal, 1)
 
  %endif
 
  %% Handle scalar expansion of ucv
  %if (ucv != "" && LibBlockInputSignalSymbolicWidth(portIdx) == "1")
    %assign tmpVect = SLibGetReimAndIdx(sigIdx)
    %assign reim = tmpVect[0]
    %assign sigIdx = "%<reim>0"
    %assign ucv = ""
  %endif
 
  %% See Also:
  %% LibBlockInputSignalAddr,
  %% LibBlockOutputSignal,
  %% LibBlockOutputSignalAddr,
  %% LibBlockParameter,
  %% LibBlockParameterAddr
  %%
  %assign retSignal = FcnGetInputOrOutputSignal("input",portIdx, ucv, ...
    lcv, sigIdx)
 
  %return retSignal
 
%endfunction %% LibBlockInputSignal
 
%function FcnAddToExprCommentList (srcBlk, srcPort) void
 
  %if ExprCommentSrcIdx.SysIdx != -1
    %% transfer comment info from port
    %assign srcBlk.ExprCommentSrcIdx.SysIdx = ExprCommentSrcIdx.SysIdx
    %assign srcBlk.ExprCommentSrcIdx.BlkIdx = ExprCommentSrcIdx.BlkIdx
  %else
    %% transfer comment info from block
    %assign srcBlk.ExprCommentSrcIdx.SysIdx = BlockIdx[0]
    %assign srcBlk.ExprCommentSrcIdx.BlkIdx = BlockIdx[2]
  %endif
 
  %assign commSysIdx = srcBlk.ExprCommentSrcIdx.SysIdx
  %assign commBlkIdx = srcBlk.ExprCommentSrcIdx.BlkIdx
  %assign commInfo = System[commSysIdx].Block[commBlkIdx].ExprCommentInfo
 
  %<SLibAddToExprCommentList(commInfo,srcBlk,srcPort)>
 
%endfunction %% FcnAddToExprCommentList
 
%%DocFunction{InputSignalFunctions}:LibBlockInputSignalAddr================
%%Abstract:
%%ReturnsappropriateCstringprovidingthethememoryaddressof
%%thespecifiedblockinputportsignal.
%%
%%Whenaninputsignaladdressisneeded,youmustusethisfunction
%%insteadofappendingan"&"tothestringreturnedbyLibBlockInputSignal.
%%Forexample,LibBlockInputSignalcanreturnaliteralconstant,
%%suchas5(i.e.aninvariantinputsignal).SimulinkCodertracks
%%whenLibBlockInputSignalAddriscalledonaninvariantsignalanddeclares
%%thesignalas"const"data(whichisaddressable),insteadofbeingplaced
%%asaliteralconstantinthegeneratedcode(whichisnotaddressable).
%%
%%Note,unlikeLibBlockInputSignal()thelastinputargument,sigIdx,
%%isnotoverloaded.Hence,iftheinputsignaliscomplex,the
%%addressofthecomplexcontainerisreturned.
%%
%%Example:
%%Togettheaddressofawideinputsignalandpassittoa
%%user-functionforprocessingonecoulduse:
%%
%%%assignuAddr=LibBlockInputSignalAddr(0,"","",0)
%%%assigny=LibBlockOutputSignal(0,"","",0)
%%y=myfcn(%<uAddr>);
%%
%function LibBlockInputSignalAddr(portIdx, ucv, lcv, sigIdx) void
 
  %% See Also:
  %% LibBlockInputSignal,
  %% LibBlockOutputSignal,
  %% LibBlockOutputSignalAddr,
  %% LibBlockParameter
  %% LibBlockParameterAddr
 
  %if LibBlockInputSignalIsExpr(portIdx)
    %%START_ASSERT
    %assign errTxt = "%<Type> block %<Name> has specified that input " ...
      "port %<portIdx> can be an expression, however the block is " ...
      "attempting to obtain the address of this input in TLC using " ...
      "LibBlockInputSignalAddr. The conflict must be resolved."
    %<LibReportFatalError(errTxt)>
    %%END_ASSERT
  %endif
 
  %assign retSignal = FcnGetInputOrOutputSignal("inputAddr",portIdx, ucv, ...
    lcv, sigIdx)
 
  %return retSignal
 
%endfunction %% LibBlockInputSignalAddr
 
%%DocFunction{InputSignalFunctions}:LibBlockInputSignalIsMatrix============
%%Abstract:
%%Returnstrueifthegivenblockinputport(index)isconnectedtoa
%%matrixorvectorsignal.
%%
%function LibBlockInputSignalIsMatrix(portIdx) void
  %% See Also:
  %% LibBlockOutputSignalIsMatrix
  %%
  %assign ip = FcnGetInputPortRecord(portIdx)
  %return LibGetRecordIsMatrix(ip)
%endfunction %% LibBlockInputSignalIsMatrix
 
%%DocFunction{InputSignalFunctions}:LibBlockInputSignalSymbolicWidth=======
%%Abstract:
%%Returnsthesymbolicwidthofthespecifiedblockinputportindex.
%%
%function LibBlockInputSignalSymbolicWidth(portIdx) void
  %assign ip = FcnGetInputPortRecord(portIdx)
  %return LibGetRecordSymbolicWidth(ip)
%endfunction %% LibBlockInputSignalSymbolicWidth
 
%%DocFunction{InputSignalFunctions}:LibBlockInputSignalSymbolicDims===
%%Abstract:
%%Returnsthesymbolicdimensionsofthespecifiedblockinputport
%%index.
%%
%function LibBlockInputSignalSymbolicDims(portIdx) void
  %assign ip = FcnGetInputPortRecord(portIdx)
  %return LibGetRecordSymbolicDims(ip)
%endfunction %% LibBlockInputSignalSymbolicDims
 
%%DocFunction{InputSignalFunctions}:LibBlockInputHasSymbolicWidth==========
%%Abstract:
%%Returnstrueifthespecifiedblockinputportindexhassymbolic
%%dimensions.
%%
%function LibBlockInputHasSymbolicWidth(portIdx) void
  %assign ip = FcnGetInputPortRecord(portIdx)
  %return LibRecordHasSymbolicWidth(ip)
%endfunction %% LibBlockInputHasSymbolicWidth
 
%%SLibNumInputPortRegions=====================================================
%%Abstract:
%%Returnsthenumberofregionsforgivenblockandinputportindex.
%%
%function SLibNumInputPortRegions(aBlock, aInputPortIdx)
  %assign numRegions = 0
  %assign ip = aBlock.DataInputPort[aInputPortIdx]
  %assign prevSrc = ""
  %foreach idx = SIZE(ip.SignalSrc, 1)
    %assign currSrc = IDNUM(ip.SignalSrc[idx])[0]
    %if currSrc != prevSrc
      %assign numRegions = numRegions + 1
      %assign prevSrc = currSrc
    %endif
  %endforeach
  %return numRegions
%endfunction
 
%%SLibBlockSystemToCallForInput===============================================
%%Abstract:
%%Returnstheconditionallyexecutedsystemtocallfortheinputport.
%%
%function SLibBlockSystemToCallForInput(portIdx) void
  %% See Also:
  %%
  %assign ip = FcnGetInputPortRecord(portIdx)
  %return ip.SystemToCall
%endfunction %% LibBlockSystemToCallForInput
 
%%
%%Returnsthedimensionsvectorofspecifiedblockinputport,e.g.["2","3"]
%%
%function LibBlockInputSignalSymbolicDimensions(portIdx) void
  %assign ip = FcnGetInputPortRecord(portIdx)
  %return LibCGTypeSymbolicDimensions(LibGetRecordCGTypeIdx(ip))
%endfunction %% LibBlockInputSignalSymbolicDimensions
 
%%DocFunction{InputSignalFunctions}:LibBlockInputSignalDataTypeName========
%%Abstract:
%%Returnsthenameofthedatatype(e.g.,int_T,...creal_T)corresponding
%%tothespecifiedblockinputport.
%%
%%Specifythereimargumentas""ifyouwantthecompletesignaltypename.
%%Forexample,ifreim==""andthefirstoutputportisrealandcomplex,
%%thedatatypenameplacedindtnamewillbecreal_T.
%%
%%%assigndtname=LibBlockInputSignalDataTypeName(0,"")
%%
%%SpecifythereimargumentastRealPartifyouwanttherawelementtype
%%name.Forexample,ifreim==tRealPartandthefirstoutputportisreal
%%andcomplex,thedatatypenamereturnedwillbereal_T.
%%
%%%assigndtname=LibBlockOutputSignalDataTypeName(0,tRealPart)
%%
%function LibBlockInputSignalDataTypeName(portIdx, reim) void
  %% See Also:
  %% LibBlockOutputSignalDataTypeName, LibBlockParameterDataTypeName
  %%
 
  %if Type == "S-Function" && !ParamSettings.AliasDataTypeCompliant
    %return LibBlockInputSignalAliasedThruDataTypeName(portIdx, reim)
  %else
    %assign ip = FcnGetInputPortRecord(portIdx)
    %return SLibGetRecordDataTypeName(ip, reim)
  %endif
%endfunction %% LibBlockInputSignalDataTypeName
 
%%DocFunction{InputSignalFunctions}:LibBlockInputSignalAliasedThruDataTypeName====
%%Abstract:
%%Returnsthenameofthealiasedthrudatatype(e.g.,int_T,...creal_T)
%%correspondingtothespecifiedblockinputport.
%%
%%Specifythereimargumentas""ifyouwantthecompletesignaltypename.
%%Forexample,ifreim==""andthefirstoutputportisrealandcomplex,
%%thedatatypenameplacedindtnamewillbecreal_T.
%%
%%%assigndtname=LibBlockInputSignalDataTypeName(0,"")
%%
%%SpecifythereimargumentastRealPartifyouwanttherawelementtype
%%name.Forexample,ifreim==tRealPartandthefirstoutputportisreal
%%andcomplex,thedatatypenamereturnedwillbereal_T.
%%
%%%assigndtname=LibBlockOutputSignalDataTypeName(0,tRealPart)
%%
%function LibBlockInputSignalAliasedThruDataTypeName(portIdx, reim) void
  %% See Also:
  %% LibBlockOutputSignalAliasedThruDataTypeName
  %%
 
  %assign ip = FcnGetInputPortRecord(portIdx)
  %return LibGetRecordAliasedThruDataTypeName(ip, reim)
%endfunction %% LibBlockInputSignalAliasedThruDataTypeName
 
 
%%DocFunction{InputSignalFunctions}:LibBlockInputSignalUnitId==========
%%Abstract:
%%Returnsthenumericidentifier(id)correspondingtotheunitsofthe
%%specifiedblockinputport.
%%
%function LibBlockInputSignalUnitId(portIdx) void
 
  %% See Also:
  %% LibBlockInputSignalUnitExpr
  %% LibBlockOutputSignalUnitId
  %% LibBlockParameterUnitId
  %%
  %assign ip = FcnGetInputPortRecord(portIdx)
  %return LibGetRecordUnitId(ip)
%endfunction %% LibBlockInputSignalUnitId
 
 
%%DocFunction{InputSignalFunctions}:LibBlockInputSignalUnitExpr========
%%Abstract:
%%Returnsthenameoftheunitscorresponding
%%tothespecifiedblockinputport.
%%
%function LibBlockInputSignalUnitExpr(portIdx) void
  %% See Also:
  %% LibBlockOutputSignalUnitExpr, LibBlockParameterUnitExpr
  %%
  %assign ip = FcnGetInputPortRecord(portIdx)
  %return SLibGetRecordUnitExpr(ip)
%endfunction %% LibBlockInputSignalUnitExpr
 
 
%%DocFunction{InputSignalFunctions}:LibBlockInputSignalASCIIEscapedUnitExpr========
%%Abstract:
%%Returnstheescapednameoftheunitscorresponding
%%tothespecifiedblockinputport.
%%
%function LibBlockInputSignalASCIIEscapedUnitExpr(portIdx) void
  %% See Also:
  %% LibBlockInputSignalUnitExpr
  %%
  %assign ip = FcnGetInputPortRecord(portIdx)
  %return SLibGetRecordASCIIEscapedUnitExpr(ip)
%endfunction %% LibBlockInputSignalASCIIEscapedUnitExpr
 
%%DocFunction{InputSignalFunctions}:LibBlockInputPortIsContinuousQuantity========
%%Abstract:
%%Returnswhethertheinputportacceptsaco-simsignal.
%%
%function LibBlockInputPortIsContinuousQuantity(portIdx) void
  %assign ip = FcnGetInputPortRecord(portIdx)
  %if EXISTS("ip.IsContinuousQuantity")
    %if ip.IsContinuousQuantity == "yes"
      %return TLC_TRUE
    %endif
  %endif
  %return TLC_FALSE
%endfunction %%LibBlockInputPortIsContinuousQuantity
 
%%DocFunction{InputSignalFunctions}:LibBlockInputSignalSampleTime==========
%%Abstract:
%%Returnsthesampletimecorrespondingtothespecifiedblockinput
%%port.
%%
%function LibBlockInputSignalSampleTime(portIdx) void
  %% See Also:
  %% LibBlockOutputSignalSampleTime, LibBlockInputSignalSampleTimeIndex,
  %% LibBlockInputSignalOffsetTime
  %%
  %if EXISTS("InputPortSampleTimes")
    %assign idx = InputPortSampleTimes[portIdx]
  %else
    %%START_ASSERT
    %assign errTxt = "SampleTime is not contained within the specified record"
    %<LibBlockReportError([],errTxt)>
    %%END_ASSERT
  %endif
  %return idx
%endfunction %% LibBlockInputSignalSampleTime
 
 
%%DocFunction{InputSignalFunctions}:LibBlockInputSignalOffsetTime==========
%%Abstract:
%%Returnstheoffsettimecorrespondingtothespecifiedblockinput
%%port.
%%
%function LibBlockInputSignalOffsetTime(portIdx) void
  %% See Also:
  %% LibBlockOutputSignalOffsetTime, LibBlockInputSignalSampleTimeIndex,
  %% LibBlockInputSignalSampleTime
  %%
  %if EXISTS("InputPortOffsetTimes")
    %assign idx = InputPortOffsetTimes[portIdx]
  %else
    %%START_ASSERT
    %assign errTxt = "OffsetTime is not contained within the specified record"
    %<LibBlockReportError([],errTxt)>
    %%END_ASSERT
  %endif
  %return idx
%endfunction %% LibBlockInputSignalOffsetTime
 
 
%%DocFunction{InputSignalFunctions}:LibBlockInputSignalSampleTimeIndex=====
%%Abstract:
%%Returnsthesampletimeindexcorrespondingtothespecifiedblockinput
%%port.
%%
%function LibBlockInputSignalSampleTimeIndex(portIdx) void
  %% See Also:
  %% LibBlockOutputSignalSampleTimeIndex, LibBlockInputSignalSampleTime,
  %% LibBlockInputSignalOffsetTime
  %%
  %if EXISTS("InputPortTIDs")
    %assign idx = InputPortTIDs[portIdx]
  %else
    %%START_ASSERT
    %assign errTxt = "SampleTimeIndex is not contained within the specified record"
    %<LibBlockReportError([],errTxt)>
    %%END_ASSERT
  %endif
  %return idx
%endfunction %% LibBlockInputSignalSampleTimeIndex
 
 
%%DocFunction{InputSignalFunctions}:LibBlockInputSignalLocalSampleTimeIndex
%%Abstract:
%%Returnsthelocalsampletimeindexcorrespondingtothespecifiedblock
%%inputport.
%%
%function LibBlockInputSignalLocalSampleTimeIndex(portIdx) void
  %% See Also:
  %% LibBlockOutputSignalSampleTimeIndex, LibBlockInputSignalSampleTime,
  %% LibBlockInputSignalOffsetTime,
  %% LibBlockOutputSignalLocalSampleTimeIndex
  %%
  %if EXISTS("InputPortLocalTIDs")
    %assign idx = InputPortLocalTIDs[portIdx]
  %else
    %%START_ASSERT
    %assign errTxt = "LocalSampleTimeIndex is not contained within the specified record"
    %<LibBlockReportError([],errTxt)>
    %%END_ASSERT
  %endif
  %return idx
%endfunction %% LibBlockInputSignalLocalSampleTimeIndex
 
%%DocFunction{AdvancedFunctions}:LibBlockInputSignalBufferDstPort===========
%%Abstract:
%%Returnstheoutputportcorrespondingtoinputport(portIdx)whichshare
%%thesamememory,otherwise(-1)isreturned.Youwillneedtousethis
%%functionwhenyouspecifyssSetInputPortOverWritable(S,portIdx,true)in
%%yourS-function.
%%
%%Ifaninputportandsomeoutputportofablockare
%%
%%1)nottestpointsand
%%2)theinputportisoverwritable,
%%
%%thentheoutputportmightreusethesamebufferastheinputport.
%%Inthiscase,LibBlockInputSignalBufferDstPortreturnstheindexofthe
%%outputportthatreusesthespecifiedinputport'sbuffer.Ifnoneof
%%theblock'soutputportsreusethespecifiedinputportbuffer,then
%%thisfunctionreturns-1.
%%
%%ThisfunctionistheTLCimplementationoftheSimulinkmacro
%%ssGetInputPortBufferDstPort.
%%
%%Example:
%%Assumeyouhaveablockthathastwoinputports,bothofwhichreceive
%%acomplexnumberin2-widevectors.Theblockoutputstheproduct
%%ofthetwocomplexnumbers.
%%
%%%assignu1r=LibBlockInputSignal(0,"","",0)
%%%assignu1i=LibBlockInputSignal(0,"","",1)
%%%assignu2r=LibBlockInputSignal(1,"","",0)
%%%assignu2i=LibBlockInputSignal(1,"","",1)
%%%assignyr=LibBlockOutputSignal(0,"","",0)
%%%assignyi=LibBlockOutputSignal(0,"","",1)
%%
%%%if(LibBlockInputSignalBufferDstPort(0)!=-1)
%%%%Thefirstinputisgoingtogetoverwrittenbyyrso
%%%%weneedtosavetherealpartinatemporaryvariable.
%%{
%%real_TtmpRe=%<u1r>;
%%%assignu1r="tmpRe";
%%%endif
%%
%%%<yr>=%<u1r>*%<u2r>-%<u1i>*%<u2i>;
%%%<yi>=%<u1r>*%<u2i>+%<u1i>*%<u2r>;
%%
%%%if(LibBlockInputSignalBufferDstPort(0)!=-1)
%%}
%%%endif
%%
%%Notethatinthiscase,wecouldhaveequivalentlyused
%%(LibBlockInputSignalBufferDstPort(0)==0)asthebooleancondition
%%forthe%ifstatementssincethereisonlyoneoutputport.
%%
%function LibBlockInputSignalBufferDstPort(portIdx)
  %assign ip = FcnGetInputPortRecord(portIdx)
  %if ip.BufferDstPort < 0
    %foreach opIdx = NumDataOutputPorts
      %if ip.SignalSrc[0] == DataOutputPort[opIdx].SignalSrc[0]
        %return opIdx
      %endif
    %endforeach
    %return -1
  %else
    %return ip.BufferDstPort
  %endif
%endfunction %% LibBlockInputSignalBufferDstPort
 
 
%%DocFunction{AdvancedFunctions}:LibBlockInputSignalStorageClass============
%%Abstract:
%%Returnsthestorageclassofthespecifiedblockinputportsignal.
%%Thestorageclasscanbe"Auto","ExportedSignal","ImportedExtern",
%%"ImportedExternPointer","Custom".
%%
%function LibBlockInputSignalStorageClass(portIdx, sigIdx) void
  %assign ip = FcnGetInputPortRecord(portIdx)
  %assign mapSource = IDNUM(ip.SignalSrc[sigIdx])[0]
 
  %if (mapSource == "L" || mapSource == "b" || mapSource == "B" || ...
       mapSource == "I" || mapSource == "C" || mapSource == "G" || ...
       mapSource == "x" || mapSource == "X" || mapSource == "F" || ...
       mapSource == "Y" || ...
       ip.HaveGround == "all")
 
    %return "Auto"
  %else
    %assign sigRec = SLibGetSourceRecord(ip, sigIdx)
    %if (SLibIsLegacyStorageClassForDataRecord(sigRec))
      %return "Custom"
    %else
      %return sigRec.StorageClass
    %endif
  %endif
%endfunction %% LibBlockInputSignalStorageClass
 
 
%%DocFunction{AdvancedFunctions}:LibBlockInputSignalStorageTypeQualifier====
%%Abstract:
%%Returnsthestoragetypequalifierofthespecifiedblockinputport
%%signal.Thetypequalifiercanbeanythingenteredbytheusersuch
%%as"const".Thedefaulttypequalifieris"Auto"-meaningdothe
%%defaultaction.
%%
%function LibBlockInputSignalStorageTypeQualifier(portIdx, sigIdx) void
  %% See Also:
  %% LibBlockOutputSignalStorageTypeQualifier
  %%
  %assign ip = FcnGetInputPortRecord(portIdx)
  %assign mapSource = IDNUM(ip.SignalSrc[sigIdx])[0]
 
  %if (mapSource == "L" || mapSource == "b" || mapSource == "B" || ...
       mapSource == "I" || mapSource == "G" || mapSource == "x" || ...
       mapSource == "X" || mapSource == "F" || mapSource == "Y" || ...
       ip.HaveGround == "all")
    %return ""
  %elseif mapSource == "C"
    %assign tmpVec = LibBlockSrcSignalBlock(portIdx, sigIdx)
    %assign sysIdx = tmpVec[0]
    %assign blkIdx = tmpVec[1]
    %assign srcBlock = ::CompiledModel.System[sysIdx].Block[blkIdx]
    %% If a block with a constant output expression has more than 1
    %% runtime parameter, we don't really know which parameter it is
    %% that is output as an expression, and we'll just return the
    %% default "" in that case
    %if srcBlock.Parameters[0] == 1
      %assign mdlParamIdx = ...
        FcnGetModelParamIdxFromBlockParam(srcBlock.Parameter[0])
      %% If we can't identify a unique model parameter from the block
      %% parameter, mdlParamIdx will be < 0, and we'll just return the
      %% default "" in that case
      %if mdlParamIdx >= 0
        %assign mdlParam = ModelParameters.Parameter[mdlParamIdx]
        %return SLibGetModelParameterTypeQualifier(mdlParam)
      %else
        %return ""
      %endif
    %else
      %return ""
    %endif
  %else
    %assign sigRec = SLibGetSourceRecord(ip, sigIdx)
    %return sigRec.StorageTypeQualifier
  %endif
%endfunction %% LibBlockInputSignalTypeQualifier
 
 
%%DocFunction{OutputSignalFunctions}:LibBlockOutputSignal==================
%%Abstract:
%%Basedontheoutputportnumber(portIdx),theusercontrolvariable(ucv),
%%theloopcontrolvariable(lcv),thesignalindex(sigIdx),andwherethe
%%outputsignaldestination,LibBlockOutputSignalreturnsthe
%%appropriatereferencetoablockoutputsignal.
%%
%%Thereturnedvalueisavalidlvalue(leftvalue)foranexpression.
%%TheblockoutputdestinationcanbealocationintheblockI/Ovector
%%(anotherblock'sinput),thestatevector,oranexternaloutput.
%%
%%Note,neverusethisfunctiontoaccesstheaddressofanoutputsignal.
%%SimulinkCodertrackswhenavariable(e.g.signalsand
%%parameters)isaccessedbyitsaddress.Toaccesstheaddressofan
%%outputsignaluseLibBlockOutputSignalAddrasinthefollowingexample:
%%%assignyAddr=LibBlockOutputSignalAddr(0,"",lcv,sigIdx)
%%x=%<yAddr>;
%%
%function LibBlockOutputSignal(portIdx, ucv, lcv, sigIdx) void
 
  %if LibBlockOutputSignalIsExpr(portIdx)
    %return ""
  %endif
 
  %% See Also:
  %% LibBlockInputSignal,
  %% LibBlockInputSignalAddr,
  %% LibBlockOutputSignalAddr,
  %% LibBlockParameter
  %% LibBlockParameterAddr
  %%
  %assign retSignal = FcnGetInputOrOutputSignal("output",portIdx, ucv, ...
    lcv, sigIdx)
 
  %return retSignal
 
 
%endfunction %% LibBlockOutputSignal
 
 
%%DocFunction{OutputSignalFunctions}:LibBlockOutputSignalAddr==============
%%Abstract:
%%Returnsappropriatestringprovidingthethememoryaddressof
%%thespecifiedblockoutputportsignal.
%%
%%Whenanoutputsignaladdressisneeded,youmustusethisfunction
%%insteadoftakingtheaddressofisreturnedbyLibBlockOutputSignal.
%%Forexample,LibBlockOutputSignalcanreturnaliteralconstant,
%%suchas5(i.e.aninvariantoutputsignal).When
%%LibBlockOutputSignalAddriscalledonaninvariantsignal,thesignal
%%isdeclaredasa"const"insteadofbeingplacedasaliteral
%%constantinthegeneratedcode.
%%
%%Note,unlikeLibBlockOutputSignal()thelastargument,sigIdx,
%%isnotoverloaded.Hence,iftheoutputsignaliscomplex,the
%%addressofthecomplexcontainerisreturned.
%%
%%Example:
%%Togettheaddressofawideoutputsignalandpassittoa
%%user-functionforprocessingonecoulduse:
%%
%%%assignu=LibBlockOutputSignalAddr(0,"","",0)
%%%assigny=LibBlockOutputSignal(0,"","",0)
%%y=myfcn(%<u>);
%%
%function LibBlockOutputSignalAddr(portIdx, ucv, lcv, sigIdx) void
 
  %if LibBlockOutputSignalIsExpr(portIdx)
    %return ""
  %endif
 
  %% See Also:
  %% LibBlockInputSignal,
  %% LibBlockInputSignalAddr,
  %% LibBlockOutputSignal,
  %% LibBlockParameter
  %% LibBlockParameterAddr
  %%
  %assign retSignal = FcnGetInputOrOutputSignal("outputAddr",portIdx, ucv, ...
    lcv, sigIdx)
 
  %return retSignal
 
%endfunction %% LibBlockOutputSignalAddr
 
 
%%DocFunction{OutputSignalFunctions}:LibBlockOutputSignalWidth=============
%%Abstract:
%%Returnsthewidthofspecifiedblockoutputport.
%%
%function LibBlockOutputSignalWidth(portIdx) void
  %% See Also:
  %% LibBlockInputSignalWidth,
  %% LibBlockOutputSignalNumDimensions, LibBlockOutputSignalDimensions
  %%
  %assign op = FcnGetOutputPortRecord(portIdx)
  %assign opWidth = LibGetRecordWidth(op)
  %if opWidth != -1
    %return opWidth
  %else
    %assign sigRec = SLibGetSourceRecord(op, 0)
    %if ISEMPTY(sigRec) %% FcnCall
      %return NumSFcnSysOutputCalls
    %else
      %return LibGetRecordWidth(sigRec)
    %endif
  %endif
%endfunction %% LibBlockOutputSignalWidth
 
%%DocFunction{OutputSignalFunctions}:LibBlockOutputSignalIsMatrix==========
%%Abstract:
%%Returnstrueifthegivenblockinputport(index)isconnectedtoa
%%matrixorvectorsignal.
%%
%function LibBlockOutputSignalIsMatrix(portIdx) void
  %% See Also:
  %% LibBlockInputSignalIsMatrix
  %%
  %assign ip = FcnGetOutputPortRecord(portIdx)
  %return LibGetRecordIsMatrix(ip)
%endfunction %% LibBlockOutputSignalIsMatrix
 
%%DocFunction{OutputSignalFunctions}:LibBlockOutputSignalSymbolicWidth=====
%%Abstract:
%%Returnsthesymbolicwidthofspecifiedblockoutputport.
%%
%function LibBlockOutputSignalSymbolicWidth(portIdx) void
  %% See Also:
  %% LibBlockInputSignalWidth,
  %% LibBlockOutputSignalNumDimensions, LibBlockOutputSignalDimensions
  %%
  %assign op = FcnGetOutputPortRecord(portIdx)
  %if LibGetRecordIsMatrix(op)
    %return LibGetRecordSymbolicWidth(op)
  %else
    %assign sigRec = SLibGetSourceRecord(op, 0)
    %if ISEMPTY(sigRec) %% FcnCall
      %return NumSFcnSysOutputCalls
    %else
      %return LibGetRecordSymbolicWidth(sigRec)
    %endif
  %endif
%endfunction %% LibBlockOutputSignalSymbolicWidth
 
%%DocFunction{OutputSignalFunctions}:LibBlockOutputHasSymbolicWidth========
%%Abstract:
%%Returnstrueifthespecifiedblockinputportindexhassymbolic
%%dimensions.
%%
%function LibBlockOutputHasSymbolicWidth(portIdx) void
  %assign ip = FcnGetOutputPortRecord(portIdx)
  %return LibRecordHasSymbolicWidth(ip)
%endfunction %% LibBlockOutputHasSymbolicWidth
 
 
%%DocFunction{OutputSignalFunctions}:LibBlockOutputSignalDimensions========
%%Abstract:
%%Returnsthedimensionsofspecifiedblockoutputport.
%%
%function LibBlockOutputSignalDimensions(portIdx) void
  %% See Also:
  %% LibBlockInputSignalDimensions
  %%
  %assign op = FcnGetOutputPortRecord(portIdx)
  %assign dims = LibGetRecordDimensions(op)
  %if dims[0] != -1
    %return dims
  %else
    %return LibBlockOutputSignalWidth(portIdx)
  %endif
%endfunction %% LibBlockOutputSignalDimensions
 
 
%%DocFunction{OutputSignalFunctions}:LibBlockOutputSignalSymbolicDimensions
%%Abstract:
%%Returnsthesymbolicdimensionsofspecifiedblockoutputport.
%%
%function LibBlockOutputSignalSymbolicDimensions(portIdx) void
  %% See Also:
  %% LibBlockInputSignalSymbolicDimensions
  %%
  %assign op = FcnGetOutputPortRecord(portIdx)
  %if LibGetRecordIsMatrix(op)
    %return LibGetRecordSymbolicDimensions(op)
  %else
    %return LibGetRecordSymbolicWidth(op)
  %endif
%endfunction %% LibBlockOutputSignalSymbolicDimensions
 
 
%%DocFunction{OutputSignalFunctions}:LibBlockOutputSignalNumDimensions=====
%%Abstract:
%%Returnsthenumberofdimensionsofthespecifiedblockoutputport.
%%
%function LibBlockOutputSignalNumDimensions(portIdx) void
  %% See Also:
  %% LibBlockInputSignalNumDimensions
  %%
  %assign op = FcnGetOutputPortRecord(portIdx)
  %assign dims = LibGetRecordDimensions(op)
  %if dims[0] != -1
    %return SIZE(dims,1)
  %else
    %return 1
  %endif
%endfunction %% LibBlockOutputSignalNumDimensions
 
 
%%DocFunction{OutputSignalFunctions}:LibBlockOutputSignalIsComplex=========
%%Abstract:
%%Returns1ifthespecifiedblockoutputportiscomplex,0otherwise.
%%
%function LibBlockOutputSignalIsComplex(portIdx) void
  %% See Also:
  %% LibBlockInputSignalIsComplex, LibBlockParameterIsComplex
  %%
  %assign op = FcnGetOutputPortRecord(portIdx)
  %return LibGetRecordIsComplex(op)
%endfunction %% LibBlockOutputSignalIsComplex
 
%%DocFunction{OutputSignalFunctions}:LibBlockOutputSignalDataTypeId========
%%Abstract:
%%ReturnsthenumericIDcorrespondingtothedatatypeofthespecified
%%blockoutputport.
%%
%%Iftheoutputportsignaliscomplex,thisfunctionreturnsthedatatype
%%ofthereal(ortheimaginary)partofthesignal.
%%
%function LibBlockOutputSignalDataTypeId(portIdx) void
  %% See Also:
  %% LibBlockOutputSignalDataTypeName, LibBlockInputSignalDataTypeId,
  %% LibBlockParameterDataTypeId
  %%
  %assign op = FcnGetOutputPortRecord(portIdx)
  %if (IDNUM(op.SignalSrc[0])[0] == "F") %% FcnCall
    %return tSS_INVALID_DATA_TYPE_ID
  %elseif Type == "S-Function" && !ParamSettings.AliasDataTypeCompliant
    %return LibGetDataTypeIdAliasedThruToFromId(LibGetRecordDataTypeId(op))
  %else
    %return LibGetRecordDataTypeId(op)
  %endif
%endfunction %% LibBlockOutputSignalDataTypeId
 
 
%%DocFunction{OutputSignalFunctions}:LibBlockOutputSignalDataTypeName======
%%Abstract:
%%Returnsthetypenamestring(e.g.int_T,...creal_T)ofthedatatype
%%correspondingtothespecifiedblockoutputport.
%%
%%Specifythereimargumentas""ifyouwantthecompletesignaltypename.
%%Forexampleifreim==""andthefirstoutputportisrealandcomplex,
%%thedatatypenameplacedindtnamewillbecreal_T:
%%%assigndtname=LibBlockOutputSignalDataTypeName(0x,"")
%%
%%SpecifythereimargumentastRealPartifyouwanttherawelementtype
%%name.Forexampleifreim==tRealPartandthefirstoutputportisreal
%%andcomplex,thedatatypenamereturnedwillbereal_T.
%%%assigndtname=LibBlockOutputSignalDataTypeName(0,tRealPart)
%%
%function LibBlockOutputSignalDataTypeName(portIdx, reim) void
  %% See Also:
  %% LibBlockOutputSignalDataTypeId, LibBlockInputSignalDataTypeName,
  %% LibBlockParameterDataTypeName
  %%
  %if Type == "S-Function" && !ParamSettings.AliasDataTypeCompliant
    %return LibBlockOutputSignalAliasedThruDataTypeName(portIdx, reim)
  %else
    %assign op = FcnGetOutputPortRecord(portIdx)
    %if (IDNUM(op.SignalSrc[0])[0] == "F") %% FcnCall
      %return ""
    %else
      %return SLibGetRecordDataTypeName(op, reim)
    %endif
  %endif
%endfunction %% LibBlockOutputSignalDataTypeName
 
%%DocFunction{OutputSignalFunctions}:LibBlockOutputSignalAliasedThruDataTypeName======
%%Abstract:
%%Returnsthetypenamestring(e.g.int_T,...creal_T)ofthealiased
%%datatypecorrespondingtothespecifiedblockoutputport.
%%
%%Specifythereimargumentas""ifyouwantthecompletesignaltypename.
%%Forexampleifreim==""andthefirstoutputportisrealandcomplex,
%%thedatatypenameplacedindtnamewillbecreal_T:
%%%assigndtname=LibBlockOutputSignalDataTypeName(0x,"")
%%
%%SpecifythereimargumentastRealPartifyouwanttherawelementtype
%%name.Forexampleifreim==tRealPartandthefirstoutputportisreal
%%andcomplex,thedatatypenamereturnedwillbereal_T.
%%%assigndtname=LibBlockOutputSignalDataTypeName(0,tRealPart)
%%
%function LibBlockOutputSignalAliasedThruDataTypeName(portIdx, reim) void
  %% See Also:
  %% LibBlockOutputSignalDataTypeId, LibBlockInputSignalDataTypeName,
  %% LibBlockParameterDataTypeName
  %%
  %assign op = FcnGetOutputPortRecord(portIdx)
  %if (IDNUM(op.SignalSrc[0])[0] == "F") %% FcnCall
    %return ""
  %else
    %return LibGetRecordAliasedThruDataTypeName(op, reim)
  %endif
%endfunction %% LibBlockOutputSignalAliasedThruDataTypeName
 
%%DocFunction{OutputSignalFunctions}:LibBlockOutputSignalUnitId========
%%Abstract:
%%ReturnsthenumericIDcorrespondingtotheunitsofthespecified
%%blockoutputport.
%%
%function LibBlockOutputSignalUnitId(portIdx) void
  %% See Also:
  %% LibBlockOutputSignalUnitExpr, LibBlockInputSignalUnitId,
  %% LibBlockParameterUnitId
  %%
  %assign op = FcnGetOutputPortRecord(portIdx)
  %if (IDNUM(op.SignalSrc[0])[0] == "F") %% FcnCall
    %return 0
  %else
    %return LibGetRecordUnitId(op)
  %endif
%endfunction %% LibBlockOutputSignalUnitId
 
 
%%DocFunction{OutputSignalFunctions}:LibBlockOutputSignalUnitExpr======
%%Abstract:
%%Returnsthetypenamestringoftheunits
%%correspondingtothespecifiedblockoutputport.
%%
%function LibBlockOutputSignalUnitExpr(portIdx) void
  %% See Also:
  %% LibBlockOutputSignalUnitId, LibBlockInputSignalUnitExpr,
  %% LibBlockParameterUnitExpr
  %%
  %assign op = FcnGetOutputPortRecord(portIdx)
  %if (IDNUM(op.SignalSrc[0])[0] == "F") %% FcnCall
    %return ""
  %else
    %return SLibGetRecordUnitExpr(op)
  %endif
%endfunction %% LibBlockOutputSignalUnitExpr
 
%%DocFunction{OutputSignalFunctions}:LibBlockOutputPortIsContinuousQuantity========
%%Abstract:
%%Returnswhethertheoutputportrepresentsaco-simsignal.
%%
%function LibBlockOutputPortIsContinuousQuantity(portIdx) void
  %assign ip = FcnGetOutputPortRecord(portIdx)
  %if EXISTS("ip.IsContinuousQuantity")
    %if ip.IsContinuousQuantity == "yes"
      %return TLC_TRUE
    %endif
  %endif
  %return TLC_FALSE
%endfunction %%LibBlockOutputPortIsContinuousQuantity
 
 
%%Function:LibBlockAllOutputSignalsAreExpr=================================
%%Abstract:
%%Returns1(true)ifalloutputsignalsareexpressions,and0(false)
%%otherwise.
%%
%function LibBlockAllOutputSignalsAreExpr() void
  %if Type == "Opaque"
    %return 0
  %elseif NumDataOutputPorts >= 1
    %foreach opIdx = NumDataOutputPorts
      %if !LibBlockOutputSignalIsExpr(opIdx)
        %return 0
      %endif
    %endforeach
    %return 1
  %else
    %return 0
  %endif
%endfunction
 
%%DocFunction{OutputSignalFunctions}:LibBlockSomeOutputSignalIsExpr=======
%%Abstract:
%%Returns1(true)ifsomeoutputsignalisanexpressions,and0(false)
%%otherwise.
%%
%function LibBlockSomeOutputSignalIsExpr() void
  %foreach opIdx = NumDataOutputPorts
    %if LibBlockOutputSignalIsExpr(opIdx)
      %return 1
    %endif
  %endforeach
  %return 0
%endfunction
 
 
%%DocFunction{OutputSignalFunctions}:LibBlockOutputSignalSampleTime========
%%Abstract:
%%Returnsthesampletimecorrespondingtothespecifiedblockoutput
%%port.
%%
%function LibBlockOutputSignalSampleTime(portIdx) void
  %% See Also:
  %% LibBlockOutputSignalSampleTime, LibBlockOutputSignalSampleTimeIndex,
  %% LibBlockInputSignalOffsetTime
  %%
 
  %if EXISTS("OutputPortSampleTimes")
    %assign idx = OutputPortSampleTimes[portIdx]
  %else
    %%START_ASSERT
    %assign errTxt = "SampleTime is not contained within the specified record"
    %<LibBlockReportError([],errTxt)>
    %%END_ASSERT
  %endif
  %return idx
%endfunction %% LibBlockOutputSignalSampleTime
 
 
%%DocFunction{OutputSignalFunctions}:LibBlockOutputSignalOffsetTime========
%%Abstract:
%%Returnstheoffsettimecorrespondingtothespecifiedblockoutput
%%port.
%%
%function LibBlockOutputSignalOffsetTime(portIdx) void
  %% See Also:
  %% LibBlockOutputSignalOffsetTime, LibBlockOutputSignalSampleTimeIndex,
  %% LibBlockInputSignalSampleTime
  %%
 
  %if EXISTS("OutputPortOffsetTimes")
    %assign idx = OutputPortOffsetTimes[portIdx]
  %else
    %%START_ASSERT
    %assign errTxt = "OffsetTime is not contained within the specified record"
    %<LibBlockReportError([],errTxt)>
    %%END_ASSERT
  %endif
  %return idx
%endfunction %% LibBlockOutputSignalOffsetTime
 
 
%%DocFunction{OutputSignalFunctions}:LibBlockOutputSignalSampleTimeIndex===
%%Abstract:
%%Returnsthesampletimeindexcorrespondingtothespecifiedblockoutput
%%port.
%%
%function LibBlockOutputSignalSampleTimeIndex(portIdx) void
  %% See Also:
  %% LibBlockOutputSignalSampleTimeIndex, LibBlockOutputSignalSampleTime,
  %% LibBlockInputSignalOffsetTime
  %%
 
  %if EXISTS("OutputPortTIDs")
    %assign idx = OutputPortTIDs[portIdx]
  %else
    %%START_ASSERT
    %assign errTxt = "SampleTimeIndex is not contained within the specified record"
    %<LibBlockReportError([],errTxt)>
    %%END_ASSERT
  %endif
  %return idx
%endfunction %% LibBlockOutputSignalSampleTimeIndex
 
 
%%DocFunction{OutputSignalFunctions}:LibBlockOutputSignalLocalSampleTimeIndex
%%Abstract:
%%Returnsthelocalsampletimeindexcorrespondingtothespecifiedblock
%%outputport.
%%
%function LibBlockOutputSignalLocalSampleTimeIndex(portIdx) void
  %% See Also:
  %% LibBlockOutputSignalSampleTimeIndex, LibBlockOutputSignalSampleTime,
  %% LibBlockOutputSignalOffsetTime,
  %% LibBlockOutputSignalLocalSampleTimeIndex
  %%
  %if EXISTS("OutputPortLocalTIDs")
    %assign idx = OutputPortLocalTIDs[portIdx]
  %else
    %%START_ASSERT
    %assign errTxt = "LocalSampleTimeIndex is not contained within the specified record"
    %<LibBlockReportError([],errTxt)>
    %%END_ASSERT
  %endif
  %return idx
%endfunction %% LibBlockOutputSignalLocalSampleTimeIndex
 
 
%%DocFunction{OutputSignalFunctions}:LibBlockOutputSignalBeingMerged========
%%Abstract:
%%Returnswhetherthespecifiedoutputportisconnectedtoamerge
%%block
%%
%function LibBlockOutputSignalBeingMerged(portIdx) void
  %% See Also:
  %% LibBlockInputSignalConnected
  %%
  %if EXISTS("Connections.OutputPortBeingMerged")
    %assign connected = (Connections.OutputPortBeingMerged[portIdx] == "yes")
  %else
    %%START_ASSERT
    %assign errTxt = "OutputPortBeingMerged is not contained within the specified record"
    %<LibBlockReportError([],errTxt)>
    %%END_ASSERT
  %endif
  %return connected
%endfunction %% LibBlockOutputSignalBeingMerged
 
 
%%DocFunction{AdvancedFunctions}:LibBlockOutputSignalStorageClass===========
%%Abstract:
%%Returnsthestorageclassoftheblock'sspecifiedoutputsignal.
%%Thestorageclasscanbe"Auto","ExportedSignal","ImportedExtern",
%%"ImportedExternPointer","Custom".
%%
%function LibBlockOutputSignalStorageClass(portIdx) void
  %% See Also:
  %% LibBlockInputSignalStorageClass
  %%
  %assign op = FcnGetOutputPortRecord(portIdx)
  %assign mapSource = IDNUM(op.SignalSrc[0])[0]
  %if (mapSource == "F") %% FcnCall
    %return "FcnCall"
  %elseif (mapSource != "E" && mapSource != "y")
    %return "Auto"
  %else
    %assign sigRec = SLibGetSourceRecord(op, 0)
    %%
    %% In the case of mapSource == "y" (canonical output),
    %% the output port can also resolve to external storage classes.
    %% In this case the signal won't be stored in the BlockIO.
    %%
    %if SLibIsLegacyStorageClassForDataRecord(sigRec)
      %return "Custom"
    %elseif ISFIELD(sigRec, "StorageClass")
      %return sigRec.StorageClass
    %else
      %assert mapSource != "E"
      %return "Auto"
    %endif
  %endif
%endfunction %% LibBlockOutputSignalDataTypeName
 
 
%%DocFunction{AdvancedFunctions}:LibBlockOutputSignalStorageTypeQualifier===
%%Abstract:
%%Returnsthestoragetypequalifieroftheblock'sspecifiedoutput
%%signal.Thetypequalifiercanbeanythingenteredbytheusersuch
%%as"const".Thedefaulttypequalifieris"Auto"-meaningdothe
%%defaultaction.
%%
%function LibBlockOutputSignalStorageTypeQualifier(portIdx) void
  %% See Also:
  %% LibBlockInputSignalStorageTypeQualifier
  %%
  %assign op = FcnGetOutputPortRecord(portIdx)
  %assign mapSource = IDNUM(op.SignalSrc[0])[0]
  %if (mapSource == "F") %% FcnCall
    %return "FcnCall"
  %elseif (mapSource != "E" && mapSource != "y")
    %return ""
  %else
    %assign sigRec = SLibGetSourceRecord(op, 0)
    %%
    %% In the case of mapSource == "y" (canonical output),
    %% the output port can also resolve to external storage classes.
    %% In this case the signal won't be stored in the BlockIO.
    %%
    %if ISFIELD(sigRec, "StorageTypeQualifier")
      %return sigRec.StorageTypeQualifier
    %else
      %assert mapSource != "E"
      %return ""
    %endif
  %endif
%endfunction %% LibBlockOutputSignalStorageTypeQualifier
 
 
%%DocFunction{AdvancedFunctions}:LibBlockOutputSignalIsInBlockIO============
%%Abstract:
%%Returns1ifthespecifiedblockoutputportexistsintheglobalBlock
%%I/Odatastructure.Youmayneedtousethisifyouspecify
%%ssSetOutputPortReusable(S,portIdx,true)inyourS-function.
%%Seematlabroot/toolbox/simulink/blocks/tlc_c/sfun_multiport.tlc.
%%
%function LibBlockOutputSignalIsInBlockIO(portIdx) void
  %assign op = FcnGetOutputPortRecord(portIdx)
  %assign mapSource = IDNUM(op.SignalSrc[0])[0]
 
  %if mapSource != "b" && mapSource != "B" && mapSource != "y"
    %return 0
  %else
    %assign sigRec = SLibGetSourceRecord(op, 0)
    %if ISFIELD(sigRec, "RequiredInBlockIO")
      %return sigRec.RequiredInBlockIO[0]
    %else
      %%
      %% In the case of mapSource == "y" (canonical output),
      %% the output port can also resolve to external storage classes.
      %% In this case the signal won't be stored in the BlockIO.
      %%
      %return 0
    %endif
  %endif
%endfunction %% LibBlockOutputSignalIsInBlockIO
 
 
%%DocFunction{AdvancedFunctions}:LibBlockOutputSignalIsValidLValue==========
%%Abstract:
%%Returns1ifthespecifiedblockoutputportsignalcanbeusedavalid
%%lefthandsideargument(lvalue)inanassignmentexpression,otherwise
%%returns0.Forexample,thisfunctionreturns1iftheblockoutput
%%portsignalisinread/writememory.
%%
%function LibBlockOutputSignalIsValidLValue(portIdx) void
  %assign op = FcnGetOutputPortRecord(portIdx)
  %assign mapSource = IDNUM(op.SignalSrc[0])[0]
 
  %if (mapSource == "F") %% FcnCall
    %return 0
  %elseif (mapSource == "I")
    %assign sigRec = SLibGetSourceRecord(op, 0)
    %return (sigRec.DoNotConstify == 1)
  %else
    %return 1
  %endif
 
%endfunction %% LibBlockOutputSignalIsValidLValue
 
 
%%DocFunction{AdvancedFunctions}:LibBlockOutputSignalIsGlobal===============
%%Abstract:
%%Returns1ifthespecifiedblockoutputportsignalisdeclaredinthe
%%globalscope,otherwisereturns0.
%%
%%Ifthisfunctionreturns1,thenthevariableholdingthissignalis
%%accessiblefromanywhereingeneratedcode.Forexample,thisfunction
%%returns1forsignalsthataretestpoints,externalorinvariant.
%%
%function LibBlockOutputSignalIsGlobal(portIdx) void
  %assign op = FcnGetOutputPortRecord(portIdx)
  %assign mapSource = IDNUM(op.SignalSrc[0])[0]
 
  %if (mapSource == "L" || mapSource == "C" || mapSource == "F")
    %return 0
  %else
    %assign sigRec = SLibGetSourceRecord(op, 0)
    %return !SLibOmitRecord(sigRec)
  %endif
%endfunction %% LibBlockOutputSignalIsGlobal
 
%%SLibBlockSystemToCallForOutput==============================================
%%Abstract:
%%Returnstheconditionallyexecutedsystemtocallfortheinputport.
%%
%function SLibBlockSystemToCallForOutput(portIdx) void
  %% See Also:
  %%
  %assign ip = FcnGetOutputPortRecord(portIdx)
  %return ip.SystemToCall
%endfunction %% LibBlockSystemToCallForOutput
 
%function FcnCheckHasSrcSignalThing(thing, validThings, funcSuffix, typeOfThing) void
  %if ...
    thing != validThings[0] && ...
    thing != validThings[1] && ...
    thing != validThings[2]
 
    %<LibBlockReportError([],"Cannot use " ...
      "LibBlockSrcSignalLocation%<funcSuffix> with %<typeOfThing> "...
      "/"%<thing>/", only with %<typeOfThing>s %<validThings>")>
  %endif
%endfunction
 
%function FcnCheckHasSrcSignal(loc, funcSuffix) void
  %assign validTypes = ["EnablePort", "TriggerPort", "Inport"]
  %assign validLocs = ["enableblk", "triggerblk", "inportblk"]
 
  %<FcnCheckHasSrcSignalThing(loc, validLocs, funcSuffix, "location" )>
  %<FcnCheckHasSrcSignalThing(Type, validTypes, funcSuffix, "block type")>
%endfunction
 
%%Function:LibBlockSrcSignalLocation=========================================
%%Abstract:
%%Returnreferencetoasourcesignalinahigherlevelsubsystem.Only
%%supportedforenabport,inportandtrigportblocks.
%%
%%Allowstheenable,trigger,andinportblockstodeterminetheirinput
%%signalattributeseventhoughtheythemselveshavenoinputport.
%%Becausethereisaninputportattheparentsubsystemlevelassociated
%%withtheenable,triggerorinportblock,thisfunctiongoestothe
%%parentsubsystemtodeterminetheinputsignal.
%%
%%Specifylocasoneof"inportblk","enableblk","triggerblk".
%%
%%Seeenableblock(enabport.ttlc)orinportblock(inport.ttlc)
%%implementationsforusageexamples.
%%
%function LibBlockSrcSignalLocation(loc, ucv, lcv, sigIdx)
  %<FcnCheckHasSrcSignal(loc, "")>
  %return LibBlockInputSignal(loc, ucv, lcv, sigIdx)
%endfunction %% LibBlockSrcSignalLocation
 
 
%%Function:LibBlockSrcSignalLocationAddr=====================================
%%Abstract:
%%Determineaddressofasourcesignal.Onlysupportedforenabport,
%%inportandtrigportblocks.Returnsareferencetoasourcesignal
%%addressviathehigherlevelsubsystem.
%%
%%Specifylocasoneof{"inportblk","enableblk","triggerblk"}
%%
%%Allowstheenable,trigger,andinportblockstodeterminetheirinput
%%signalattributeseventhoughtheythemselveshavenoinputport.
%%Becausethereisaninputportattheparentsubsystemlevelassociated
%%withtheenable,triggerorinportblock,thisfunctiongoestothe
%%parentsubsystemtodeterminetheinputsignaladdress.
%%
%%Seerolllib.tlcforusageexamples.
%%
%function LibBlockSrcSignalLocationAddr(loc, ucv, lcv, sigIdx)
  %<FcnCheckHasSrcSignal(loc, "Addr")>
  %return LibBlockInputSignalAddr(loc, ucv, lcv, sigIdx)
%endfunction %% LibBlockSrcSignalLocationAddr
 
 
%%Function:LibBlockSrcSignalLocationStorageClass=============================
%%Abstract:
%%Determinestorageclassofasourcesignal.Onlysupportedforenabport,
%%inportandtrigportblocks.Returnsthestorageclassofsourcesignal
%%viathehigherlevelsubsystem.
%%
%%Specifylocasoneof{"inportblk","enableblk","triggerblk"}
%%
%%Allowstheenable,trigger,andinportblockstodeterminetheirinput
%%signalattributeseventhoughtheythemselveshavenoinputport.
%%Becausethereisaninputportattheparentsubsystemlevelassociated
%%withtheenable,triggerorinportblock,thisfunctiongoestothe
%%parentsubsystemtodeterminetheinputsignalstorageclass.
%%
%%Seerolllib.tlcforusageexamples.
%%
%function LibBlockSrcSignalLocationStorageClass(loc, sigIdx)
  %<FcnCheckHasSrcSignal(loc, "StorageClass")>
  %return LibBlockInputSignalStorageClass(loc, sigIdx)
%endfunction %% LibBlockSrcSignalLocationStorageClass
 
 
%%Function:LibBlockSrcSignalLocationStorageTypeQualifier=====================
%%Abstract:
%%Determinestoragetypequalifierofasourcesignal.Onlysupportedfor
%%enabport,inportandtrigportblocks.Returnsthestorageclassof
%%sourcesignalviathehigherlevelsubsystem.
%%
%%Specifylocasoneof{"inportblk","enableblk","triggerblk"}
%%
%%Allowstheenable,trigger,andinportblockstodeterminetheirinput
%%signalattributeseventhoughtheythemselveshavenoinputport.
%%Becausethereisaninputportattheparentsubsystemlevelassociated
%%withtheenable,triggerorinportblock,thisfunctiongoestothe
%%parentsubsystemtodeterminetheinputsignalstoragetypequalifier.
%%
%%Seerolllib.tlcforusageexamples.
%%
%function LibBlockSrcSignalLocationStorageTypeQualifier(loc, sigIdx)
  %<FcnCheckHasSrcSignal(loc, "StorageTypeQualifier")>
  %return LibBlockInputSignalStorageTypeQualifier(loc, sigIdx)
%endfunction %% LibBlockSrcSignalLocationStorageTypeQualifier
 
 
%%DocFunction{AdvancedFunctions}:LibBlockSrcSignalBlock=====================
%%Abstract:
%%Returnsareferencetotheblockthatissourceofthespecifiedblock
%%inputportelement.Thereturnargumentoneofthefollowing:
%%
%%[systemIdx,blockIdx]ifuniqueblockoutputorblockstate
%%"ExternalInput"ifexternalinput(rootinport)
%%"Ground"ifunconnectedorconnectedtoground
%%"FcnCall"iffunction-calloutput
%%0ifnotunique(i.e.sourcestoaMergeblock
%%orisareusedsignalduetoblockI/O
%%optimization)
%%Example:
%%Ifyouwanttofindtheblockthatdrivesthesecondinputon
%%thefirstportofthecurrentblock.Then,assign
%%theinputsignalofthissourceblocktothevariabley.The
%%followingcodefragmentdoesexactlythis:
%%
%%%assignsrcBlock=LibBlockSrcSignalBlock(0,1)
%%%%Makesurethatthesourceisablock
%%%ifTYPE(srcBlock)=="Vector"
%%%assignsys=srcBlock[0]
%%%assignblk=srcBlock[1]
%%%assignblock=::CompiledModel.System[sys].Block[blk]
%%%withblock
%%%assignu=LibBlockInputSignal(0,"","",0)
%%y=%<u>;
%%%endwith
%%%endif
%%
%function LibBlockSrcSignalBlock(portIdx, sigIdx) void
  %assign ip = FcnGetInputPortRecord(portIdx)
  %assign sigRec = SLibGetSourceRecord(ip, sigIdx)
 
  %if ISEMPTY(sigRec) %% ground
    %return "Ground"
  %else
    %if !ISFIELD(sigRec,"SigSrc") || ISEMPTY(sigRec.SigSrc)
      %return 0
    %else
      %return Vector(2) [%, %]
    %endif
  %endif
  %% Notice that the a input signal can't have "FcnCall" as a source
 
%endfunction %% LibBlockSrcSignalBlock
 
 
%%Function:SLibExternalOutputIsVirtual=======================================
%%Abstract:
%%Returntrueifrootoutportcorrespondingtoarootoutportblockcan
%%bevirtualized
%function SLibExternalOutputIsVirtual(opBlock)
  %with opBlock
    %assign vR = LibBlockParamSetting("Outport", "VirtualizableRoot")
  %endwith
  %return vR == "yes"
%endfunction %% SLibExternalOutputIsVirtualized
 
%%Function:SLibBlockSrcSignalIsGnd===========================================
%%Abstract:
%%Returntrueifspecifiedinputsignalsourceisground.Otherwise,return
%%false.
%%
%function SLibBlockSrcSignalIsGnd(portIdx, sigIdx) void
  %assign ip = FcnGetInputPortRecord(portIdx)
  %assign idNum = IDNUM(ip.SignalSrc[sigIdx])
  %return (idNum[0] == "G")
%endfunction
 
 
%%DocFunction{AdvancedFunctions}:LibBlockSrcSignalIsDiscrete================
%%Abstract:
%%Returns1ifthesourcesignalcorrespondingtothespecifiedblockinput
%%portelementisdiscrete,otherwisereturns0.
%%Notethatthisfunctionalsoreturns0ifthedrivingblockcannotbe
%%uniquelydeterminedifitisamergedorreusedsignal(i.e.thesource
%%isaMergeblockorthesignalhasbeenreusedduetooptimization).
%%
%function LibBlockSrcSignalIsDiscrete(portIdx, sigIdx) void
 
  %% See Also:
  %% LibBlockSrcSignalBlock
  %%
  %assign tmpVect = LibBlockSrcSignalBlock(portIdx, sigIdx)
  %if TYPE(tmpVect) == "Vector"
    %assign sysIdx = tmpVect[0]
    %assign blkIdx = tmpVect[1]
    %assign srcBlk = ::CompiledModel.System[sysIdx].Block[blkIdx]
    %return LibIsDiscrete(srcBlk.TID)
  %else
    %return 0
  %endif
 
%endfunction %% LibBlockSrcSignalIsDiscrete
 
 
%%DocFunction{AdvancedFunctions}:LibBlockSrcSignalIsGlobalAndModifiable=====
%%Abstract:
%%Thisfunctionreturns1ofthesourcesignalcorrespondingtothespecified
%%blockinputportelementsatisfiesthefollowingthreeconditions:
%%
%%a)Itisreadableeverywhereinthegeneratedcode
%%b)Itcanbereferencedbyitsaddress
%%c)Itsvaluecanchange(i.e.itisnotdeclaredasa"const")
%%
%%otherwise,thisfunctionreturns0
%%
%function LibBlockSrcSignalIsGlobalAndModifiable(portIdx, sigIdx) void
 
  %assign ip = FcnGetInputPortRecord(portIdx)
  %assign mapSource = IDNUM(ip.SignalSrc[sigIdx])[0]
   
  %if (mapSource == "b" || mapSource == "B" || mapSource == "E" || mapSource == "y")
    %assign sigRec = SLibGetSourceRecord(ip, sigIdx)
    %return !SLibOmitRecord(sigRec)
  %endif
  %return TLC_FALSE
 
%endfunction %% LibBlockSrcSignalIsGlobalAndModifiable
 
 
%%DocFunction{AdvancedFunctions}:LibBlockSrcSignalIsInvariant===============
%%Abstract:
%%Returns1ifthesourcesignalcorrespondingtothespecifiedblockinput
%%portelementisinvariant(i.e.thesignaldoesnotchange).
%%Forexample,asourceblockwithaconstantTID(orequivalently,an
%%infinitesample-time)wouldoutputaninvariantsignal.
%%
%function LibBlockSrcSignalIsInvariant(portIdx, sigIdx) void
 
  %assign ip = FcnGetInputPortRecord(portIdx)
  %assign mapSource = IDNUM(ip.SignalSrc[sigIdx])[0]
 
  %return (mapSource == "I" || mapSource == "C")
 
%endfunction %% LibBlockSrcSignalIsInvariant
 
 
%%Function:LibBlockDstSignalLocation=========================================
%%Abstract:
%%Usedbyoutportblocktodeterminethedestinationsignallocation
%%forthecorrespondingsubsystemblockoutputport.Inputargument,
%%locmustbe"outportblk".
%%
%%Thisfunctionreturns:
%%((%<dtype>*)ssGetOutputPortSignal(%<::tSimStruct>,%<outPortNum>))for
%%S-Functioncodeformats(writesdirectlytoS-functionoutputs)
%%rtYforallothercodeformats
%%rtY.-Externaloutputsvector(drivinganoutportblock)
%%
%function LibBlockDstSignalLocation(loc, ucv, lcv, sigIdx) void
 
  %% First split sigIdx into idx and reim
  %assign tmpVect = SLibGetReimAndIdx(sigIdx)
  %assign reim = tmpVect[0]
  %assign idx = tmpVect[1]
 
  %switch loc
    %case "outportblk"
 
      %% If the signal is not complex then the imaginary part is ""
      %if reim == tImagPart && !LibBlockInputSignalIsComplex(0)
        %return ""
      %endif
 
      %assign inputWidth = LibBlockInputSignalSymbolicWidth(0)
      %assign inputNumDims = LibGetRecordNumDimsFromContainerCgTypeIdx(FcnGetInputPortRecord(0))
      %assign sigIndexer = SLibGet1DArrayIndexer(inputWidth, ucv, lcv, idx)
 
      %if (ucv != "") || (lcv == "") || (lcv != "" && inputWidth == "1")
        %assign outPortNum = LibBlockParamSetting("Outport", "PortNumber") - 1
        %if CodeFormat == "S-Function"
          %assign dtype = LibBlockInputSignalDataTypeName(0, "")
          %assign ans = "((%<dtype> *)"...
            "%<RTMGetIdxed("OutputPortSignal",outPortNum)>)"
          %assign ans = ans + "[%<idx>]"
        %else
          %assign extOut = ExternalOutputs.ExternalOutput[outPortNum]
          %if(extOut.Identifier != "")
            %assign id = LibGetRecordIdentifier(extOut)
          %else
            %assign id = Identifier
          %endif
 
          %% If this External Output belongs to a coderDataGroup, then we
          %% need to ensure that we return the correct structure reference.
          %if(SLibDataRecordIsInCoderGroup(extOut))
            %assign structName = SLibGetCoderDataGroupStructForRecord(extOut)
          %else
            %assign structName = SLibGetExternalOutputStruct(TLC_TRUE,TLC_TRUE,TLC_FALSE)
          %endif
           
          %assign accessSymb = YQualifier
 
          %% If this External Output belongs to a coderDataGroup and if the code is
          %% generated for C++ and if the coderDataGroup is a pointer in the class,
          %% then return the structure reference name and set the access symbol to ->
          %if(SLibDataRecordIsInCoderGroup(extOut))
           %if( ISFIELD(extOut,"VarGroupIdx") )
             %assign varGroupIdx = extOut.VarGroupIdx[0]
             %assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
             %if (LibGetVarGroupCategory(varGroupIdx) == "HierarchicalCoderData" && (varGroup.PackageAsStruct != 0) && ...
               GenerateClassInterface && SLibAccessViaPointerInSelf(FcnGetCoderGroupForVarGroup(varGroup)))
               %assign structName = varGroup.StructureReferenceName
               %assign accessSymb = "->"
             %endif
           %endif
         %endif
           
          %% It's possible that we have an empty struct name, if the external
          %% output is in a coder group whose AsStructure property is None.
          %if ISEMPTY(structName)
            %assign ans = LibGetAddressOfFirstElement("%<id>", ...
                            inputNumDims) + "%<sigIndexer>"
          %else
            %assign ans = LibGetAddressOfFirstElement(...
                            "%<structName>%<accessSymb>%<id>", ...
                            inputNumDims) + "%<sigIndexer>"
          %endif
           
          %if MultiInstanceERTCode && ...
            !(RootIOStructures || SLibHasGlobalExternalOutputsWithFPC()) && ...
            inputWidth == "1"
            %assign ans = "(*%<ans>)"
          %endif
          %<SLibAccessArgHelper(extOut,"",TID)>
        %endif
      %else
        %% rolling
        %assign ans = LibGetAddressOfFirstElement("y0", inputNumDims) + ...
                      "%<sigIndexer>"
      %endif
 
      %if reim != "" && LibBlockInputSignalIsComplex(0)
        %assign ans = ans + ".%<reim>"
      %endif
 
      %return ans
    %default
      %%START_ASSERT
      %assign errTxt = "Invalid location '%<loc>' specified."
      %%END_ASSERT
      %<LibBlockReportError([],errTxt)>
  %endswitch %% loc
 
%endfunction %% LibBlockDstSignalLocation
 
%function LibGetIsInputPortVarDims(portIdx)
  %assign portObj = FcnGetInputPortRecord(portIdx)
  %return SLibGetArgIsVarDims(portObj)
%endfunction
 
%function LibGetIsOutputPortVarDims(portIdx)
  %assign portObj = FcnGetOutputPortRecord(portIdx)
  %return SLibGetArgIsVarDims(portObj)
%endfunction
 
%function FcnBlockHasVarDimsInput()
  %foreach ipIdx = NumDataInputPorts
    %if LibGetIsInputPortVarDims(ipIdx)
      %return TLC_TRUE
    %endif
  %endforeach
  %return TLC_FALSE
%endfunction
 
%function FcnBlockHasVarDimsOutput()
  %foreach opIdx = NumDataOutputPorts
    %if LibGetIsOutputPortVarDims(opIdx)
      %return TLC_TRUE
    %endif
  %endforeach
  %return TLC_FALSE
%endfunction
 
%function FcnBlockNumVarDimsInput()
  %assign num = 0
  %foreach ipIdx = NumDataInputPorts
    %if LibGetIsInputPortVarDims(ipIdx)
      %assign num = num + 1
    %endif
  %endforeach
  %return num
%endfunction
 
%function FcnBlockNumVarDimsOutput()
  %assign num = 0
  %foreach opIdx = NumDataOutputPorts
    %if LibGetIsOutputPortVarDims(opIdx)
      %assign num = num + 1
    %endif
  %endforeach
  %return num
%endfunction
 
%function SLibGetDims(kind, portIdx, dimIdx) void
  %return SLibInvokeTLCInterface(SLibGetCurrentBlock(), kind, portIdx, 0, ...
    TLC_FALSE, "", "%<dimIdx>", "", "")
%endfunction
 
%%thisistheS-fcnblockTLCinterfacetoaccess
%%blockoutputsize.
%%outputsizevariseither:
%%-acanonicalDWorkvar
%%-aDWorkvar(non-autoorauto).
%%
%%theblockoutputsizevarcannotbeinthe
%%ExternalOutputSizevargroup.
%function SLibGetCurrentOutputPortDimensions(portIdx, dimIdx) void
  %assign dworkVar = SLibGetDims("OutputDims", portIdx, dimIdx)
  %if !ISEMPTY(dworkVar)
    %return dworkVar
  %endif
  %assign portObj = FcnGetOutputPortRecord(portIdx)
  %assign the_hstruct = System[System[SystemIdx].HStructDeclSystemIdx]
  %assign dimStr = TYPE(dimIdx) == "Number" ? "%<dimIdx>" : dimIdx
  %if SLibGetArgUseCanDimSizeDW(portObj)
    %assign can_dwork_idx = SLibGetCanDimSizeDWIdxForArg(portObj)
    %assign dworkVar = LibGetRecordIdentifier(the_hstruct.Interface.CanonicalDWorkArgDef[can_dwork_idx])
    %<SLibAccessArgHelper(the_hstruct.Interface.CanonicalDWorkArgDef[can_dwork_idx],"",...
      System[SystemIdx].CurrentTID)>
    %assign dworkVar = "%<dworkVar>[%<dimStr>]"
  %else
    %assert SLibGetArgUseSharedDimSizeDW(portObj)
    %assign dworkRec = ::CompiledModel.DWorks.DWork[portObj.DimSizeDWork]
    %assign width = LibCGTypeWidth(LibGetRecordCGTypeIdx(dworkRec))
    %if dworkRec.StorageClass == "Auto"
      %assign dworkVar = SLibCG_DWV(portObj.DimSizeDWork, ...
        System[SystemIdx].CrossNoArgFcnBound, the_hstruct.SystemIdx, ...
        width, "", -1, dimStr, 0)
    %else
      %assign dworkVar = SLibCG_V(LibGetRecordIdentifier(dworkRec), TLC_FALSE, width, ...
        "", -1, dimStr, 0)
      %% pass TLC_FALSE to isPointer, since DWorks are generated as array.
    %endif
  %endif
  %return dworkVar
%endfunction %%SLibGetCurrentOutputPortDimensions
 
%function SLibSetCurrentOutputPortDimensions(portIdx, dimIdx, dimSize) Output
  %<SLibGetCurrentOutputPortDimensions(portIdx, dimIdx)> = %<dimSize>;
%endfunction %% SLibSetCurrentOutputPortDimensions
 
%%thisistheS-fcnblockTLCinterfacetoaccess
%%blockinputsize.
%%inputsizevariseither:
%%-acanonicalDWorkvar
%%-arootinportsizevar(canonlybeauto)
%%-aDWorkvar(non-autoorauto).
%%inputsizevarcouldbearootinportsizevar
%%IN->ELEMENT-WISEGAIN->TLC
%%inputsizevarisaDWORKvarif
%%IN->TRANSPOSE->TLC
%function SLibGetCurrentInputPortDimensions(portIdx, dimIdx) void
  %assign dworkVar = SLibGetDims("InputDims", portIdx, dimIdx)
  %if !ISEMPTY(dworkVar)
    %return dworkVar
  %endif
  %assign portObj = FcnGetInputPortRecord(portIdx)
  %assign the_hstruct = System[System[SystemIdx].HStructDeclSystemIdx]
  %assign dimStr = TYPE(dimIdx) == "Number" ? "%<dimIdx>" : dimIdx
  %if SLibGetArgUseCanDimSizeDW(portObj)
    %% the current input port's DimSize DWork is from a canonical input
    %assign can_dwork_idx = SLibGetCanDimSizeDWIdxForArg(DataInputPort[portIdx])
    %assign dworkVar = LibGetRecordIdentifier(the_hstruct.Interface.CanonicalDWorkArgDef[can_dwork_idx])
    %<SLibAccessArgHelper(the_hstruct.Interface.CanonicalDWorkArgDef[can_dwork_idx],"",...
      System[SystemIdx].CurrentTID)>
    %assign dworkVar = "%<dworkVar>[%<dimStr>]"
  %else
    %assert SLibGetArgUseSharedDimSizeDW(portObj)
    %assign dworkRec = ::CompiledModel.DWorks.DWork[portObj.DimSizeDWork]
 
    %if ISFIELD(dworkRec, "VarGroupIdx") && ...
      LibGetVarGroupCategory(dworkRec.VarGroupIdx[0]) == "ExternalInputSize"
      %if CodeFormat == "S-Function"
        %assign sigRecAndMapInfo = SLibGetSourceRecordAndMapInfo(...
          portObj, 0, TLC_TRUE, TLC_FALSE)
        %assign extIn = sigRecAndMapInfo.sigRec
        %assign sizeTypeIdx = SLibCGVarGroupMemberCGTypeIdx(...
          extIn.SizeVarGroupIdx[0], ...
          extIn.SizeVarGroupIdx[1])
        %assign sizeTypeWidth = LibCGTypeWidth(sizeTypeIdx)
        %return SLibGetInportSize(...
          sigRecAndMapInfo.mapIdx, sizeTypeWidth, "", -1, dimStr, 0)
      %else
        %assign width = LibCGTypeWidth(LibGetRecordCGTypeIdx(dworkRec))
        %assign varGroup = ::CompiledModel.VarGroups.VarGroup[dworkRec.VarGroupIdx[0]]
        %assign identifier = varGroup.Name + "." + LibGetRecordIdentifier(dworkRec)
        %return SLibCG_V(identifier, TLC_FALSE, width, ...
          "", -1, dimStr, 0)
      %endif
    %else
      %assign width = LibCGTypeWidth(LibGetRecordCGTypeIdx(dworkRec))
      %if dworkRec.StorageClass == "Auto"
        %assign dworkVar = SLibCG_DWV(portObj.DimSizeDWork, ...
          System[SystemIdx].CrossNoArgFcnBound, the_hstruct.SystemIdx, ...
          width, "", -1, dimStr, 0)
      %else
        %assign dworkVar = SLibCG_V(LibGetRecordIdentifier(dworkRec), TLC_FALSE, width, ...
          "", -1, dimStr, 0)
        %% pass TLC_FALSE to isPointer, since DWorks are generated as array.
      %endif
    %endif
  %endif
  %return dworkVar
%endfunction %%SLibGetCurrentInputPortDimensions
 
%%-----------------------------------------%
%%LocalFunctionsusedonlyinthisfile.%
%%-----------------------------------------%
 
 
%%Function:FcnGetInputPortRecord=============================================
%%Abstract:
%%Forthegiveninputportindex,returnareferencetothecorresponding
%%datainputportrecord(DataInputPort[i]).Theinportblocksare
%%handledbymappingbacktothecorrespondingsubsystemdatainputport
%%record.
%%
%function FcnGetInputPortRecord(portIdx) void
  %<LibGetInputPortRecordIsValid(portIdx)>
  %if portIdx >= 0 && portIdx < NumDataInputPorts
    %assign ip = DataInputPort[portIdx]
  %else
    %assign errTxt = "The specified port index '%<TYPE(portIdx)>' " ...
                 "should be a number between 0 and %."
    %<LibBlockReportError([],errTxt)>
  %endif
  %return ip
%endfunction %% FcnGetInputPortRecord
 
%%Function:FcnGetOutputPortRecord============================================
%%Abstract:
%%Forthegivenoutputportindex,returnareferencetothecorresponding
%%dataoutputportrecord(DataOutputPort[i]).
%%
%function FcnGetOutputPortRecord(portIdx) void
  %if portIdx >= 0 && portIdx < NumDataOutputPorts
    %assign op = DataOutputPort[portIdx]
  %else
    %assign errTxt = "The specified port index '%<TYPE(portIdx)>' " ...
      "of %<Name> should be a number between 0 and %."
      %<LibBlockReportError([],errTxt)>
  %endif
 
  %return op
 
%endfunction %% FcnGetOutputPortRecord
 
 
%%Function:SLibGetMapSrcAndMapIdx============================================
%%Abstract:
%%Return[%<src>,%<srcidx>]forthespecifiedportand
%%signalOffset
%%
%function SLibGetMapSrcAndMapIdx(port, sigIdx)
    %if SIZE(port.SignalSrc, 1) > 1
      %assign idNum = IDNUM(port.SignalSrc[sigIdx])
    %else
      %assign idNum = IDNUM(port.SignalSrc[0])
    %endif
    %return idNum
%endfunction %% SLibGetMapSrcAndMapIdx()
 
 
%%Function:FcnGetMapSrcAndMapIdx=============================================
%%Abstract:
%%Return[%<src>,%<srcidx>]forthespecifiedinputportsignalindex
%%(sigIdx).
%%
%function FcnGetMapSrcAndMapIdx(portIdx, sigIdx) void
  %assign ip = FcnGetInputPortRecord(portIdx)
 
  %% find map ID, and scalar expanded if necessary
  %return SLibGetMapSrcAndMapIdx(ip, sigIdx)
 
%endfunction %% FcnGetMapSrcAndMapIdx
 
%%Function:FcnReportNonAddressableError======================================
%%Abstract:
%%Reportanattempttotaketheaddressofnonaddressabledata
%%
%function FcnReportNonAddressableError(bInput, sigRec) void
  %assign block = SLibGetCurrentBlock()
  %<SLibReportNonAddressableError(bInput ? "Input" : "Output", block, sigRec)>
%endfunction %% FcnReportNonAddressableError
 
%%Function:FcnAddrHandling=============================================
%%Abstract:
%%Processforproperaddressing/dereferencing
%%
%function FcnAddrHandling(bAddr, returnBaseAddr, identi, identiIsPointer, sigSrcWidth, ...
  busSelElIdx, sigIndexer, rm)
  %assign retVal = ""
  %if bAddr
    %if returnBaseAddr
      %if identiIsPointer
        %if (sigSrcWidth > 1) || (!ISEMPTY(busSelElIdx))
          %assign retVal = "(*(" + identi + "))" + busSelElIdx
        %else
          %assign retVal = identi
        %endif
      %else
        %if (sigSrcWidth > 1)
          %assign retVal = identi + busSelElIdx
        %else
          %assign retVal = "&" + identi + busSelElIdx
        %endif
      %endif
    %else
      %if identiIsPointer
        %assign retVal = "&(*" + identi + ")" + busSelElIdx + sigIndexer
      %else
        %assign retVal = "&" + identi + busSelElIdx + sigIndexer
      %endif
    %endif
  %else
    %if identiIsPointer
      %assign retVal = "(*" + identi + ")" + busSelElIdx + sigIndexer + rm
    %else
      %assign retVal = identi + busSelElIdx + sigIndexer + rm
    %endif
  %endif
  %return retVal
%endfunction
 
%%Function:FcnGetArrayElementSignalReference=================================
%%Abstract:
%%Constructacallsitestringforanaccessfunctionthatisaccessingadata
%%elementbyanindex.
%%
%function FcnGetArrayElementSignalReference(fcn, sigIdx)
  %assign numChars = SIZE(sigIdx, 1)
  %assign isPureIdx = TLC_TRUE
  %foreach charIdx = numChars
    %if (sigIdx[charIdx] == "]") && (charIdx < numChars - 2)
      %assign isPureIdx = TLC_FALSE
      %break
    %endif
  %endforeach
  %if isPureIdx
    %assign retVal = fcn + "("
    %foreach charIdx = numChars-2
      %assign retVal = retVal + sigIdx[charIdx + 1]
    %endforeach
    %assign retVal = retVal + ")"
    %return retVal
  %else
    %return FcnGetBusArraySignalReference(fcn, sigIdx)
  %endif
%endfunction
 
%%Function:FcnGetBusArraySignalReference======================================
%%Abstract:
%%Constructacallsitestringthatisaccessingastructfieldfromastruct
%%oranelementofastructarrayreturnedbyanaccessfunction.
%%
%function FcnGetBusArraySignalReference(fcn, sigIdx)
  %assert((sigIdx[0] == ".") || (sigIdx[0] == "[")) %% .b.c (OR) [3].b[2].c
  %if (sigIdx[0] == ".") %% .b.c
    %return "(%<fcn>())%<sigIdx>"
  %else %% [3].b[2].c
    %assign retref = "(%<fcn>"
    %assign numChars = SIZE(sigIdx,1)
    %assign endBracketReplaced = 0
    %foreach elIdx = numChars
      %if (elIdx == 0)
        %assign retref = retref + "("
      %elseif ((sigIdx[elIdx] == "]") && (endBracketReplaced == 0))
        %assign retref = retref + "))"
        %assign endBracketReplaced = 1
      %else
        %assign retref = retref + sigIdx[elIdx]
      %endif
    %endforeach
    %return retref
  %endif
%endfunction
 
%function FcnGetAccessFunctionSignalReference(sigRec, addr, sigIdx) void
  %assert sigRec.UseAccessFunctions
  %assign mode = sigRec.AccessMode
  %if addr
    %if mode == "Reference"
      %assign fcn = sigRec.GetAccessFunction
      %return fcn + "()"
    %else
      %assign err = "Unable to take address of access method"
      %<LibReportFatalError(err)>
    %endif
  %else
    %if mode == "Reference"
      %assign fcn = sigRec.GetAccessFunction
      %if ISEMPTY(sigIdx)
        %return "(*(" + fcn + "()))"
      %else
        %return fcn + "()" + sigIdx
      %endif
    %else
      %assert mode == "Value"
      %assign fcn = sigRec.GetElementAccessFunction
      %if ISEMPTY(sigIdx)
        %return fcn + "()"
      %else
        %return FcnGetArrayElementSignalReference(fcn, sigIdx)
      %endif
    %endif
  %endif
%endfunction
 
%function FcnSetAccessFunctionSignalReference(sigRec, sigIdx, rhs) void
  %assert sigRec.UseAccessFunctions
  %assign mode = sigRec.AccessMode
  %if mode == "Reference"
    %assign fcn = sigRec.SetAccessFunction
    %if ISEMPTY(sigIdx)
      %return "(*(" + fcn + "())) = " + rhs + ";"
    %else
      %return fcn + "()" + sigIdx + " = " + rhs + ";"
    %endif
  %else
    %assert mode == "Value"
    %assign fcn = sigRec.SetElementAccessFunction
    %if ISEMPTY(sigIdx)
      %return fcn + "(" + rhs + ");"
    %else
      %assign debracedIdx = ""
      %foreach sIdx = SIZE(sigIdx,1) - 2
        %assign debracedIdx = debracedIdx + sigIdx[sIdx+1]
      %endforeach
      %return fcn + "(" + debracedIdx + ", " + rhs + ");"
    %endif
  %endif
%endfunction
 
%%Function:FcnCheckForNonAddressableError
%%Abstract:
%%
%%Thisfunctionchecksasignalrecordtoseeifweneedtothrowanon-
%%addressableerror
%function FcnCheckForNonAddressableError(aInput, aAddr, aSigRec, aStorageClass) void
  %% If we're taking the address, and:
  %% 1. It's an access function not using reference mode, OR
  %% 2. It's a non addressable storage class, then error
  %if (aAddr && ...
      ((ISFIELD(aSigRec, "UseAccessFunctions") && aSigRec.UseAccessFunctions && aSigRec.AccessMode != "Reference") || ...
       (aStorageClass == "Custom" && !LibCustomDataIsAddressable(aSigRec))))
      %<FcnReportNonAddressableError(aInput, aSigRec)>
  %endif
%endfunction
 
%%Function:FcnGetBasicSignalReference========================================
%%Abstract:
%%
%%Thisisthe'guts'ofFcnGetInputOrOutputSignalwhenwearenot
%%trulyrollinginCandisalwaysthebodyforAda.Itspurpose
%%istoprovideavalidsignalreferenceforthespecifiedmapSource
%%(e.g.blockI/O:"B")andmapIndex(e.g.25thlogicalelementinthe
%%blockI/Ovector).
%%
%function FcnGetBasicSignalReference(sigRecAndMapInfo, portWidth, reim, ...
                                     bInput, bAddr, isComplex, isStdContainer, ucv, lcv, cross) void
 
  %assign sigRec = sigRecAndMapInfo.sigRec
  %assign mapSource = sigRecAndMapInfo.mapSrc
  %assign mapIdx = sigRecAndMapInfo.mapIdx
  %assign sigSrcWidth = LibGetRecordWidth(sigRec)
  %assign sigOffset = sigRecAndMapInfo.signalOffset
  %assign busSelElIdx = sigRecAndMapInfo.busSelElIdx
  %assign busSelElCGTypeId = sigRecAndMapInfo.busSelElCGTypeId
 
  %if (!ISEMPTY(busSelElIdx) && busSelElCGTypeId != -1)
    %assign sigSrcWidth = LibCGTypeWidth(busSelElCGTypeId)
  %endif
  %if sigRecAndMapInfo.symbolicSignalOffset > -1
    %assign symbolicOffset = "(" + ...
      LibCGTypeSymbolicWidth(sigRecAndMapInfo.symbolicSignalOffset) + ")"
    %assign sigOffset = 0
    %if WHITE_SPACE(ucv)
      %assign ucv = symbolicOffset
    %else
      %assign ucv = ucv + "+" + symbolicOffset
    %endif
  %endif
 
  %%
  %assign returnBaseAddr = (sigOffset == 0 && ucv == "" && lcv == "" && bAddr && portWidth > 1 && sigSrcWidth == portWidth) && !isStdContainer
  %%
  %%-------------------------------------------------------------%
  %% Returning a reference to a block I/O, input or state signal %
  %%-------------------------------------------------------------%
 
  %%
  %% Locate the the block record that is driving (input
  %% signal source) or generates (output signal) this signal.
  %%
  %% Notes:
  %% 1) For input signal sources, the blkOut connection may
  %% be have a non-zero offset (sigOffset). This occurs in
  %% cases like:
  %%
  %% .-----------. .---------. .-------.
  %% | sin(1:10) |-------->| Sel 3:6 |----->| block |
  %% `-----------' `---------' `-------'
  %%
  %% In this example, the blkIOSlotWidth is 10 and the input port
  %% width to the block is 4 with an offset of 3.
  %%
  %% 2) For output signals, we can have a non-zero offset
  %% due to merge blocks.
  %%
  %%
  %% Generate the signal indexer (sigIndexer)
  %%
 
  %if bInput && sigSrcWidth > 1 && portWidth == 1
    %%
    %% This occurs in cases like:
    %%
    %% .-------.
    %% .----------. | |
    %% | sin(1:2) |------>| demux | .-------.
    %% `----------' | |---------->| block |
    %% `-------' `-------'
    %%
    %% The input width to block is 1, yet the sigSrcWidth it is
    %% connected to is > 1. In this case we need to return a
    %% index of the form rtB.sigout[1].
    %%
    %assign sigIndexer = SLibGet1DArrayIndexer(sigSrcWidth, ...
      "", "", sigOffset)
    %assign lcv = ""
  %else
    %%if returnBaseAddr
    %%assign sigIndexer = ""
    %%else
    %assign sigIndexer = SLibGet1DArrayIndexer(sigSrcWidth, ...
      ucv, lcv, sigOffset)
    %%endif
  %endif
 
  %%--------------------------------------------------%
  %% Special handling for the different record types %
  %%--------------------------------------------------%
 
  %if mapSource != "Y"
    %assign storageClass = sigRec.StorageClass
  %else
    %assign storageClass = "Auto"
  %endif
 
  %if SLibIsLegacyStorageClassForDataRecord(sigRec)
    %assign storageClass = "Custom"
  %endif
 
  %if reim != "" && isComplex
    %assign rm = ".%<reim>"
  %else
    %assign rm = ""
  %endif
 
  %if !ISEMPTY(sigRecAndMapInfo.identi)
    %assign tempVal = FcnAddrHandling(bAddr, returnBaseAddr, sigRecAndMapInfo.identi, ...
      sigRecAndMapInfo.isPointer, sigSrcWidth, busSelElIdx, sigIndexer, rm)
    %if !ISEMPTY(tempVal)
      %return tempVal
    %endif
  %endif
 
  %assign scalarInputPassedByAddr = TLC_FALSE
  %assign scalarOutputPassedByAddr = TLC_FALSE
 
  %switch (mapSource)
    %case "C"
      %%
      %% An example of this is:
      %%
      %% .--------------. .-------.
      %% | constant 1:5 |------>| block |
      %% `--------------' `-------'
      %%
      %assign sysRef = System[sigRec.SigSrc[0]]
      %assign blkRef = sysRef.Block[sigRec.SigSrc[2]]
      %assign oPort = sigRec.SigSrc[3]
 
      %if !bInput
        %% constExpr is turned off when connected to a merge
        %% block. Therefore, there is no concept of an offset for
        %% a constExpr output signal
        %assign sigOffset = 0
      %endif
 
      %% Update expression comment
      %if GeneratingOutputsCode
        %<FcnAddToExprCommentList(blkRef, oPort)>
 
        %assign blkRef.ExprCommentSrcIdx.SysIdx = -1
        %assign blkRef.ExprCommentSrcIdx.BlkIdx = -1
      %endif
 
      %if !ISEMPTY(busSelElIdx)
        %% Update sigIndexer
        %assign sigIndexer = SLibGet1DArrayIndexer(sigSrcWidth, ...
          ucv, lcv, sigOffset)
        %% Ignore ucv, lcv, sigIdx as these are included in sigIndexer
        %assign retSignal = SLibBlockOutputSignal(...
          blkRef,sysRef,oPort,"","","", bAddr ? "SignalAddr" : "Signal")
 
        %% Is constant expression a pointer?
        %% We cannot use bAddr or sigRecAndMapInfo.isPointer to infer this
        %assign identiIsPointer = TLC_FALSE
        %assign len = SIZE(retSignal,1)
        %foreach idx = len
          %if retSignal[idx] == "&"
            %assign identiIsPointer = TLC_TRUE
            %break
          %endif
        %endforeach
 
        %assign retSignal = FcnAddrHandling(bAddr, returnBaseAddr, retSignal, ...
          identiIsPointer, sigSrcWidth, busSelElIdx, sigIndexer, rm)
      %else
        %assign sigIdx = "%<reim>%<sigOffset>"
        %if sigOffset != 0
          %if ucv != ""
            %assign ucv = "%<ucv>+%<sigOffset>"
            %assign sigIdx = "%<reim>0"
          %elseif lcv != ""
            %assign lcv = "%<lcv>+%<sigOffset>"
            %assign sigIdx = "%<reim>0"
          %endif
        %endif
        %assign retSignal = SLibBlockOutputSignal(blkRef,sysRef,oPort,...
          ucv,lcv,sigIdx, bAddr ? "SignalAddr" : "Signal")
      %endif
 
      %%--------------%%
      %% early return %%
      %%--------------%%
      %return retSignal
 
    %case "E"
      %% external signal
 
      %if storageClass == "Custom"
        %<FcnCheckForNonAddressableError(bInput, bAddr, sigRec, storageClass)>
        %return LibCustomData(sigRec, bAddr ? "address" : "contents", ...
          busSelElIdx + sigIndexer, reim)
      %else
        %assign retSignalWithoutIndexer = LibGetRecordIdentifier(sigRec)
      %endif
 
      %if reim != "" && isComplex
        %% The real or imaginary part of a complex signal is
        %% requested. For now, disallow imported complex block
        %% signals since we don't know how to dereference them.
        %if storageClass == "ImportedExtern" || ...
          storageClass == "ImportedExternPointer"
          %assign errTxt = ...
            "Imported complex signals not supported: " + ...
            retSignalWithoutIndexer
          %<LibBlockReportError([],errTxt)>
        %endif
      %endif
 
      %assign retSignal = retSignalWithoutIndexer + busSelElIdx + sigIndexer
 
      %%
      %% Finally, if we got here, decorate the return signal as needed
      %%
      %if reim != "" && isComplex
        %assign retSignal = retSignal + ".%<reim>"
      %endif
 
      %break
 
    %case "I" %% This is an invariant signal, get its identifier.
 
      %if !sigRec.RequiredInConstBlockIO && !GeneratingDeadCode
        %assign sigRec.RequiredInConstBlockIO = 1
        %assign blkOutsRec = ::CompiledModel.BlockOutputs
        %assign blkOutsRec.NumSignalsInConstBlockIO = ...
          blkOutsRec.NumSignalsInConstBlockIO + 1
      %endif
      %%
      %% Constant block IO structure handling
      %%
      %%
      %% see the comment in SLibGetSourceRecordAndMapInfo
      %% for more information on this. Basically, a block inside
      %% a nonreusable function is reading from the const blockIO
      %% of it's reusable parent.
      %assign accessSysIdx = SLibGetHStructWithLocalScopeSystemIdx(SystemIdx)
      %assign varGroupIdx = sigRec.VarGroupIdx[0]
      %assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
      %assign sysIdx = varGroup.SysIdx
      %assign instanceIdx = varGroup.InstanceIdx
      %assign retSignalWithoutIndexer = ...
        SLibCG_GetVarGroupElementPath(sigRec.VarGroupIdx, accessSysIdx, ...
        CrossNoArgFcnBound)
 
      %assign retSignal = retSignalWithoutIndexer + busSelElIdx + sigIndexer
 
      %%
      %% Finally, if we got here, decorate the return signal as needed
      %%
      %if reim != "" && isComplex
        %assign retSignal = retSignal + ".%<reim>"
      %endif
 
      %break
 
    %case "D" %% Discrete State
      %assign signalName = LibGetDWorkStruct() + DWorkQualifier + LibGetRecordIdentifier(sigRec)
      %assign retSignal = signalName + busSelElIdx + sigIndexer
      %break
 
    %case "X" %% Continuous State
      %assign signalName = LibGetContinuousStateStruct() + XQualifier + sigRec.Identifier
      %assign retSignal = signalName + busSelElIdx + sigIndexer
      %break
 
    %case "U"
      %%--------------------------------------------%
      %% Returning a reference to an external input %
      %%--------------------------------------------%
 
      %% Update expression comment
      %if GeneratingOutputsCode
        %if Type != "Opaque"
          %assign commSysIdx = ExprCommentSrcIdx.SysIdx
          %assign commBlkIdx = ExprCommentSrcIdx.BlkIdx
          %if commSysIdx != -1 && commBlkIdx != -1
            %assign commInfo = System[commSysIdx].Block[commBlkIdx].ExprCommentInfo
          %else
            %assign commInfo = ExprCommentInfo
          %endif
        %else
          %assign commInfo = ExprCommentInfo
        %endif
        %<SLibAddToExprCommentList(commInfo,sigRec,0)>
      %endif
 
      %if storageClass != "Auto"
        %% external signal
        %%
        %% S-functions do not support external i/o
        %%
        %if CodeFormat == "S-Function"
          %assign args = [%<LibGetRecordIdentifier(sigRec)>, storageClass]
          %<SLibReportErrorWithIdAndArgs("RTW:tlc:UnsupportStorageInRootU", args)>
        %endif
        %if storageClass == "Custom"
          %<FcnCheckForNonAddressableError(bInput, bAddr, sigRec, storageClass)>
          %return LibCustomData(sigRec, bAddr ? "address" : "contents", ...
            busSelElIdx + sigIndexer, reim)
        %endif
        %assign retSignal = "%<LibGetRecordIdentifier(sigRec)>%<busSelElIdx>%<sigIndexer>"
        %if reim != ""
          %% The real or imaginary part of a complex signal is
          %% requested. For now, disallow imported complex block
          %% signals since we don't know how to dereference them.
          %if storageClass == "ImportedExtern" || ...
            storageClass == "ImportedExternPointer"
            %<SLibReportErrorWithIdAndArgs("RTW:tlc:NoImportedComplex", retSignal)>
          %else
            %assign retSignal = retSignal + ".%<reim>"
          %endif
        %endif
      %else
        %if sigRec.UseAccessFunctions
          %<FcnCheckForNonAddressableError(bInput, bAddr, sigRec, storageClass)>
          %return FcnGetAccessFunctionSignalReference(sigRec, bAddr, busSelElIdx + sigIndexer)
        %endif
         
        %% Normal signal or the Accelerator version of the S-function
        %% target. The Accelerator doesn't need the 'ssGetInputPortSignalPtrs
        %% because the inputs only exist at the root model window.
        %if CodeFormat != "S-Function" || Accelerator
          %if SLibFcnProtoCtrlActive() && sigRec.RequiresGlobalAccess == "no"
            %assign fcnData = FcnGetFunctionPrototypeRecord()
            %assign spec = FcnGetFcnDataForPort(fcnData, "Inport", mapIdx)
            %assign identifier = spec.ArgName
            %assign scalarInputPassedByAddr = spec.Category == "Pointer" && (sigSrcWidth == 1)
            %assign derefNeeded = scalarInputPassedByAddr && !bAddr
          %elseif GenerateClassInterface && sigRec.RequiresGlobalAccess == "no"
            %assign classConfObj = FcnGetRTWCPPStepPrototypeRecord()
            %if !classConfObj.hasGlobalAccessForInport
              %assign spec = FcnGetFcnDataForPort(classConfObj, "Inport", mapIdx)
              %assign identifier = spec.ArgName
              %assign scalarInputPassedByAddr = spec.Category == "Pointer" && (sigSrcWidth == 1)
              %assign derefNeeded = scalarInputPassedByAddr && !bAddr
            %else
              %assign identifier = "%<SLibGetExternalInputStruct(TLC_TRUE,TLC_TRUE,cross)>%<UQualifier>%<LibGetRecordIdentifier(sigRec)>"
              %assign derefNeeded = PassExtInpByRef(sigRec)
            %endif
          %else
            %assign identifier = "%<SLibGetExternalInputStruct(TLC_TRUE,TLC_TRUE,cross)>%<UQualifier>%<LibGetRecordIdentifier(sigRec)>"
            %assign derefNeeded = PassExtInpByRef(sigRec)
          %endif
          %if derefNeeded
            %assign retSignal = ...
              "(*%<identifier>)%<busSelElIdx>%<sigIndexer>"
          %else
            %assign retSignal = ...
              "%<identifier>%<busSelElIdx>%<sigIndexer>"
          %endif
          %if reim != ""
            %assign retSignal = retSignal + ".%<reim>"
          %endif
        %else %% s-function target
          %assign dataType = SLibGetRecordDataTypeName(sigRec, "")
 
          %% anchor.b.c, the anchor must be a value
          %% anchor[0], the anchor must be a reference, note [0] is sigIndexer
          %% anchor[1].elem[2], the anchor must be a reference,
          %% note [1].elem is busSelElIdx and [2] is sigIndexer
          %if ISEMPTY(busSelElIdx) || LibGetRecordWidth(sigRec) > 1
            %assign derefOnAnchor = ""
          %else
            %assign derefOnAnchor = "*"
          %endif
 
          %assign extInp = ::CompiledModel.ExternalInputs.ExternalInput[mapIdx]
 
          %% anchor is always a pointer.
          %if ISFIELD(extInp, "HasVarDims")
            %assign anchor = "(%<derefOnAnchor>(const %<dataType>*)"...
              "ssGetInputPortSignal(%<SLibGetSimStruct()>, %<mapIdx>))"
          %else
            %assign anchor = "(%<derefOnAnchor>*((const %<dataType>**)"...
              "ssGetInputPortSignalPtrs(%<SLibGetSimStruct()>, %<mapIdx>)))"
          %endif
 
          %assign sigIndexer = (ISEMPTY(busSelElIdx) && ISEMPTY(sigIndexer)) ? "[0]" : sigIndexer
          %assign retSignal = "%<anchor>%<busSelElIdx>%<sigIndexer>"
 
          %if reim != ""
            %assign retSignal = "(%<retSignal>.%<reim>)"
          %endif
        %endif
      %endif
 
      %break
 
    %case "Y"
      %% the code for ROOT OUTPORT is simpler than ROOT INPORT because
      %% the optimization that removes block IO to root outport data copy
      %% works for standalone target only.
 
      %% But we could have ROOT OUTPORTS mapped to a Legacy Storage Class
      %% via Default Mapping. Handle that first
      %if storageClass != "Auto"
        %% external signal
        %%
        %% S-functions do not support external i/o
        %%
        %if CodeFormat == "S-Function"
          %assign args = [%<LibGetRecordIdentifier(sigRec)>, storageClass]
          %<SLibReportErrorWithIdAndArgs("RTW:tlc:UnsupportStorageInRootY", args)>
        %endif
        %if storageClass == "Custom"
          %<FcnCheckForNonAddressableError(bInput, bAddr, sigRec, storageClass)>
          %return LibCustomData(sigRec, bAddr ? "address" : "contents", ...
            busSelElIdx + sigIndexer, reim)
        %endif
      %else
        %if sigRec.UseAccessFunctions
          %<FcnCheckForNonAddressableError(bInput, bAddr, sigRec, storageClass)>
          %return FcnGetAccessFunctionSignalReference(sigRec, bAddr, busSelElIdx + sigIndexer)
        %endif
 
        %<LibAccessArg(sigRec)>
 
        %if SLibFcnProtoCtrlActive() && sigRec.RequiresGlobalAccess == "no"
          %assign fcnData = FcnGetFunctionPrototypeRecord()
          %assign spec = FcnGetFcnDataForPort(fcnData, "Outport", mapIdx)
          %assign identifier = spec.ArgName
          %assign scalarOutputPassedByAddr = spec.Category == "Pointer" && (sigSrcWidth == 1)
          %assign derefNeeded = scalarOutputPassedByAddr && !bAddr
        %elseif GenerateClassInterface && sigRec.RequiresGlobalAccess == "no"
          %assign classConfObj = FcnGetRTWCPPStepPrototypeRecord()
          %if !classConfObj.hasGlobalAccessForOutport
            %assign spec = FcnGetFcnDataForPort(classConfObj, "Outport", mapIdx)
            %assign identifier = spec.ArgName
            %assign scalarOutputPassedByAddr = spec.Category == "Pointer" && (sigSrcWidth == 1)
            %assign derefNeeded = scalarOutputPassedByAddr && !bAddr
          %else
            %assign identifier = "%<SLibGetExternalOutputStruct(TLC_TRUE,TLC_TRUE,cross)>%<UQualifier>%<LibGetRecordIdentifier(sigRec)>"
            %assign derefNeeded = PassExtOutpByRef(sigRec)
          %endif
        %else
          %assign identifier = "%<SLibGetExternalOutputStruct(TLC_TRUE,TLC_TRUE,cross)>%<UQualifier>%<LibGetRecordIdentifier(sigRec)>"
          %assign derefNeeded = PassExtOutpByRef(sigRec)
        %endif
        %if derefNeeded
          %assign retSignal = ...
            "(*%<identifier>)%<busSelElIdx>%<sigIndexer>"
        %else
          %assign retSignal = ...
            "%<identifier>%<busSelElIdx>%<sigIndexer>"
        %endif
        %if reim != ""
          %assign retSignal = retSignal + ".%<reim>"
        %endif
      %endif
      %break
       
    %case "G"
    %default
      %
  %endswitch %% mapSource
 
  %assign cast = ""
  %if mapSource == "I"
    %% Unconditionally cast away qualifiers for ConstBlockIO sigrecs
    %assign dtypeName = LibGetRecordDataTypeName(sigRec, "")
    %assign cast = "(%<dtypeName>*)"
  %endif
 
  %if bAddr && !scalarInputPassedByAddr && ...
    !scalarOutputPassedByAddr && ...
    ((storageClass != "ImportedExternPointer") || (sigSrcWidth > 1))
    %assign retSignal = cast + "&" + retSignal
  %endif
 
  %return retSignal
 
%endfunction %% end FcnGetBasicSignalReference
 
%%Function:FcnGetGroundSignalValue==========================================
%%Abstract:
%%Returnsthevalueofagroundedsignal.
%%
%function FcnGetGroundSignalValue(dtID, isComplex, reim) void
  %if isComplex && reim == ""
    %%
    %% the complex container is required (by name)
    %%
    %assign retSignal = SLibGetDtGroundName(dtID, isComplex, reim)
    %<SLibSetDataTypeComplexGroundReqInMemory(dtID)>
  %else
    %%
    %% it's a non-complex ground or the real or imaginary part
    %% of a complex ground, so return the actual value/name
    %%
    %if LibIsDataTypeMultiWordFixpt(dtID)
      %%
      %% the multiword container is required (by name)
      %%
      %assign retSignal = SLibGetDtGroundName(dtID, isComplex, reim)
      %<SLibSetDataTypeGroundReqInMemory(dtID)>
    %else
      %assign retSignal = SLibGetDtGroundValue(dtID, isComplex, reim, 1)
      %if TYPE(retSignal) != "String"
        %% format value according to data type
        %assign retSignal = SLibGetFormattedValueFromId(dtID, retSignal)
      %endif
    %endif
  %endif
  %return retSignal
%endfunction
 
%%Function:FcnGetGroundSignalAddr============================================
%%Abstract:
%%Returnstheaddressofagroundedsignal.
%%
%function FcnGetGroundSignalAddr(dtID, isComplex, reim) void
  %assign retSignal = "&" + SLibGetDtGroundName(dtID, isComplex, "")
 
  %% We cast away constness (and possibly volatility) whenever the address of a
  %% ground signal is requested. A future enhancement would be to provide
  %% information about the intended use to determine if this cast is necessary
  %assign dtypeName = ""
  %if isComplex
    %assign dtypeName = LibGetDataTypeComplexNameFromId(dtID)
  %else
    %assign dtypeName = LibGetDataTypeNameFromId(dtID)
  %endif
 
  %assign cast = "(%<dtypeName>*)"
  %%need extra bracket for class to handle the case for class, e.g.,: ((myClass*) &ground)->length()
  %assign retSignal = "(%<cast> %<retSignal>)"
 
  %if isComplex
    %<SLibSetDataTypeComplexGroundReqInMemory(dtID)>
  %else
    %<SLibSetDataTypeGroundReqInMemory(dtID)>
  %endif
  %return retSignal
%endfunction
 
%%Function:FcnGetGroundSignalReference=======================================
%%Abstract:
%%Returningareferencetoagroundedsignal
%%
%function FcnGetGroundSignalReference(sigKind, dtID, isComplex, reim) void
  %switch sigKind
    %case "input"
      %return FcnGetGroundSignalValue(dtID, isComplex, reim)
      %%break
    %case "inputAddr"
      %return FcnGetGroundSignalAddr(dtID, isComplex, reim)
      %%break
    %default
      %% output signals can't source to ground!
      %<SLibReportErrorWithIdAndArgs("RTW:tlc:UnexpectedSigKind", sigKind)>
  %endswitch
  %return ""
%endfunction %% end FcnGetGroundSignalReference
 
%%Function:FcnGetLocalDWorkIdentifier=======================================
%%Abstract:
%%Thisfunctionreturntheidentifierfora**global**DWorksignal.
%%(e.g."rtDW.sub1.sub2.signal,localDW->sub1.sub2.signal")
%%
%%Arguments:
%%
%%blkSysIdx-Wheredoesthesignallive?(Notusedyet)
%%accessSysIdx-Wheredowanttoseethesignal?
%%sigIdx-SignalSrcindex(containscallsiteindex)
%%
%function FcnGetLocalDWorkIdentifier(blkSysIdx, accessSysIdx, sigIdx) void
  %assign dwRec = DWorks.DWork[sigIdx]
  %if dwRec.StorageClass == "Auto"
    %if CodeFormat == "S-Function" && !Accelerator
      %assign idxStr = SLibDWorkWidth(dwRec) == 1 ? "[0]" : ""
      %return SLibGetGlobalDWorkIdentifier(dwRec, sigIdx) + idxStr
    %else
      %assign varGroup = ::CompiledModel.VarGroups.VarGroup[dwRec.VarGroupIdx[0]]
      %return SLibCG_GetVarGroupElementPath(dwRec.VarGroupIdx, accessSysIdx, ...
        System[varGroup.SysIdx].CrossNoArgFcnBound)
    %endif
  %else
    %return ""
  %endif
%endfunction
 
%%Function:FcnGetLocalCStateIdentifier=======================================
%%Abstract:
%%Thisfunctionreturntheidentifierfora**global**CStatesignal.
%%(e.g."rtX.sub1.sub2.signal,localX->sub1.sub2.signal")
%%
%%Arguments:
%%
%%blkSysIdx-Wheredoesthesignallive?(Notusedyet)
%%accessSysIdx-Wheredowanttoseethesignal?
%%sigIdx-SignalSrcindex(containscallsiteindex)
%%
%function FcnGetLocalCStateIdentifier(blkSysIdx, accessSysIdx, sigIdx) void
  %assign csRec = ::CompiledModel.ContStates.ContState[sigIdx]
  %assign varGroupIdx = csRec.VarGroupIdx[0]
  %assign cross = CrossNoArgFcnBound
  %assign identiPath = SLibCGIRVarGroupPath(varGroupIdx, accessSysIdx, cross)
  %return identiPath + csRec.Identifier
%endfunction
 
%%Function:FcnGetCanonicalArg================================================
%%Abstract:
%%Returnsaidentifierforacanonicalinputoroutputargument.
%%
%function FcnGetCanonicalArg(portObj, sigIdx, cross, scalarByAddr) void
  %assign sigRecAndMapInfo = ...
    SLibGetSourceRecordAndMapInfo(portObj, sigIdx, TLC_TRUE, TLC_FALSE)
 
  %assign bAddr = TLC_FALSE
  %assign sigType = "input" %% only needed by canonical inputs that are
                              %% connected to ground blocks or unconnected
 
  %assign portWidth = LibGetRecordWidth(portObj)
  %assign identi = sigRecAndMapInfo.identi
 
  %if portWidth > 1 || (scalarByAddr && portWidth == 1)
    %assign sigOffset = sigRecAndMapInfo.signalOffset
    %if !ISEMPTY(identi) && sigOffset == 0
      %if portWidth > 1
        %if ISFIELD(portObj, "SrcIsPointerToArray") && portObj.SrcIsPointerToArray == "yes"
          %return "*" + identi
        %else
          %return identi
        %endif
        %% Handle all scalars (portWidth == 1) in FcnGetBasicSignalReference
      %endif
    %endif
    %assign bAddr = TLC_TRUE
    %assign sigType = "inputAddr"
  %endif
 
  %assign signalRec = sigRecAndMapInfo.sigRec
  %assign mapSource = sigRecAndMapInfo.mapSrc
 
  %if mapSource=="G" || ISEMPTY(signalRec) %% needs to be removed
    %assign dtID = LibGetRecordDataTypeId(portObj)
    %return FcnGetGroundSignalReference(sigType, dtID, TLC_FALSE, "")
  %else
    %assign retSignal = FcnGetBasicSignalReference(sigRecAndMapInfo, ...
      portWidth, "", TLC_TRUE, bAddr, TLC_FALSE, LibGetRecordIsStdContainer(portObj), "", "", cross)
 
    %if ISFIELD(signalRec, "StorageClass") && ...
      signalRec.StorageClass == "ImportedExternPointer"
      %% We always pass structs by reference in C
      %% except for multiword and complex
      %if LibGetRecordWidth(signalRec) == 1 && ...
        !SLibDeclareDataAsPointer(LibGetRecordDataTypeId(signalRec)) && ...
        !bAddr
        %assign retSignal = "(*%<retSignal>)"
      %endif
    %endif
 
    %return retSignal
  %endif
 
%endfunction
 
 
%%Function:ReAssignLocalBlockOutputTID=======================================
%%Abstract:
%%ThisfunctionsetsalTID'sofalocalblockoutput.
%%TheTIDinthelocalblockoutputisasupersetoftheTIDneededto
%%declarethelocalvariablesineachratewherethevariableappears.
%%ThisfunctionprunesnotneededTIDelementsofthelocalblockoutputs
%%TIDvectorandassignsaTIDforeverytriggerdblockoutput.
%%
%function ReAssignLocalBlockOutputTID(localBO) void
  %if SLibIsPeriodicRateGrouping()
    %if TYPE(CurrentTID) == "Number" && CurrentTID == -1
      %% don't change localBO.TID if CurrenTID is -1
    %elseif !ISEQUAL(localBO.TID, CurrentTID)
      %assign temp = []
      %foreach i = NumSampleTimes
        %assign temp = temp + 0
      %endforeach
 
      %if TYPE(localBO.TID) == "Vector"
        %foreach i = SIZE(localBO.TID,1)
          %assign idx = (localBO.TID[i] > 0) ? localBO.TID[i] : 0
          %assign temp[idx] = 1
        %endforeach
      %elseif TYPE(localBO.TID) == "Number"
        %assert localBO.TID >= 0
        %assign temp[localBO.TID] = 1
      %endif
      %if TYPE(CurrentTID) == "Number"
        %assign temp[CurrentTID] =1
      %elseif TYPE(CurrentTID) == "Vector"
        %foreach i = SIZE(CurrentTID,1)
          %assign idx = (CurrentTID[i] > 0) ? CurrentTID[i] : 0
          %assign temp[idx] = 1
        %endforeach
      %endif
      %assign localBO.TID = []
      %foreach i = NumSampleTimes
        %if temp[i] == 1
          %assign localBO.TID = localBO.TID + i
        %endif
      %endforeach
    %endif
  %endif
%endfunction
 
%function FcnGetActiveFcnForDecl() void
  %if ::BlockFcn == "RootUpdate"
    %if CombineOutputUpdateFcns == 1
      %return "Output"
    %else
      %return "Update"
    %endif
  %elseif ::BlockFcn == "OutputUpdate"
    %return "Output"
  %else
    %return ::BlockFcn
  %endif
%endfunction
 
%%Function:SLibCreateDummyPortRecord=========================================
%%Abstract:
%%Thisfunctioncreatesadummyportrecordthatcanbeusedtoinvoke
%%SLibGetSourceRecordAndMapInfo.
%%
%function SLibCreateDummyPortRecord() void
  %createrecord portObj { /
    BusSelElIdx [""] /
    BusSelElCGTypeId [-1] /
    SignalSrc [-1] /
    SignalOffset [-1] /
    SymbolicSignalOffset -1 /
    Width 1 }
  %return portObj
%endfunction
 
%%Function:SLibGetSourceRecordAndMapInfo=====================================
%%Abstract:
%%Thisfunctiontakesaportobjectandportsignalindexasaargument
%%andreturnsasignalrecordand.
%%
%%bReturnIdentfier-doesthefunctioncallerneedstoknowthe
%%signalidentifierstring??
%%
%function SLibGetSourceRecordAndMapInfo(portObj, sigIdx, ...
  bReturnIdentfier, bTLCInterfaceV2Active) void
 
  %createrecord rec {mapSrc "";mapIdx -1;sigRec [];busSelElIdx "";busSelElCGTypeId -1;signalOffset -1; symbolicSignalOffset -1; identi "";isPointer TLC_FALSE}
 
  %if SIZE(portObj.SignalSrc,1) > 1
    %assign lSigIdx = sigIdx
  %else
    %assign lSigIdx = 0
  %endif
 
  %assign sigRecEmpty = TLC_TRUE
  %assign idNum = IDNUM(portObj.SignalSrc[lSigIdx])
  %assign busSelElIdx = ""
  %assign busSelElCGTypeId = -1
 
  %if ISFIELD(portObj,"BusSelElIdx")
    %assign busSelElIdx = portObj.BusSelElIdx[lSigIdx]
    %assign busSelElCGTypeId = portObj.BusSelElCGTypeId[lSigIdx]
  %endif
 
  %% translate relative into absolute positions
  %switch (idNum[0])
    %case "L"
      %assign localBO = BlockOutputs.LocalBlockOutput[idNum[1]]
      %assign rec.sigRec = localBO
      %assign rec.mapSrc = "b"
      %assign rec.isPointer = localBO.DeclareAsPointer == "yes"
      %assign sigRecEmpty = TLC_FALSE
      %%
      %if bReturnIdentfier && !bTLCInterfaceV2Active
        %if localBO.VarGroupVarIdx > -1
          %assign varGroupIdx = ...
            ::CompiledModel.VarGroups.VarGroupVarIdx[localBO.VarGroupVarIdx]
          %assign rec.identi = SLibCG_GetVarGroupElementPath(varGroupIdx, ...
            SLibGetHStructWithLocalScopeSystemIdx(SystemIdx), CrossNoArgFcnBound)
        %else
          %assign activeFcn = FcnGetActiveFcnForDecl()
          %assign declareInFcnScope = "DeclareIn%<activeFcn>FcnScope"
          %assign localBO.%<declareInFcnScope> = 1
          %<ReAssignLocalBlockOutputTID(localBO)>
          %%yz %assign rec.identi = tLocalBlockIO + "_" + LibGetRecordIdentifier(localBO)
          %assign rec.identi = "%<LibGetRecordIdentifier(localBO)>"
        %endif
      %endif
      %break
    %%
    %% Global block IO structure handling
    %%
    %case "b" %% global block IO index
      %assign globalBO = BlockOutputs.GlobalBlockOutput[idNum[1]]
      %assign rec.sigRec = globalBO
      %assign rec.mapSrc = "b"
      %assign rec.isPointer = globalBO.DeclareAsPointer == "yes"
      %assign sigRecEmpty = TLC_FALSE
      %%
      %if bReturnIdentfier && !bTLCInterfaceV2Active
        %% where the signal is accessed
        %% For example,
        %%
        %% gainA -> [ O->gainB->O]
        %% ^
        %% |
        %% nonreusable function
        %% then LibBlockInputSignal for gainB needs to know that
        %% is crossed the nonreused boundary to generate the correct
        %% path.
        %assign rec.identi = ...
          SLibCG_GetVarGroupElementPath(globalBO.VarGroupIdx, ...
          SLibGetHStructWithLocalScopeSystemIdx(SystemIdx), CrossNoArgFcnBound)
      %endif
      %break
    %%
    %% Canonical inputs handling (system level inputs)
    %%
    %case "u"
      %assign blkSysIdx = System[BlockIdx[1]].ReusedParentSystemIdx
      %assign interface = System[blkSysIdx].Interface
      %assign canInputArg = interface.CanonicalInputArgDef[idNum[1]]
 
      %assign sys = System[SystemIdx]
      %with sys
        %assign tid = FcnGetCurrentAccessTid()
      %endwith
 
      %if ISFIELD(portObj,"RecordType") && ...
        portObj.RecordType == "ControlInputPort"
        %% See engine_blksNS/tsubsys (msubsys5). Connect Enable port to
        %% a root inport block
        %assign cross = System[BlockIdx[1]].CrossNoArgFcnBound
      %else
        %% See example in modelref/basic/tblockio lvlTwo25
        %assign cross = CrossNoArgFcnBound
      %endif
 
      %%
      %if bReturnIdentfier
        %if !bTLCInterfaceV2Active
          %% where the signal is accessed
          %assert (System[SystemIdx].HStructDeclSystemIdx <= blkSysIdx || ISFIELD(System[SystemIdx],"RTWSystemCodeOptIntf"))
          %if !cross
            %assign rec.identi = LibGetRecordIdentifier(canInputArg)
          %else
            %<SLibAccessArgHelper(canInputArg,"Global",tid)>
            %assign rec.identi = canInputArg.GlobalIdentifier
          %endif
          %if canInputArg.DeclareAsPointer == "yes"
            %assign rec.identi = "(*%<rec.identi>)"
          %endif
          %<SLibAccessArgHelper(canInputArg,"",tid)>
        %endif
        %assign rec.sigRec = canInputArg
        %assign rec.mapSrc = "u"
        %assign sigRecEmpty = TLC_FALSE
      %else
        %assign idNum = IDNUM(canInputArg.SignalSrc[0])
        %assign mapSource = idNum[0]
        %assign mapIndex = idNum[1]
      %endif
      %%
      %break
    %case "y" %% system level output
      %assign blkSysIdx = System[BlockIdx[1]].ReusedParentSystemIdx
      %assign interface = System[blkSysIdx].Interface
      %assign canOutputArg = interface.CanonicalOutputArgDef[idNum[1]]
 
      %assign sys = System[SystemIdx]
      %with sys
        %assign tid = FcnGetCurrentAccessTid()
      %endwith
 
      %if ISFIELD(portObj,"RecordType") && ...
        portObj.RecordType == "ControlInputPort"
        %% See engine_blksNS/tsubsys (msubsys5)
        %% Since each enable subsystems accesses its enable port inside
        %% the system function, the cross flag must be basded on the
        %% sysIdx of the subsystem itself.
        %assign cross = System[BlockIdx[1]].CrossNoArgFcnBound
      %else
        %% See example in modelref/basic/tblockio lvlTwo25
        %assign cross = CrossNoArgFcnBound
      %endif
      %%
      %if bReturnIdentfier
        %% where the signal is accessed
        %if !bTLCInterfaceV2Active
          %assert (System[SystemIdx].HStructDeclSystemIdx <= blkSysIdx || ISFIELD(System[SystemIdx],"RTWSystemCodeOptIntf"))
          %if !cross
            %if LibGetRecordWidth(canOutputArg) == 1 && ...
              canOutputArg.DeclareAsPointer == "yes"
              %assign rec.identi = "(*" + LibGetRecordIdentifier(canOutputArg) + ")"
            %else
              %assign rec.identi = LibGetRecordIdentifier(canOutputArg)
            %endif
          %else
            %<SLibAccessArgHelper(canOutputArg,"Global",tid)>
            %assign ident = canOutputArg.GlobalIdentifier
            %if LibGetRecordWidth(canOutputArg) == 1 && ...
              canOutputArg.PassByReturn == "no"
              %assign rec.identi = "(*%<ident>)"
            %else
              %assign rec.identi = "%<ident>"
            %endif
          %endif
          %<SLibAccessArgHelper(canOutputArg,"",tid)>
        %endif
        %assign rec.sigRec = canOutputArg
        %assign rec.mapSrc = "y"
        %assign sigRecEmpty = TLC_FALSE
      %else
        %assign idNum = IDNUM(canOutputArg.SignalSrc[0])
        %assign mapSource = idNum[0]
        %assign mapIndex = idNum[1]
      %endif
      %%
      %break
    %case "d" %% local DWork index
      %if bReturnIdentfier && !bTLCInterfaceV2Active
        %assign blkSysIdx = BlockIdx[0] %% where the signal is created
        %assign accessSysIdx = System[SystemIdx].HStructDeclSystemIdx
        %% where the signal is accessed
        %assign rec.identi = ...
          FcnGetLocalDWorkIdentifier(blkSysIdx, accessSysIdx, idNum[1])
      %endif
      %assign mapSource = "D"
      %assign mapIndex = idNum[1]
      %break
    %case "x" %% local continuous state index
      %if bReturnIdentfier && !bTLCInterfaceV2Active
        %assign blkSysIdx = BlockIdx[0] %% where the signal is created
        %assign accessSysIdx = System[SystemIdx].HStructDeclSystemIdx
        %% where the signal is accessed
        %assign rec.identi = ...
          FcnGetLocalCStateIdentifier(blkSysIdx, accessSysIdx, idNum[1])
      %endif
      %assign mapSource = "X"
      %assign mapIndex = idNum[1]
      %break
    %default
      %assign mapSource = idNum[0]
      %assign mapIndex = idNum[1]
  %endswitch
 
  %assign rec.busSelElIdx = busSelElIdx
  %assign rec.busSelElCGTypeId = busSelElCGTypeId
  %assign rec.signalOffset = portObj.SignalOffset[lSigIdx]
  %if ISFIELD(portObj, "SymbolicSignalOffset")
    %assign rec.symbolicSignalOffset = portObj.SymbolicSignalOffset
  %endif
   
  %if sigRecEmpty
    %if bReturnIdentfier
      %assign rec.mapSrc = mapSource
      %assign rec.mapIdx = mapIndex
    %endif
    %switch (mapSource)
      %%
      %% Constant expression handling
      %%
      %case "C"
        %assign rec.sigRec = BlockOutputs.ConstOutputExpr[mapIndex]
        %break
      %case "L" %% local variable
        %assign rec.sigRec = ...
          ::CompiledModel.BlockOutputs.LocalBlockOutput[mapIndex]
        %break
      %case "B" %% global block IO index
        %assign rec.sigRec = ...
          ::CompiledModel.BlockOutputs.GlobalBlockOutput[mapIndex]
        %break
      %case "I" %% invariant signal
        %assign rec.sigRec = ...
          ::CompiledModel.BlockOutputs.ConstBlockOutput[mapIndex]
        %break
      %case "E" %% external signal
        %assign rec.sigRec = ...
          ::CompiledModel.BlockOutputs.ExternalBlockOutput[mapIndex]
        %break
      %case "D" %% global DWork index
        %assign rec.sigRec = ::CompiledModel.DWorks.DWork[mapIndex]
        %break
      %case "X" %% global state vector index
        %assign rec.sigRec = ::CompiledModel.ContStates.ContState[mapIndex]
        %break
      %case "U" %% root level input
        %assign rec.sigRec = ...
          ::CompiledModel.ExternalInputs.ExternalInput[mapIndex]
        %if bReturnIdentfier
          %<LibAccessArg(rec.sigRec)>
        %endif
        %break
      %case "Y" %% root level output
        %assign rec.sigRec = ...
          ::CompiledModel.ExternalOutputs.ExternalOutput[mapIndex]
        %break
      %case "G" %% grounded signal
        %assign rec.sigRec = []
        %break
      %case "F" %% function call
        %assign rec.sigRec = []
        %break
      %case "M" %% Simulink Message
        %assign rec.sigRec = []
        %break
      %default
        %error ...
          "Wrong map source '%<mapSource>' in SLibGetSourceRecordAndMapInfo."
    %endswitch %% mapSource
  %endif
  %return rec
 
%endfunction %% end SLibGetSourceRecordAndMapInfo
 
%%Function:SLibGetSourceRecord===============================================
%%Abstract:
%%Thisfunctiontakesaportobjectandportsignalindexasaargument
%%andreturnsasignalrecord.
%%
%function SLibGetSourceRecord(portObj, sigIdx) void
  %assign rec = SLibGetSourceRecordAndMapInfo(portObj, sigIdx, ...
    TLC_FALSE, TLC_FALSE)
  %return rec.sigRec
%endfunction %% end SLibGetSourceRecord
 
%%Function:SLibGetSourceMapInfo=============================================
%%Abstract:
%%Thisfunctiontakesaportobjectandportsignalindexasaargument
%%andreturnsmappinginfo.
%%
%function SLibGetSourceMapInfo(portObj, sigIdx) void
  %return SLibGetSourceRecordAndMapInfo(portObj, sigIdx, TLC_FALSE, TLC_FALSE)
%endfunction %% end SLibGetSourceMapInfo
 
%%Function:FcnGetInputOrOutputSignal=========================================
%%Abstract:
%%Thisimplementsthe'body'of
%%LibBlockInputSignal
%%LibBlockInputSignalAddr
%%LibBlockOutputSignal
%%LibBlockOutputSignalAddr
%%
%%
%%Ingeneral,thereareessentiallyfourpartstothesignalreference
%%returnedbythisroutine:
%%.
%%
%%Thefirstpart,,dependsonwherethissignalisdeclared,which
%%inturnisessentiallydeterminedbytheattributesofthedrivingblock
%%andtheoutputportfromwherethissignaloriginates.Herearethe
%%variouspossibilities:
%%
%%"rtU":Externalinputsvector(drivenbyainportblocknotina
%%subsystem)
%%"rtX":Statesvector(outputfromthestateportofdrivingblock)
%%"rtB":BlockI/Ovector,declaredglobally
%%"rtb_":BlockI/Ovector,declaredlocally
%%"rtC":ConstBlockI/Ovector(drivenbyaninvariantblock)
%%"rtC_":#define'dConstBlockI/O(drivenbyaninvariantblock)
%%{false,"0","0.0","rtGROUND","rtGROUND_Complex"}:
%%GroundedorunconnectedinputwheredTypeistheinputport
%%datatype.
%%"u":Insidearolledloop
%%databanks:(userdefinedmemorylocation).
%%rtP:DefinedinTLC
%%
%%Thesecondpart,,istheI/Oqualifier(ortheselectionoperator)
%%whichislargelydeterminedbythecodeformat.Thepossibilities:
%%
%%"":Insidearolledloop
%%".":RealTimeandEmbedded-Ccodeformats(static)
%%"->":RealTimeandEmbedded-Ccodeformats(malloc)andS-functioncodeformats
%%
%%Thethirdpart,,istheuniquifiedidentifierassignedtothis
%%signal.Thisidentifierisobtainedfromeitherthesignallabel
%%specifiedintheSimulinkdiagramor,ifasignallabelisnot
%%present,thenameoftheblockfromwhichthissignaloriginates.
%%
%%For#define'dinvariantblockI/Osignals,anadditional"_"is
%%appendedbetweentheandpositions.
%%
%%Thefinalpart,,istheindexintotheappropriateelement
%%and/orthereal/imaginarypartoftheinputsignal,ifitiseither
%%wideand/orcomplex.
%%
%%Combiningallofthem,onegetsstringssuchas"rtB.s7_Gain1[2]"."rtB"
%%isthepart,"."istheI/Oqualifier,"s7_Gain1"isthe
%%part(s7representsSubsystem7whileGain1isthenameoftheblock),
%%and"[2]"isthepart.
%%
%function FcnGetInputOrOutputSignal(sigKind, aPortIdx, ucv, lcv, sigIdx) void
 
  %assign portIdx = CAST("Number", aPortIdx)
 
  %%------------------------------------------%%
  %% Process sigIdx & configure reim, retType %%
  %%------------------------------------------%%
  %assign reim = "" %% assume we are accessing the whole signal
 
  %if sigKind == "input" || sigKind == "inputAddr"
    %assign bInput = TLC_TRUE
  %elseif sigKind == "output" || sigKind == "outputAddr"
    %assign bInput = TLC_FALSE
  %else
    %<LibBlockReportError([],"Invalid sigKind")>
  %endif
 
  %if sigKind == "input" || sigKind == "output"
    %assign bAddr = TLC_FALSE
  %else
    %assign bAddr = TLC_TRUE
  %endif
 
  %if ISEMPTY(sigIdx)
    %if ISEMPTY(ucv) && ISEMPTY(lcv)
      %setcommandswitch "-v1"
      %<LibBlockReportError([],"Invalid sigIdx: '%<sigIdx>' " + ...
        "(must be an integer or an integer prefixed with the TLC " + ...
        "variable tRealPart or tImagPart)")>
    %endif
    %assign sigIdx = 0 %% ucv != "" || lcv != "" => sigIdx ignored.
  %endif
 
  %if bInput
    %assign portObj = FcnGetInputPortRecord(portIdx)
    %assign portType = "BlockInput" %% needed for purely integer error message
    %assign varName = "u" %% needed in case of rolling
  %else %%output
    %assign portObj = FcnGetOutputPortRecord(portIdx)
    %assign portType = "BlockOutput" %% needed for purely integer error message
    %assign varName = "y" %% needed in case of rolling
  %endif
 
  %assign isComplex = LibGetRecordIsComplex(portObj)
 
  %% the complex signal handling is the same for input and output signals
  %% because discontiguous signal with mixed complex and non-complex signals
  %% are not allowed in Simulink
  %%
  %if !bAddr
    %if TYPE(sigIdx) == "String"
      %assign tmpVect = SLibGetReimAndIdx(sigIdx)
      %assign reim = tmpVect[0]
      %assign sigIdx = tmpVect[1]
 
      %% Return "" when attempting to access the imaginary part of a
      %% non-complex signal.
      %if reim != "" && !isComplex
        %% If the signal is not complex then the imaginary part is ""
        %if reim == tImagPart
          %return ""
        %elseif reim == tRealPart
          %% The input signal is not complex so we don't need the .re part
          %assign reim = ""
        %else
          %<LibBlockReportError([], ...
            "Invalid value of Real/Imag sigIdx part: %<reim>")>
        %endif
      %endif
    %endif
  %else %% sigKind == "inputAddr" || sigKind == "outputAddr"
    %if TYPE(sigIdx) != "Number"
      %<LibBlockReportError([], "sigIdx must be an integer index " + ...
        "when accessing an input signal address")>
    %endif
  %endif
 
  %if !bInput && ucv != "" %% ucv handling for output signals
    %% the signal type is output and ucv is specified inside a roller
    %% the user has to manage the signal indexing by passing the
    %% the loop variable plus signal index
    %%
    %% Notice: this library function will add an offset if the outport
    %% is connected to a merge block (e.g. SignalOffset[0] != 0).
    %%
    %assign sigIdx = 0
  %endif
 
  %%
  %% Invoking the auto-generated TLC interface functions for the current TLC
  %% block. Notice that those will update all required access flags. The
  %% subsequent call to SLibGetSourceRecordAndMapInfo will not update any
  %% access flags if the TLC interface has been called (tlcIFv2Enable is true)
  %%
  %if bInput && SIZE(portObj.SignalSrc,1) > 1
    %assign regionIdx = portObj.SignalRegion[sigIdx]
  %else
    %assign regionIdx = 0
  %endif
  %if SIZE(portObj.SignalOffset,1) > 1
    %assign sigOffset = portObj.SignalOffset[sigIdx]
  %else
    %assign sigOffset = portObj.SignalOffset[0]
  %endif
  %if ISFIELD(portObj, "SymbolicSignalOffset") && portObj.SymbolicSignalOffset > -1
    %assign symbolicOffset = LibCGTypeSymbolicWidth(portObj.SymbolicSignalOffset)
    %assign symbolicOffset = "(" + symbolicOffset + ")"
    %if !WHITE_SPACE(ucv)
      %assign symbolicOffset = ucv + "+" + symbolicOffset
    %endif
    %assign ident = SLibInvokeTLCInterface(SLibGetCurrentBlock(), ...
      (bInput ? "Input" : "Output"), portIdx, regionIdx, bAddr, ...
      lcv, symbolicOffset, 0, reim)
  %else
    %assign ident = SLibInvokeTLCInterface(SLibGetCurrentBlock(), ...
      (bInput ? "Input" : "Output"), portIdx, regionIdx, bAddr, ...
      lcv, ucv, sigOffset, reim)
  %endif
  %assign tlcIFv2Enable = !ISEMPTY(ident)
 
  %%
  %% Retrieving the signal record and mapping info
  %%
  %assign sigRecAndMapInfo = ...
    SLibGetSourceRecordAndMapInfo(portObj, sigIdx, TLC_TRUE, tlcIFv2Enable)
 
  %assign portWidth = LibGetRecordWidth(portObj)
  %assign signalRec = sigRecAndMapInfo.sigRec
  %assign mapSource = sigRecAndMapInfo.mapSrc
  %assign sigOffset = sigRecAndMapInfo.signalOffset
   
  %if !ISEMPTY(signalRec) && ISFIELD(signalRec, "UseAccessFunctions") && signalRec.UseAccessFunctions
    %assign tlcIFv2Enable = TLC_FALSE
  %endif
 
  %%---------------------------------------------------------------------%%
  %% Based on mapSource, generate signal identifier to return (retSignal) %%
  %%---------------------------------------------------------------------%%
  %if ucv != "" || lcv == "" || (lcv != "" && portWidth==1) || ...
    mapSource=="G" || ISEMPTY(signalRec)
    %% ucv specified, not rolling, or rolling a scalar or ground
 
    %if mapSource == "F"
      %error "This function is called from a function that did not" + ...
        "check for function call or action data output port"
    %endif
 
    %if !tlcIFv2Enable && (mapSource=="G" || ISEMPTY(signalRec)) %% needs to be removed
      %% needs to check the result of TLC v2 because canonical I/O records are empty records
      %assign dtID = LibGetRecordDataTypeId(portObj)
      %return FcnGetGroundSignalReference(sigKind, dtID, isComplex, reim)
    %else
      %% Check for floating-point types if integer only code
      %if PurelyIntegerCode
        %assign dTypeId = LibGetDataTypeIdAliasedThruToFromId(LibGetRecordDataTypeId(signalRec))
        %if dTypeId == tSS_DOUBLE || dTypeId ==tSS_SINGLE
          %<SLibCacheIntegerOnlyWarning(Name, portType)>
        %endif
      %endif
 
      %if tlcIFv2Enable
        %if !bInput && bAddr && "I" == mapSource
          %%
          %% The following code is handling scenarios where we pass the
          %% a pointer to a ConstB elemenent to a function that expects
          %% a none constant pointer. This is questionable to say the least,
          %% since this will not work on a embedded target (one cannot cast
          %% ROM to RAM using software) and Simulink should probably not create
          %% models that write to signals with constant (inf) sample time.
          %%
          %assign dtypeName = LibGetRecordDataTypeName(signalRec, "")
          %assign cast = "(%<dtypeName>*)"
          %return cast + ident
        %else
          %return ident
        %endif
      %else
        %assign retSignal = FcnGetBasicSignalReference(sigRecAndMapInfo, ...
          portWidth, reim, bInput, bAddr, isComplex, LibGetRecordIsStdContainer(portObj), ucv, lcv, TLC_FALSE)
      %endif
    %endif
 
  %else %% 'true' rolling
    %%
    %% We are rolling a signal that is non-scalar and non-grounded signal.
    %%
    %%
 
    %assign sigIndexer = SLibGet1DArrayIndexer(portWidth, ucv, lcv, sigOffset)
 
    %assign returnBaseAddr = (bAddr && ucv == "" && lcv == "" && sigIdx == 0 && portWidth > 1) && ...
                             !LibGetRecordIsStdContainer(portObj)
    %%
    %% Return reference to the signal
    %%
    %if returnBaseAddr
      %assign retSignal = "%<varName>%<portIdx>"
    %else
      %assign retSignal = "%<varName>%<portIdx>%<sigIndexer>"
      %%
      %if reim != ""
        %assign retSignal = retSignal + ".%<reim>"
      %endif
      %%
      %if bAddr
        %assign retSignal = "&" + retSignal
      %endif
      %%
    %endif
    %%
  %endif
  %%
  %% Add indirection access if needed
  %%
  %%
  %if !bAddr && ...
    ISFIELD(signalRec, "StorageClass") && ...
    signalRec.StorageClass == "ImportedExternPointer" && ...
    LibGetRecordWidth(signalRec) == 1
    %assign retSignal = "(*%<retSignal>)"
  %endif
 
  %return retSignal
 
%endfunction %% FcnGetInputOrOutputSignal
 
%function FcnGetIOSignalBaseAddr(sigKind, portIdx) void
 
  %%------------------------------------------%%
  %% Process sigIdx & configure reim, retType %%
  %%------------------------------------------%%
  %assign reim = "" %% assume we are accessing the whole signal
 
  %if sigKind == "input"
    %assign bInput = TLC_TRUE
  %elseif sigKind == "output"
    %assign bInput = TLC_FALSE
  %else
    %<LibBlockReportError([],"Invalid sigKind")>
  %endif
 
  %if bInput
    %assign portObj = FcnGetInputPortRecord(portIdx)
    %assign varName = "u" %% needed in case of rolling
  %else %%output
    %assign portObj = FcnGetOutputPortRecord(portIdx)
    %assign varName = "y" %% needed in case of rolling
  %endif
 
  %%
  %% Return reference to the signal
  %%
  %assign retSignal = "%<varName>%<portIdx>"
  %if LibGetRecordWidth(portObj) == 1
    %assign retSignal = "&" + retSignal
  %endif
 
  %return retSignal
 
%endfunction %% FcnGetIOSignalBaseAddr
 
%%Function:SLibBlockOutputSignal=============================================
%%Abstract:
%%Callbackintoablock'sBlockOutputSignal.
%%
%%
%function SLibBlockOutputSignal(block,system,portIdx,ucv,lcv,sigIdx,retType) void
 
  %assign returnValue = ""
  %assign fcn = "BlockOutputSignal"
  %if LibBlockFunctionExists(block,fcn)
    %assign prevBlockFcnIdx = ::CurrentBlockFcnIdx
    %if -1 < block.OutputBlockFcnIdx
      %assign ::CurrentBlockFcnIdx = block.OutputBlockFcnIdx
    %endif
    %with block
      %assign returnValue = GENERATE(block,fcn,system,portIdx,ucv,lcv,sigIdx,retType)
    %endwith
    %assign ::CurrentBlockFcnIdx = prevBlockFcnIdx
  %else
    %assign errTxt = "Block specifies that its output signal " ...
      "is an expression, however, the block does not provide the " ...
      "necessary TLC function: %<fcn>"
    %<LibBlockReportError(block, errTxt)>
  %endif
  %return returnValue
%endfunction
 
%%Function:SLibGetBlockOutputIdentifierFromRecord============================
%%Abstract:
%%Fromthe.rtwfileBlockOutputsRecordgetitsbaseidentifierinthe
%%blockI/OstructuretobeaccessedfromwithintheaccessSysIdx
%%
%function SLibGetBlockOutputIdentifierFromRecord(bo, accessSysIdx) void
  %assign varGroup = ::CompiledModel.VarGroups.VarGroup[bo.VarGroupIdx[0]]
  %return SLibCG_GetVarGroupElementPath(bo.VarGroupIdx, accessSysIdx, ...
    System[varGroup.SysIdx].CrossNoArgFcnBound)
%endfunction
 
%%Function:SLibGetBlockOutputFromRecord======================================
%%Abstract:
%%Fromthe.rtwfileBlockOutputsRecordgetthepathtothatelemntinthe
%%blockI/OstructuretobeaccessedfromwithintheaccessSysIdx
%%
%function SLibGetBlockOutputFromRecord(bo,accessSysIdx) void
 
  %assign id = SLibGetBlockOutputIdentifierFromRecord(bo, accessSysIdx)
 
  %if LibGetRecordWidth(bo) > 1
    %assign indexer = "[0]"
  %else
    %assign indexer = ""
  %endif
  %if LibGetRecordIsComplex(bo)
    %assign re = ".%<tRealPart>"
  %else
    %assign re = ""
  %endif
  %return "&%<id>%<indexer>%<re>"
%endfunction
 
%endif %% _BLKIOLIB_
 
%%[EOF]blkiolib.tlc