%%==============================================================================
%%
%%
%%
%%
%%Abstract:
%%Outputfiletemplatelibrary
%%
%%Copyright1994-2019TheMathWorks,Inc.
%%
%selectfile NULL_FILE
 
%%=============================================================================
%%Publicfunctions
%%=============================================================================
 
%%DocFunction{CodeConfigurationFunctions}:LibGetNumSourceFile===============
%%Abstract:
%%Getthenumberofsourcefiles(.cand.h)thathavebeencreated.
%%
%%Callsyntax:
%%%assignnumFiles=LibGetNumSourceFiles()
%%
%%Returns:
%%Returnsthenumberoffiles(Number).
 
%function LibGetNumSourceFiles() void
  %return LibGetNumModelFiles()
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibGetSourceFileTag===============
%%Abstract:
%%Returns_hand_cforheaderandsourcefiles,
%%respectivelywherefileNameisthenameofthemodelfile.
%%
%%Callsyntax:
%%%assigntag=LibGetSourceFileTag(fileIdx)
%%
%%Arguments:
%%fileIndex(Number)-Fileindex.
%%
%%Returns:
%%Returnsthetag(String).
 
%function LibGetSourceFileTag(fileIdx) void
  %return LibGetModelFileTag(fileIdx)
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibCreateSourceFileAtPath===============
%%Abstract:
%%CreateanewCfile,andreturnitsreference.Ifthefilealreadyexists,
%%simplyreturnitsreference.
%%
%%Callsyntax:
%%%assignfileH=LibCreateSourceFileAtPath("Source","Custom","../slprj/ert/_shareutils/foofile","foofile")
%%
%%Arguments:
%%type(String):
%%Validvaluesare"Source"and"Header"for.cand.hfiles,
%%respectively.
%%
%%creator(String):
%%Who'screatingthefile?Anerrorisreportedifdifferentcreators
%%attempttocreatethesamefile.
%%
%%namewithpath(String):
%%Nameofthefile(withthefilepathbutwithouttheextension).
%%
%%basename(String):
%%Nameofthefile(withoutthepathorextension).
%%
%%Note:Forfilesdestinedtothemodelbuilddir,usethesimpler
%%LIbCreateSourceFile(type,creator,name)
%%
%%Note:Filearenotwrittentodiskiftheyareempty.
%%
%%Returns:
%%Referencetothemodelfile(Scope).
%%
%function LibCreateSourceFileAtPath(type,creator,namewithpath,basename) void
  %assign type = (type == "Source") ? "SystemBody" : "SystemHeader"
  %return SLibAddModelFileWithBasename(type,creator,namewithpath,basename)
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibCreateSourceFile===============
%%Abstract:
%%CreateanewCfile,andreturnitsreference.Ifthefilealreadyexists,
%%simplyreturnitsreference.
%%
%%Callsyntax:
%%%assignfileH=LibCreateSourceFile("Source","Custom","foofile")
%%
%%Arguments:
%%type(String):
%%Validvaluesare"Source"and"Header"for.cand.hfiles,
%%respectively.
%%
%%creator(String):
%%Who'screatingthefile?Anerrorisreportedifdifferentcreators
%%attempttocreatethesamefile.
%%
%%name(String):
%%Nameofthefile(withouttheextension).
%%
%%Note:Filearenotwrittentodiskiftheyareempty.
%%
%%Returns:
%%Referencetothemodelfile(Scope).
 
%function LibCreateSourceFile(type,creator,name) void
  %assign type = (type == "Source") ? "SystemBody" : "SystemHeader"
  %return SLibAddModelFile(type,creator,name)
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibGetSourceFileFromIdx===========
%%Abstract:
%%Returnamodelfilereferencebasedonitsindex.Thisisveryuseful
%%foracommonoperationonallfiles.Forexample,tosettheleadingfile
%%bannerofallfiles.
%%
%%Callsyntax:
%%%assignfileH=LibGetSourceFileFromIdx(fileIdx)
%%
%%Arguments:
%%fileIdx(Number):Indexofmodelfile(thatisinternallymanagedbySimulinkCoder).
%%
%%Returns:
%%Reference(Scope)tothemodelfile.
 
%function LibGetSourceFileFromIdx(fileIdx) void
  %return ModelFiles.ModelFile[fileIdx]
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibSetSourceFileSection===========
%%Abstract:
%%Addtothecontentsofafile.Validattributesinclude:
%%
%%Banner-Setthefilebanner(comment)atthetopofthefile.
%%Includes-Appendtothe#includesection.
%%Defines-Appendtothe#definesection.
%%IntrinsicTypes-Appendtotheintrinsictypedefsection.Intrinsic
%%typesarethosethatonlydependonintrinsicCtypes.
%%PrimitiveTypedefs-Appendtotheprimitivetypedefsection.Primitive
%%typedefsarethosethatonlydependonintrinsicCtypes
%%andanytypedefspreviouslydefinedinthe
%%IntrinsicTypessection.
%%UserTop-Appendtothe"usertop"section.
%%Typedefs-Appendtothetypedefsection.Typedefscandependon
%%anypreviouslydefinedtype.
%%GuardedIncludes-Appendsaftertypedefsection.headerswhichareguardedbypreprocessors
%%arepresentinthissection
%%Enums-Appendtotheenumeratedtypessection.
%%Definitions-Appendtothedatadefinitionsection.
%%ExternData-(reserved)externdata.
%%ExternFcns-(reserved)externfunctions.
%%FcnPrototypes-(reserved)functionprototypes.
%%Declarations-Appendtothedatadeclarationsection.
%%Functions-AppendtotheCfunctionssection.
%%CompilerErrors-Appendtothe#errorsection.
%%CompilerWarnings-Appendtothe#warningsection.
%%Documentation-Appendtothedocumentation(comment)section.
%%UserBottom-Appendtothe"userbottom"section.
%%
%%CodeisemittedbySimulinkCoderintheorderinwhichitislisted
%%above.
%%
%%Examplecallsyntax(iteratingoverallfile):
%%
%%%openfiletmpBuf
%%whatever
%%%closefiletmpBuf
%%
%%%foreachfileIdx=LibGetNumSourceFiles()
%%%assignfileH=LibGetSourceFileFromIdx(fileIdx)
%%%<LibSetSourceFileSection(fileH,"SectionOfInterest",tmpBuf)>
%%%endforeach
%%
%%%assignfileH=LibCreateSourceFile("Header","Custom","foofile")
%%%<LibSetSourceFileSection(fileH,"Defines","#defineFOO5.0/n")
%%
%%Arguments:
%%fileH-Referenceorindextoafile(ScopeorNumber).
%%section-Filesectionofinterest(String).
%%value-Value(String).
 
%function LibSetSourceFileSection(fileH, section, value) void
  %if TYPE(fileH) != "Scope"
    %if TYPE(fileH) == "Number"
      %assign fileH = ModelFiles.ModelFile[fileH]
    %else
      %assign errTxt = "LibSetSourceFileSection expects a reference or " ...
        "and index to a file. It was passed a %<TYPE(fileH)>"
      %<LibReportError(errTxt)>
    %endif
  %endif
  %if section == "ExternData" || section == "ExternFcns" || section == "FcnPrototypes"
    %assign errTxt = "%<section> is reserved for Simulink Coder."
    %setcommandswitch "-v1"
    %<LibReportError(errTxt)>
  %endif
  %<SLibSetModelFileAttribute(fileH,section,value)>
%endfunction
 
%%Function:LibGetSourceFileSection===============================================================
%%Abstract:
%%Getthecontentsofafile.SeeLibSetSourceFileSectionforlistofvalid
%%sections.
%%
%%Arguments:
%%fileIndex-Referenceorindextoafile(ScopeorNumber).
%%section-Filesectionofinterest(String).
 
%function LibGetSourceFileSection(fileIdx, section) void
  %if TYPE(fileIdx) != "Number"
    %if TYPE(fileIdx) == "Scope"
      %assign fileIdx = fileIdx.Index
    %else
      %assign errTxt = "LibGetSourceFileSection expects an index or a " ...
        "reference to a file."
      %<LibReportError(errTxt)>
    %endif
  %endif
  %return LibGetModelFileAttribute(fileIdx,section)
%endfunction
 
%%Function:LibGetSourceFileIndent================================================================
%%Abstract:
%%GettheIndentflagofafile.
%%
%%Arguments:
%%fileIndex-Referenceorindextoafile(ScopeorNumber).
 
%function LibGetSourceFileIndent(fileIdx) void
  %if TYPE(fileIdx) != "Number"
    %if TYPE(fileIdx) == "Scope"
      %assign fileIdx = fileIdx.Index
    %else
      %assign errTxt = "LibGetSourceFileSection expects an index or a " ...
        "reference to a file."
      %<LibReportError(errTxt)>
    %endif
  %endif
 
  %return SLibDirectAccessGetFileAttribute(ModelFiles.ModelFile[fileIdx], "Indent")
%endfunction
 
%%Function:LibGetSourceFileShared================================================================
%%Abstract:
%%GettheSharedflagofafile.Thisissetforsharedutilityfunctions
%%beinggeneratedto_sharedutils.Notesharedtypeuseadifferentflag
%%(seeLibGetSourceFileSharedType())
%%
%%Arguments:
%%fileIndex-Referenceorindextoafile(ScopeorNumber).
 
%function LibGetSourceFileShared(fileIdx) void
  %if TYPE(fileIdx) != "Number"
    %if TYPE(fileIdx) == "Scope"
      %assign fileIdx = fileIdx.Index
    %else
      %assign errTxt = "LibGetSourceFileSection expects an index or a " ...
        "reference to a file."
      %<LibReportError(errTxt)>
    %endif
  %endif
 
  %return SLibDirectAccessGetFileAttribute(ModelFiles.ModelFile[fileIdx], "Shared")
%endfunction
 
%%Function:LibGetSourceFileSharedType============================================================
%%Abstract:
%%GettheSharedTypeflagofafile.Thisissetforsharedtypes
%%beinggeneratedto_sharedutils.Notesharedtypeuseadifferentflag
%%(seeLibGetSourceFileSharedType())
%%
%%Arguments:
%%fileIndex-Referenceorindextoafile(ScopeorNumber).
 
%function LibGetSourceFileSharedType(fileIdx) void
  %if TYPE(fileIdx) != "Number"
    %if TYPE(fileIdx) == "Scope"
      %assign fileIdx = fileIdx.Index
    %else
      %assign errTxt = "LibGetSourceFileSection expects an index or a " ...
        "reference to a file."
      %<LibReportError(errTxt)>
    %endif
  %endif
 
  %return SLibDirectAccessGetFileAttribute(ModelFiles.ModelFile[fileIdx], "SharedType")
%endfunction
 
%%Function:LibIndentSourceFile===================================================================
%%Abstract:
%%Indentafilewiththec_beautifierutility(fromwithinTLCenvironment).
%%
%%Callsyntax:
%%%<LibIndentSourceFile("foofile.c","")>
%%
%%Arguments:
%%fileName-Nameoffile(String).
%%modelName-Nameofmodel(String).(optionalargument)
%%
 
%function LibIndentSourceFile(fileName,modelName) void
  %<SLibIndentFile(fileName,modelName)>
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibSetSourceFileCodeTemplate======
%%Abstract:
%%Bydefault,*.cand*.hfilesaregeneratedwiththecodetemplates
%%specifiedintheGUI.Thisfunctionallowsyoutochangethe
%%thetemplateforafile.Usesthe"Codetemplates"enteredintothe
%%TemplatesUI.
%%
%%Note:CustomtemplatesisafeatureofEmbeddedCoder.
%%
%%Callsyntax:
%%%assigntag=LibSetSourceFileCodeTemplate(opFile,name)
%%
%%Arguments:
%%opFile(Scope)-Referencetofile
%%name(String)-Nameofthedesiredtemplate
%%
%%Returns:
%%None
 
%function LibSetSourceFileCodeTemplate(opFile,name) void
  %<SLibSetModelFileAttribute(opFile,"CodeTemplate",name)>
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibSetSourceFileOutputDirectory===
%%Abstract:
%%Bydefault,*.cand*.hfilesaregeneratedintothebuilddirectory.
%%Thisfunctionallowsyoutochangethedefaultlocation.Notethat
%%thecallerisreponsibleforspecifyingavaliddirectory.
%%
%%Callsyntax:
%%%assigntag=LibSetSourceFileOutputDirectory(opFile,dirName)
%%
%%Arguments:
%%opFile(Scope)-Referencetofile
%%dirName(String)-Nameofthedesiredoutputdirectory
%%
%%Returns:
%%None
 
%function LibSetSourceFileOutputDirectory(opFile,name) void
  %<SLibSetModelFileAttribute(opFile,"OutputDirectory",name)>
%endfunction
 
 
%%DocFunction{CodeConfigurationFunctions}:LibCallModelInitialize============
%%Abstract:
%%Returnsnecessarycodeforcallingthemodel'sinitializefunction(valid
%%forERTonly).
 
%function LibCallModelInitialize() void
  %openfile tmpFcnBuf
  %<GenerateModelInitFcnName()>(%<SLibModelFcnArgs("Initialize",TLC_TRUE,"")>);
  %closefile tmpFcnBuf
  %return tmpFcnBuf
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibCallModelStep==================
%%Abstract:
%%Returnsnecessarycodeforcallingthemodel'sstepfunction(valid
%%forERTonly).
 
%function LibCallModelStep(tid) void
  %assign rootSystem.CurrentTID =tid
  %openfile tmpFcnBuf
  %<FcnCallMdlStep(tid)>
  %closefile tmpFcnBuf
  %return tmpFcnBuf
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibCallModelTerminate=============
%%Abstract:
%%Returnsnecessarycodeforcallingthemodel'sterminatefunction(valid
%%forERTonly).
 
%function LibCallModelTerminate() void
  %openfile tmpFcnBuf
  %if IncludeMdlTerminateFcn
    %<::CompiledModel.Name>_terminate(%<SLibModelFcnArgs("Terminate",TLC_TRUE,"")>);
  %endif
  %closefile tmpFcnBuf
  %return tmpFcnBuf
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibCallSetEventForThisBaseStep====
%%Abstract:
%%Returnsnecessarycodeforcallingthemodel'sseteventsfunction(valid
%%forERTonly).
%%
%%Args:
%%buffername-Nameofthevariableusedtobuffertheevents.Forthe
%%exampleert_main.cthisis"eventFlags".
 
%function LibCallSetEventForThisBaseStep(buffername) void
  %return EventFlagsFunction("%<::CompiledModel.Name>_", buffername)
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibWriteModelData=================
%%Abstract:
%%Returnsnecessarydataforthemodel(validforERTonly).
 
%function LibWriteModelData() void
  %return SLibDeclareModelFcnArgs(TLC_TRUE)
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibSetRTModelErrorStatus==========
%%Abstract:
%%Returnsthecoderequiredsetthemodelerrorstatus
%%
%%Args:
%%str(String)-char*toaCstring
%%
%%Callsyntax:
%%%<LibSetRTModelErrorStatus("/"Overrun/"")>;
 
%function LibSetRTModelErrorStatus(str) void
  %return RTMSetErrStat(str)
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibGetRTModelErrorStatus==========
%%Abstract:
%%Returnsthecoderequiredtogetthemodelerrorstatus
%%
%%Callsyntax:
%%%<LibGetRTModelErrorStatus()>;
 
%function LibGetRTModelErrorStatus() void
  %return RTMGetErrStat()
%endfunction
 
%%DocFunction{SampleTimeFunctions}:LibIsSingleRateModel=====================
%%Abstract:
%%Returntrueifmodelissinglerateandfalseotherwise.
 
%function LibIsSingleRateModel() void
  %assign rootSystem = System[NumSystems-1]
  %return LibIsSingleRateSystem(rootSystem)
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibGetMdlSrcBaseName==============
%%Abstract:
%%Returnthebasenameofthemodel'smainsource(e.g.,model.c)file
 
%function LibGetMdlSrcBaseName() void
  %return CGMODEL_ACCESS("FileRepository.getModelFileName","ModelSourceFile")
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibGetMdlPubHdrBaseName===========
%%Abstract:
%%Returnthebasenameofthemodel'spublicheader(e.g.,model.h)file
 
%function LibGetMdlPubHdrBaseName() void
  %return CGMODEL_ACCESS("FileRepository.getModelFileName","ModelHeaderFile")
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibGetMdlPrvHdrBaseName===========
%%Abstract:
%%Returnthebasenameofthemodel'sprivateheader(e.g.,model_private.h)
%%file
 
%function LibGetMdlPrvHdrBaseName() void
  %return CGMODEL_ACCESS("FileRepository.getModelFileName","ModelPrivateFile")
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibGetMdlDataSrcBaseName==============
%%Abstract:
%%Returnthebasenameofthemodel'sdatafile(e.g.,model_data.c)
 
%function LibGetMdlDataSrcBaseName() void
  %return CGMODEL_ACCESS("FileRepository.getModelFileName","ModelDataFile")
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibGetMdlTypesHdrBaseName==============
%%Abstract:
%%Returnthebasenameofthemodeltypesfile(e.g.,model_types.h)
 
%function LibGetMdlTypesHdrBaseName() void
  %return CGMODEL_ACCESS("FileRepository.getModelFileName","ModelTypesFile")
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibGetMdlCapiHdrBaseName==============
%%Abstract:
%%Returnthebasenameofthemodelcapiheaderfile(e.g.,model_capi.h)
 
%function LibGetMdlCapiHdrBaseName() void
  %return CGMODEL_ACCESS("FileRepository.getModelFileName","ModelCapiHdrFile")
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibGetMdlCapiSrcBaseName==============
%%Abstract:
%%Returnthebasenameofthemodelcapisourcefile(e.g.,model_capi.c)
 
%function LibGetMdlCapiSrcBaseName() void
  %return CGMODEL_ACCESS("FileRepository.getModelFileName","ModelCapiSrcFile")
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibGetMdlCapiHostHdrBaseName==========
%%Abstract:
%%Returnthebasenameofthemodelcapihostheaderfile(e.g.,model_host_capi.h)
 
%function LibGetMdlCapiHostHdrBaseName() void
  %return CGMODEL_ACCESS("FileRepository.getModelFileName","ModelCapiHostHdrFile")
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibGetMdlTestIfHdrBaseName============
%%Abstract:
%%Returnthebasenameofthemodeltestinterfaceheaderfile(e.g.,model_testinterface.h)
 
%function LibGetMdlTestIfHdrBaseName() void
  %return CGMODEL_ACCESS("FileRepository.getModelFileName","ModelTestIfHdrFile")
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibGetMdlTestIfSrcBaseName==============
%%Abstract:
%%Returnthebasenameofthemodeltestinterfacesourcefile(e.g.,model_testinterface.c)
 
%function LibGetMdlTestIfSrcBaseName() void
  %return CGMODEL_ACCESS("FileRepository.getModelFileName","ModelTestIfSrcFile")
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibGetDataTypeTransHdrBaseName=========
%%Abstract:
%%Returnthebasenameofthedatatypetransitionfile(e.g.,model_dt.h)forcode
%%generation'sRealTimeandEmbedded-ccodeformats
 
%function LibGetDataTypeTransHdrBaseName() void
  %return CGMODEL_ACCESS("FileRepository.getModelFileName","ModelExtModeDataInterfaceFile")
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibGetModelDotCFile==============
%%Abstract:
%%Gettherecordforthemodel.cfile.Additionalcodecanthenbecached
%%usingLibSetSourceFileSection().
%%
%%Callsyntax:
%%%assignsrcFile=LibGetModelDotCFile()
%%%<LibSetSourceFileSection(srcFile,"Functions",mybuf)>
%%
%%Returns:
%%Returnsthemodel.csourcefilerecord.
 
%function LibGetModelDotCFile() void
  %assign modelSrcName = LibGetMdlSrcBaseName()
  %return LibCreateSourceFile("Source","Simulink",modelSrcName)
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibGetModelDotHFile==============
%%Abstract:
%%Gettherecordforthemodel.hfile.Additionalcodecanthenbecached
%%usingLibSetSourceFileSection().
%%
%%Callsyntax:
%%%assignhdrFile=LibGetModelDotHFile()
%%%<LibSetSourceFileSection(hdrFile,"Functions",mybuf)>
%%
%%Returns:
%%Returnsthemodel.hsourcefilerecord.
 
%function LibGetModelDotHFile() void
  %assign modelHdrName = LibGetMdlPubHdrBaseName()
  %return LibCreateSourceFile("Header","Simulink",modelHdrName)
%endfunction
 
%%Thisistemporarycodetosupporttimingserviceincodegen.Willberemovedlater.
%%Seeg2060510.
%function LibGetRTEHeaderFileName() void
  %return "rte"
%endfunction
 
%%Thisistemporarycodetosupporttimingserviceincodegen.Willberemovedlater.
%%Seeg2060510.
%function LibGetRTESourceFileName() void
  %return "rte"
%endfunction
 
%%Function:LibIsSingleTasking====================================================================
%%Abstract:
%%Returntrueifthemodelisconfiguredforsingletaskingexecutionand
%%falseotherwise(i.e.,multitasking).
 
%function LibIsSingleTasking() void
  %return SLibSingleTasking()
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibWriteModelInput================
%%Abstract:
%%Returnthecodenecessarytowritetoaparticularrootinput(i.e.,a
%%modelinportblock).ThisfunctionisvalidforERTonly,andnotvalid
%%forreferencedmodels.
%%
%%Args:
%%tid(Number):Taskidentifier(0isfastestrateandnistheslowest)
%%rollThreshold:Widthofsignalbeforewrappinginaforloop.
 
%function LibWriteModelInput(tid,rollThreshold) void
  %if IsModelReferenceTarget()
    %assign errTxt = "LibWriteModelInput may not be called for referenced " + ...
      "models; you may wish to guard its invocation with !IsModelReferenceTarget()."
    %<LibReportError(errTxt)>
  %endif
  %openfile tmpFcnBuf
  %if MultiInstanceERTCode && !RootIOStructures
    %assign localUQualifier = "_"
  %else
    %assign localUQualifier = "."
  %endif
  %foreach idx = ExternalInputs.NumExternalInputs
    %assign extInp = ::CompiledModel.ExternalInputs.ExternalInput[idx]
    %with extInp
      %if TID == tid
        %assign rhs = "your_value"
        /* InportID: %<idx>, TaskID: %<tid> */
        %assign id = LibGetRecordIdentifier(extInp)
        %assign optStr = ""
        %if StorageClass == "Auto"
          %assign optStr = "%<LibGetExternalInputStruct()>%<localUQualifier>"
        %endif
        %if StorageClass == "ImportedExternPointer"
          %assign id = "%<id>_value"
        %endif
        %assign portWidth = LibGetRecordWidth(extInp)
        %assign isComplex = LibGetRecordIsComplex(extInp)
        %if portWidth == 1
          %if isComplex
            %<optStr>%<id>.re = %<rhs>;
            %<optStr>%<id>.im = %<rhs>;
          %else
            %<optStr>%<id> = %<rhs>;
          %endif
        %elseif portWidth < rollThreshold
          %foreach sigIdx = portWidth
            %if isComplex
              %<optStr>%<id>[%<sigIdx>].re = %<rhs>;
              %<optStr>%<id>[%<sigIdx>].im = %<rhs>;
            %else
              %<optStr>%<id>[%<sigIdx>] = %<rhs>;
            %endif
          %endforeach
        %else %% portWidth > rollThreshold
          {
            int i = 0;
            for(i = 0; i < %<portWidth>; i++) {
              %if isComplex
                %<optStr>%<id>[i].re = %<rhs>;
                %<optStr>%<id>[i].im = %<rhs>;
              %else
                %<optStr>%<id>[i] = %<rhs>;
              %endif
            }
          }
        %endif
      %endif
    %endwith %% extInp
  %endforeach
  %closefile tmpFcnBuf
  %return tmpFcnBuf
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibWriteModelOutput===============
%%Abstract:
%%Returnthecodenecessarytowritetoaparticularrootoutput(i.e.,a
%%modeloutportblock).ThisfunctionisvalidforERTonly,andnotvalid
%%forreferencedmodels.
%%
%%Args:
%%tid(Number):Taskidentifier(0isfastestrateandnistheslowest)
%%rollThreshold:Widthofsignalbeforewrappinginaforloop.
 
%function LibWriteModelOutput(tid,rollThreshold) void
  %if IsModelReferenceTarget()
    %assign errTxt = "LibWriteModelOutput may not be called for referenced " + ...
      "models; you may wish to guard its invocation with !IsModelReferenceTarget()."
    %<LibReportError(errTxt)>
  %endif
  %openfile tmpFcnBuf
  %if MultiInstanceERTCode && !RootIOStructures
    %assign localYQualifier = "_"
  %else
    %assign localYQualifier = "."
  %endif
  %assign lhs = "your_variable"
  %foreach idx = ExternalOutputs.NumExternalOutputs
    %assign extOut = ExternalOutputs.ExternalOutput[idx]
    %assign sysIdx = extOut.Block[0]
    %assign blkIdx = extOut.Block[1]
    %assign outportBlock = System[sysIdx].Block[blkIdx]
    %with System[sysIdx]
      %with outportBlock
        %if tid == SLibGetNumericTID(outportBlock)
          %assign portWidth = LibBlockInputSignalWidth(0)
          %assign id = LibGetRecordIdentifier(outportBlock)
          /* OutportID: %<idx>, TaskID: %<tid> */
          %if portWidth == 1
            %if SLibExternalOutputIsVirtual(outportBlock)
              %<lhs> = %<LibBlockInputSignal(0, "", "", 0)>;
            %else
              %<lhs> = %<LibGetExternalOutputStruct()>%<localYQualifier>%<id>;
            %endif
          %elseif portWidth < rollThreshold
            %foreach sigIdx = portWidth
              %if SLibExternalOutputIsVirtual(outportBlock)
                %<lhs> = %<LibBlockInputSignal(0, "", "", sigIdx)>;
              %else
                %<lhs> = %<LibGetExternalOutputStruct()>%<localYQualifier>%<id>[%<sigIdx>];
              %endif
            %endforeach
          %else %% portWidth > rollThreshold
            {
              int i = 0;
              for(i = 0; i < %<portWidth>; i++) {
                %if SLibExternalOutputIsVirtual(outportBlock)
                  %<lhs>[i] = %<LibBlockInputSignal(0, "i", "", 0)>;
                %else
                  %<lhs>[i] = %<LibGetExternalOutputStruct()>%<localYQualifier>%<id>[i];
                %endif
              }
            }
          %endif
        %endif
      %endwith %% outportBlock
    %endwith %% System[sysIdx]
  %endforeach
  %closefile tmpFcnBuf
  %return tmpFcnBuf
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibWriteModelInputs===============
%%Abstract:
%%Returnthecodenecessarytowritetorootinputs(i.e.,allthe
%%modelinportblocks).ThisfunctionisvalidforERTonly,andnotvalid
%%forreferencedmodels.
 
%function LibWriteModelInputs() void
  %if IsModelReferenceTarget()
    %assign errTxt = "LibWriteModelInputs may not be called for referenced " + ...
      "models; you may wish to guard its invocation with !IsModelReferenceTarget()."
    %<LibReportError(errTxt)>
  %endif
  %openfile varbufs
  %foreach tid = LibNumRuntimeExportedRates()
    %<LibWriteModelInput(tid,RollThreshold)>/
  %endforeach
  %closefile varbufs
 
  %if WHITE_SPACE(varbufs)
    %return ""
  %else
    %openfile tmpFcnBuf
    #if 0
    %<varbufs>/
    #endif
    %closefile tmpFcnBuf
    %return tmpFcnBuf
  %endif
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibWriteModelOutputs==============
%%Abstract:
%%Returnthecodenecessarytowritetorootoutputs(i.e.,allthe
%%modeloutportblocks).ThisfunctionisvalidforERTonly,andnotvalid
%%forreferencedmodels.
 
%function LibWriteModelOutputs() void
  %if IsModelReferenceTarget()
    %assign errTxt = "LibWriteModelOutputs may not be called for referenced " + ...
      "models; you may wish to guard its invocation with !IsModelReferenceTarget()."
    %<LibReportError(errTxt)>
  %endif
  %openfile varbufs
  %foreach tid = LibNumRuntimeExportedRates()
    %<LibWriteModelOutput(tid,RollThreshold)>/
  %endforeach
  %closefile varbufs
 
  %if WHITE_SPACE(varbufs)
    %return ""
  %else
    %openfile tmpFcnBuf
    #if 0
    %<varbufs>/
    #endif
    %closefile tmpFcnBuf
    %return tmpFcnBuf
  %endif
%endfunction
 
%%DocFunction{SampleTimeFunctions}:LibNumDiscreteSampleTimes================
%%Abstract:
%%Returnthenumberofdiscretesampletimesinthemodel
 
%function LibNumDiscreteSampleTimes() void
  %return ::CompiledModel.NumSynchronousSampleTimes - LibIsContinuous(0)
%endfunction
 
%function LibGetTID01EQ() void
  %return ::CompiledModel.FixedStepOpts.TID01EQ
%endfunction
 
%function LibGetSampleTimePeriodAndOffset(tid, idx) void
  %return ::CompiledModel.SampleTime[tid].PeriodAndOffset[idx]
%endfunction
 
 
%%DocFunction{SampleTimeFunctions}:LibNumRuntimeExportedRates================
%%Abstract:
%%Returnthenumberofruntimeexportedratesinthemodel
 
%function LibNumRuntimeExportedRates() void
  %return ::CompiledModel.NumRuntimeExportedRates
%endfunction
 
%%DocFunction{SampleTimeFunctions}:LibNumSynchronousSampleTimes================
%%Abstract:
%%Returnthenumberofsynchronoussampletimesinthemodel
 
%function LibNumSynchronousSampleTimes() void
  %return ::CompiledModel.NumSynchronousSampleTimes
%endfunction
 
%%DocFunction{SampleTimeFunctions}:LibNumAsynchronousSampleTimes============
%%Abstract:
%%Returnthenumberofasynchronoussampletimesinthemodel
 
%function LibNumAsynchronousSampleTimes() void
  %return ::CompiledModel.NumAsynchronousSampleTimes
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibAddSourceFileCustomSection=====
%%Abstract:
%%Addacustomsectiontoasourcefile.Youmustassociateacustom
%%sectionwithoneofthebuilt-insections:Includes,Defines,Types,
%%Enums,Definitions,Declarations,Functions,orDocumentation.
%%
%%Noactionifthesectionalreadyexists,excepttoreportanerror
%%ifainconsistentbuilt-insectionassociationisattempted.
%%
%%OnlyavailablewithEmbeddedCoder.
%%
%%Arguments:
%%file-Sourcefilereference(Scope)
%%builtInSection-Nameoftheassociatedbuilt-insection(String)
%%newSection-Nameofthenew(custom)section(String)
 
%function LibAddSourceFileCustomSection(file,builtInSection,newSection) void
 
  %if !SLibIsERTTarget()
    %assign errTxt = "LibAddSourceFileCustomSection is only available with " ...
      "ERT-based (Embedded Coder) targets."
    %<LibReportError(errTxt)>
  %endif
 
  %
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibIsSourceFileCustomSection=====
%%Abstract:
%%Returnswhetherasectionisacustomsectioninthespecifiedfile.
%%
%%OnlyavailablewithEmbeddedCoder.
%%
%%Arguments:
%%file-Sourcefilereference(Scope)
%%sectionName-Nameofthe(custom)section(String)
%function LibIsSourceFileCustomSection(file, sectionName) void
  %return IS_CUSTOM_SECTION(file.Index, sectionName)
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibSetSourceFileVariantCustomSection=====
%%Abstract:
%%SetacustomvariantsectionpreviouslycreatedwithLibAddSourceFileCustomSection.
%%
%%OnlyavailablewithEmbeddedCoder.
%%
%%Arguments:
%%file-Sourcefilereferenceorindex(ScopeorNumber)
%%attrib-Nameofcustomsection(String)
%%value-valuetobeappendedtosection(String)
 
%function LibSetSourceFileVariantCustomSection(file,attrib,value) void
  %if TYPE(file) != "Scope"
    %if TYPE(file) == "Number"
      %assign file = ModelFiles.ModelFile[file]
    %else
      %assign errTxt = "LibSetSourceFileCustomSection expect a " ...
        "reference or an index to a file. It was passed a: " ...
        "%<TYPE(file)>"
      %<LibReportError(errTxt)>
    %endif
  %endif
 
  %if ISEMPTY(value)
    %assign value = ""
  %endif
  %
%endfunction
 
 
 
 
%%DocFunction{CodeConfigurationFunctions}:LibSetSourceFileCustomSection=====
%%Abstract:
%%SetacustomsectionpreviouslycreatedwithLibAddSourceFileCustomSection.
%%
%%OnlyavailablewithEmbeddedCoder.
%%
%%Arguments:
%%file-Sourcefilereferenceorindex(ScopeorNumber)
%%attrib-Nameofcustomsection(String)
%%value-valuetobeappendedtosection(String)
 
%function LibSetSourceFileCustomSection(file,attrib,value) void
  %if TYPE(file) != "Scope"
    %if TYPE(file) == "Number"
      %assign file = ModelFiles.ModelFile[file]
    %else
      %assign errTxt = "LibSetSourceFileCustomSection expect a " ...
        "reference or an index to a file. It was passed a: " ...
        "%<TYPE(file)>"
      %<LibReportError(errTxt)>
    %endif
  %endif
 
  %if ISEMPTY(value)
    %assign value = ""
  %endif
  %
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibGetSourceFileCustomSection=====
%%Abstract:
%%GetacustomsectionpreviouslycreatedwithLibAddSourceFileCustomSection.
%%
%%Arguments:
%%file-Sourcefilereferenceorindex(ScopeorNumber)
%%attrib-Nameofcustomsection(String)
 
%function LibGetSourceFileCustomSection(file,attrib) void
  %if TYPE(file) != "Scope"
    %if TYPE(file) == "Number"
      %assign file = ModelFiles.ModelFile[file]
    %else
      %assign errTxt = "LibGetSourceFileCustomSection expect a " ...
        "reference or an index to a file. It was passed a: " ...
        "%<TYPE(file)>"
    %endif
  %endif
 
  %assign retVal = GET_CUSTOM_SECTION_CONTENT(file.Index, attrib)
  %return retVal
%endfunction
 
%%=============================================================================
%%AddModelFilesto::CompiledModel
%%=============================================================================
 
%with ::CompiledModel
  %addtorecord ::CompiledModel /
  ModelFiles { /
  NumModelFiles 0 /
  NumSupportFiles 0 /
  ComplianceLevel -1 /
}
%endwith %% ::CompiledModel
 
 
%%=============================================================================
%%Privatefunctions(MathWorksuseonly)
%%=============================================================================
 
%function SLibGetTag(type, name) void
 
  %% In case name contains . and other funny char
  %assign name = LibConvertNameToIdentifier(name)
 
  %switch type
    %case "SystemHeader"
      %assign tag = "%<name>_h"
      %break
    %case "SystemBody"
      %assign tag = "%<name>_c"
      %break
    %default
      %assign errTxt = "unknown type: %<type>"
      %<LibReportFatalError(errTxt)>
  %endswitch
  %return tag
%endfunction
 
%function SLibSectionIsInFileContents(fileRec, sectionName) void
  %switch sectionName
    %case "Banner"
    %case "Includes"
    %case "ModelTypesIncludes"
    %case "ModelTypesDefines"
    %case "Defines"
    %case "ModelTypesTypedefs"
    %case "IntrinsicTypes"
    %case "PrimitiveTypedefs"
    %case "UserTop"
    %case "Typedefs"
    %case "GuardedIncludes"
    %case "Enums"
    %case "Definitions"
    %case "ExternData"
    %case "ExternFcns"
    %case "FcnPrototypes"
    %case "Declarations"
    %case "Functions"
    %case "CompilerErrors"
    %case "CompilerWarnings"
    %case "Documentation"
    %case "UserBottom"
      %return TLC_TRUE
    %default
      %return TLC_FALSE
  %endswitch
%endfunction
 
%%Function:SLibSetSourceFileCustomTokenInUse=====================================================
%%Abstract:
%%Thertw_expand_templatescriptidentifiesandsetcustomstokenswith
%%thisfunction.Thisallowscustomsectionstobeplacedinthe
%%appropriatesectionwhenatokenismissing.
%%
%function SLibSetSourceFileCustomTokenInUse(fileIdx,token) void
  %
%endfunction
 
%%Function:LibGetFileRecordName==================================================================
%%Abstract:
%%Thisfunctiontakesamodelfilerecordandreturnsthefilename
%%(includingpath)withoutthefileextension.Toretrievethefilename
%%withfileextension(includingpath),callLibGetModelFileAttributeand
%%passin"Name"asthefileattribute.
%%
%function LibGetFileRecordName(fileRec) void
  %return GET_FILE_ATTRIBUTE(fileRec.Index, "NameWithoutExtension")
%endfunction
 
%%Function:FcnAppendMissingTokens================================================================
%%Abstract:
%%Sincecustomsectionscanbeaddedwithoutacorrespondingtokenin
%%thecodetemplatefile,weneedtogracefullyaccomodatemissingtokens.
%%Ifthecustomtokenismissing,it'splacedjustbelowit'sregistered
%%built-insection.
%%
%function FcnAppendMissingTokens(opFile,section) void
  %
%endfunction
 
 
%%Checkifmodelfileexists
%function SLibDoesModelFileExist(type,name) void
  %assign fullName = SLibGetFullFileName(name, type)
  %assign fileIdx = SOURCE_FILE_EXISTS(fullName)
  %if fileIdx >= 0
    %assign mf = ModelFiles.ModelFile[fileIdx]
    %return mf
  %else
    %return ""
  %endif
%endfunction
 
%%CheckifthefileisanImportedsharedtypefile
%function SLibFileContainsImportedSharedType(fileIdx) void
  %assign filter = LibGetModelFileAttribute(fileIdx,"Filter")
  %assign isSharedType = LibGetSourceFileSharedType(fileIdx)
  %assign isImportedSharedTypeFile = filter && isSharedType
  %return isImportedSharedTypeFile
%endfunction
 
%%FunctionSLibAddGeneratedFileToList===================================
%%Abstract:
%%AddsspecifiedfiletoTLCglobalvariableGeneratedFileList
%%
%function SLibAddGeneratedFileToList(filename, category, type, dir) void
  %assign tmpMdlHeaderFileName = LibGetMdlPubHdrBaseName()
  %assign tmpMdlSourceFileName = LibGetMdlSrcBaseName()
  %% Model source and header files may be tagged wrongly, such as "data" group. Correct them to "model".
  %if (type == "header" && FEVAL("strncmp", filename, tmpMdlHeaderFileName + ".", SIZE(tmpMdlHeaderFileName,1)+1)) || ...
    (type == "source" && FEVAL("strncmp", filename, tmpMdlSourceFileName + ".", SIZE(tmpMdlSourceFileName,1)+1))
    %assign category = "model"
  %endif
  %assign errTxt = FEVAL("coder.internal.slcoderReport", "addFileInfo", ...
    LibGetModelName(), filename, category, type, dir)
%endfunction %%SLibAddGeneratedFileToList
 
 
%%Function:SLibAddModelFile======================================================================
%%Createanewmodelfile,orreturnitsexistingreference.
%%
%%"type"isthetypeoffile,e.g."SystemBody"(.cfile)or"SystemHeader"(.hfile)
%%"creator"istypically"Simulink".
%%"name"isthebasenameofthefileifwritingtothebuilddirectory,
%%andisthefullpathifwritingtosomeotherdirectory(e.g._sharedutils)
%%
%%Forexample:Buildingmodel"foo"tobuilddirectory./foo_ert_rtw/.
%%Ifcreatingsourcefile"foo.h"tobuilddirectory,then:
%%type="SystemHeader",creator="Simulink",
%%name="foo",basename="foo".
%%Ifcreatingsharedtype"a.h"inthesharedutilitiesdir:
%%type="SystemHeader",creator="Simulink",
%%name="/_sharedutils/a",basename="a"
%%
%function SLibAddModelFile(type, creator, name) void
  %return SLibAddModelFileWithBasename(type, creator, name, name)
%endfunction
 
%function SLibGetFullFileName(name, type)
  %assign headerExt = ".h"
  %assign sourceExt = "." + ::LangFileExt
  %assign extension = type == "SystemHeader" ? headerExt : sourceExt
  %return "%<name>%<extension>"
%endfunction
 
%%Function:SLibSynchronizeFileRepWithFileRecords
%%
%%ThisfunctionsynchronizesthemodelfilerecordsinsideCompiledModel
%%withtherecordsinsidethefilerepository.Thisneedstobecalled
%%atthebeginningofTLCandafteranyadditionalfilesareaddedto
%%thefilerepositoryoutsideofTLC.
%function SLibSynchronizeFileRepWithFileRecords() void
 
  %assign numFileRecords = ::CompiledModel.ModelFiles.NumModelFiles
 
  %% Iterate over each file in the repository. Add file records for
  %% additional files
  %foreach fileIdx = LibGetNumSourceFiles()
    %if fileIdx >= numFileRecords
      %addtorecord ::CompiledModel.ModelFiles /
      ModelFile { /
      Index fileIdx /
    }
    %assign ::CompiledModel.ModelFiles.NumModelFiles = ::CompiledModel.ModelFiles.NumModelFiles + 1
 
    %assign type = GET_FILE_ATTRIBUTE(fileIdx, "Type")
    %% Include the code template from "rtw_code.tlc" (or custom template)
    %if ERTCustomFileBanners
      %assign template = (type == "SystemBody") ? ...
        ERTSrcFileBannerTemplate : ERTHdrFileBannerTemplate
    %else
      %assign template = "rtw_code.tlc"
    %endif
 
    %assign success = SET_FILE_ATTRIBUTE(fileIdx, "CodeTemplate", template)
  %endif
%endforeach
%endfunction
 
%%Function:SLibAssignCustomCodeTemplates
%%IterateovereachfileinDataObjectUsageVectorandcheckiftheyare
%%custom.Forcustomfiles,retrievethefileIdxandsettheCodeTemplate
%%objectappropriately
%function SLibAssignCustomCodeTemplates() void
  %if LibGetNumSourceFiles() > 0 && ISFIELD(::CompiledModel,"DataObjectUsage")
    %foreach fileIdx = ::CompiledModel.DataObjectUsage.NumFiles[0]
      %assign dataObjectFileRec = ::CompiledModel.DataObjectUsage.File[fileIdx]
      %if dataObjectFileRec.IsCustom == "yes"
        %assign type = dataObjectFileRec.Type
        %if type == "header"
          %assign type = "SystemHeader"
        %elseif type == "source"
          %assign type = "SystemBody"
        %endif
 
        %assign modelFile = SLibDoesModelFileExist(type, dataObjectFileRec.Name)
        %if !ISEMPTY(modelFile) && !WHITE_SPACE(modelFile)
          %if dataObjectFileRec.Type == "header"
            %<LibSetSourceFileCodeTemplate(modelFile, ERTDataHdrFileTemplate)>
          %else
            %<LibSetSourceFileCodeTemplate(modelFile, ERTDataSrcFileTemplate)>
          %endif
        %endif
      %endif
    %endforeach
  %endif
%endfunction
 
%function FcnReturnExistingFile(fileIndex, type, creator, name) void
  %assign mf = ::CompiledModel.ModelFiles.ModelFile[fileIndex]
  %assign existingCreator = SLibDirectAccessGetFileAttribute(mf, "Creator")
  %assign existingGroup = SLibDirectAccessGetFileAttribute(mf, "Group")
  %assign existingType = SLibDirectAccessGetFileAttribute(mf, "Type")
 
  %if creator != existingCreator
    %if type == "SystemHeader" && existingGroup == "utility" && existingType == "SystemHeader"
      %<SLibReportErrorWithIdAndArgs("RTW:tlc:ErrWhenGenSharedDataConflictModelFile", "%<name>"+".h")>
    %else
      %assign errTxt = "%<creator> is attempting to create " ...
        "file %<name>, however, this file was already created " ...
        "by %<existingCreator>."
      %<LibReportFatalError(errTxt)>
    %endif
  %else
    %return mf
  %endif
%endfunction
 
%%Function:SLibAddModelFileWithBasename==========================================================
%%Createanewmodelfile,orreturnitsexistingreference.
%%
%%"type"isthetypeoffile,e.g."SystemBody"(.cfile)or"SystemHeader"(.hfile)
%%"creator"istypically"Simulink".
%%"name"isthebasenameofthefileifwritingtothebuilddirectory,
%%andisthefullpathifwritingtosomeotherdirectory(e.g._sharedutils)
%%'basename'isalwaysthebasenameofthefile
%%
%%Forexample:Buildingmodel"foo"tobuilddirectory./foo_ert_rtw/.
%%Ifcreatingsourcefile"foo.h"tobuilddirectory,then:
%%type="SystemHeader",creator="Simulink",
%%name="foo",basename="foo".
%%Ifcreatingsharedtype"a.h"inthesharedutilitiesdir:
%%type="SystemHeader",creator="Simulink",
%%name="/_sharedutils/a",basename="a"
%%
%function SLibAddModelFileWithBasename(type, creator, name, basename) void
 
  %% Include the code template from "rtw_code.tlc" (or custom template)
  %if ERTCustomFileBanners
    %assign template = (type == "SystemBody") ? ...
      ERTSrcFileBannerTemplate : ERTHdrFileBannerTemplate
  %else
    %assign template = "rtw_code.tlc"
  %endif
 
  %assign fullName = SLibGetFullFileName(name, type)
 
  %assign findIdx = SOURCE_FILE_EXISTS(fullName)
  %if findIdx == -1 && type == "SystemHeader"
    %assign findIdx = SOURCE_FILE_EXISTS("%<basename>.h")
  %endif
  %if findIdx != -1
    %return FcnReturnExistingFile(findIdx, type, creator, name)
  %endif
 
  %% This creates a new file in the file repository
  %assign fileIdx = CREATE_SOURCE_FILE(fullName)
  %% Now, set the template, type and creator attributes
  %assign success = SET_FILE_ATTRIBUTE(fileIdx, "Type", type)
  %assign success = SET_FILE_ATTRIBUTE(fileIdx, "Creator", creator)
  %assign success = SET_FILE_ATTRIBUTE(fileIdx, "CodeTemplate", template)
 
  %% If the user has specified a different base name, then use that
  %if name != basename
    %assign success = SET_FILE_ATTRIBUTE(fileIdx, "BaseName", basename)
  %endif
 
  %return LibUpdateCompiledModelFiles(fileIdx)
%endfunction
 
%%Function:UpdateCompiledModelFiles
%%Abstract:
%%Addsthenewlycreatedfiletothecompiledmodelfilesrecord
%function LibUpdateCompiledModelFiles(fileIdx) void
  %% For backwards compatibility, create a file record that just uses the
  %% index. Operations will retrieve this record, and the use the index to
  %% access the file repository
  %addtorecord ::CompiledModel.ModelFiles /
  ModelFile { /
  Index fileIdx /
}
 
  %assign ::CompiledModel.ModelFiles.NumModelFiles = ::CompiledModel.ModelFiles.NumModelFiles + 1
  %return ::CompiledModel.ModelFiles.ModelFile[fileIdx]
%endfunction
 
%%Function:SLibSetContentAttribute===============================================================
%%Abstract:
%%AddstotheContentsfieldofafile
%%
%%Arguments:
%%opFile-thefileweareaddingto(see::CompiledModel.ModelFilesstructureabove)
%%c-specifiestheContentssection.Contents
%%attrib-thesubfieldoftheContentstoaddto,e.g.IncludesorTypedefsor...
%%value-thetexttoadd
 
%function SLibSetContentsAttribute(opFile, c, attrib, value) void
  %if !WHITE_SPACE(value)
    %assign success = SET_FILE_ATTRIBUTE(opFile.Index, attrib, value)
  %endif
%endfunction
 
%%Function:SLibDirectAccessGetFileAttribute======================================================
%%Abstract:
%%Returnsthespecifiedattributeofafiledirectly.Thisdiffersfrom
%%LibGetModelFileAttributeinthatLibGetModelFileAttributemayformatthedata
%%returned,whilethisfunctionreturnstherawvalueoftheattribute.
%%
%%Arguments:
%%file-thefileweareaccessing
%%attrib-theattributename(e.g.WrittenToDisk,RequiredIncludes)
%function SLibDirectAccessGetFileAttribute(file, attrib) void
  %return GET_FILE_ATTRIBUTE(file.Index, attrib)
%endfunction
 
%%Function:SLibDirectAccessSetFileAttribute======================================================
%%Abstract:
%%Setsspecifiedattributeofafiledirectly.Thisdiffersfrom
%%SLibSetModelFileAttributeinthatSLibSetModelFileAttributemayformatthedata
%%beforesettingtheattribute,whilethisfunctionsetstherawvalueoftheattribute.
%%
%%Arguments:
%%file-thefileweareaccessing
%%attrib-theattributename(e.g.WrittenToDisk,RequiredIncludes)
%%value-theattributevalue
%function SLibDirectAccessSetFileAttribute(file, attrib, value) void
  %assign success = SET_FILE_ATTRIBUTE(file.Index, attrib, value)
%endfunction
 
%%Function:SLibDirectAccessGetFileContent========================================================
%%Abstract:
%%Returnsthespecifiedcontentofafiledirectly.Thisdiffersfrom
%%LibGetModelFileAttributeinthatLibGetModelFileAttributemayformatthedata
%%returned,whilethisfunctionreturnstherawvalueofthecontent.
%%
%%Arguments:
%%file-thefileweareaccessing
%%attrib-thecontentsectionname(e.g.Includes,Functions)
%function SLibDirectAccessGetFileContent(file, attrib) void
  %return GET_FILE_ATTRIBUTE(file.Index, attrib)
%endfunction
 
%%Function:SLibDirectAccessSetFileContent========================================================
%%Abstract:
%%Setsspecifiedcontentssectionofafiledirectly.Thisdiffersfrom
%%SLibSetModelFileAttributeinthatSLibSetModelFileAttributemayformatthedata
%%beforesettingthecontent,whilethisfunctionsetstherawvalueofthecontent.
%%
%%Arguments:
%%file-thefileweareaccessing
%%attrib-thecontentsectionname(e.g.Includes,Functions)
%%value-thecontentvalue
%function SLibDirectAccessSetFileContent(file, attrib, value) void
  %assign success = SET_FILE_ATTRIBUTE(file.Index, attrib, value)
%endfunction
 
%%ThisutilityfunctionappendsadditionalfilestoRequiredIncludes
%function FcnAddCoderTypesFilesToRequiredIncludes(opFile) void
  %if SLibGetModelFileDeferredIncludeCoderTypes(opFile)
    %if LibGetModelFileAttribute(opFile.Index, "Group") == "utility"
      %assign files = []
      %assign files = files + SLibCoderTypesFilename()
      %assign rtwCtx = ::CompiledModel.RTWContext
      %assign fileBaseName = SLibDirectAccessGetFileAttribute(opFile, "BaseName")
 
      %assign isMultiword = SLibIsHostBasedSimulationTarget() ? ...
        TLC_TRUE : ...
        FEVAL("rtwprivate", "retrieveMultiWordUtilitiesAndFunctions", "%<MasterSharedCodeManagerFile>", rtwCtx, fileBaseName)
      %if isMultiword
        %assign files = files + SLibCoderMultiwordTypesFilename()
      %endif
      %if SLibDeclareHalfPrecisionUsage()
        %assign files = files + SLibCoderHalfTypeHdrFilename()
      %endif
    %else
      %assign files = SLibUsedCoderTypesFilenames()
    %endif
    %foreach fIdx = SIZE(files, 1)
      %<SLibSetModelFileAttribute(opFile, "RequiredIncludes", files[fIdx])>
    %endforeach
  %endif
%endfunction
 
%function LibWriteFileSectionToDisk(fileIndex, attrib) Output
  %assign opFile = ModelFiles.ModelFile[fileIndex]
  %if attrib == "Includes"
    %<FcnAddCoderTypesFilesToRequiredIncludes(opFile)>
  %endif
 
  %
%endfunction
 
%function LibClearFileSectionContents(fileIndex,attrib) void
  %if TYPE(fileIndex) != "Number"
    %if TYPE(fileIndex) == "Scope"
      %assign fileIndex = fileIndex.Index
    %else
      %assign errTxt = "LibClearFileSectionContents expects an index or a" ...
        " reference to a file."
      %<LibReportError(errTxt)>
    %endif
  %endif
  %
%endfunction
 
%%Function:SLibSetModelFileAttribute=============================================================
%%Abstract:
%%AddstoeitherthefileContentsortosomeothertop-levelsection
%%ofthefile(e.g.RequiredIncludes)
%%
%%Arguments:
%%opFile-thefileweareaddingto(see::CompiledModel.ModelFilesstructureabove)
%%attrib-canspecifyatop-levelsection(fieldname)ofthefiletoaddto
%%(e.g.RequiredIncludes),orcanspecifyasub-section(fieldname)of
%%Contents(e.g.IncludesorTypedefsor...).
%%value-thetexttoadd
%function SLibSetModelFileAttribute(opFile,attrib,value) void
  %% After LibClearModelFileBuffers() is called, Contents will not
  %% exist. However, still allow access to SystemsInFile,
  %% RequiredIncludes, NeedsModelHeader.
  %assign c = ""
  %if attrib == "Filter"
    %assert (value == 1)
  %elseif attrib == "WrittenToDisk"
    %assert (value == TLC_TRUE)
  %endif
 
  %assign success = SET_FILE_ATTRIBUTE(opFile.Index, attrib, value)
%endfunction
 
 
%%Function:SLibSetModelFileAttributeWithRequiredInclude==========================================
%%Abstract:
%%LikeSLibSetModelFileAttribute,butthisversionalsoaddsaspecifiedinclude
%%(currentlyalways"rtwtypes.h")totheRequiredIncludessection
%%
%%Arguments:
%%opFile-thefileweareaddingto(see::CompiledModel.ModelFilesstructureabove)
%%attrib-canspecifyatop-levelsection(fieldname)ofthefiletoaddto
%%(e.g.RequiredIncludes),orcanspecifyasub-section(fieldname)of
%%Contents(e.g.IncludesorTypedefsor...).
%%value-thetexttoadd
%%incl-theincludetoaddtoRequiredIncludes.Thecallershouldjust
%%passtheincludefilename,e.g."rtwtypes.h",andlateronthe
%%emittingcodewillwrapthatinanincludedirective
%%toturnitinto:#include"rtwtypes.h"
 
%function SLibSetModelFileAttributeWithRequiredInclude(opFile,attrib,value,incl) void
  %% Call the underlying function twice, first to add to the RequiredIncludes,
  %% then to add to the given section. But note we're careful not to add the
  %% RequiredIncludes if we're not actually adding anything (i.e. if value is empty).
  %%
  %if !WHITE_SPACE(value) && !WHITE_SPACE(incl)
    %<SLibSetModelFileAttribute(opFile, "RequiredIncludes", incl)>
  %endif
  %<SLibSetModelFileAttribute(opFile, attrib, value)>
%endfunction
 
 
%function SLibGetModelFileIndent(opFile) void
  %return SLibDirectAccessGetFileAttribute(opFile, "Indent")
%endfunction
 
%function SLibSetModelFileIndent(opFile, setting) void
  %<SLibDirectAccessSetFileAttribute(opFile, "Indent", setting)>
%endfunction
 
%function SLibGetModelFileShared(opFile) void
  %return SLibDirectAccessGetFileAttribute(opFile, "Shared")
%endfunction
 
%function SLibSetModelFileShared(opFile, setting) void
  %<SLibDirectAccessSetFileAttribute(opFile, "Shared", setting)>
%endfunction
 
%function SLibGetModelFileSharedType(opFile) void
  %return SLibDirectAccessGetFileAttribute(opFile, "SharedType")
%endfunction
 
%function SLibSetModelFileSharedType(opFile, setting) void
  %<SLibDirectAccessSetFileAttribute(opFile, "SharedType", setting)>
%endfunction
 
%function SLibGetModelFileDeferredIncludeCoderTypes(opFile) void
  %return SLibDirectAccessGetFileAttribute(opFile, "DeferredIncludeCoderTypes")
%endfunction
 
%function SLibSetModelFileDeferredIncludeCoderTypes(opFile, setting) void
  %<SLibDirectAccessSetFileAttribute(opFile, "DeferredIncludeCoderTypes", setting)>
%endfunction
 
%function SLibGetModelFileIsEmpty(opFile) void
  %return SLibDirectAccessGetFileAttribute(opFile, "IsEmpty")
%endfunction
 
%%Function:LibGetNumModelFiles===================================================================
%%Abstract:
%%Getthenumberofgeneratedfiles.
%%
%function LibGetNumModelFiles() void
  %return NUM_SOURCE_FILES()
%endfunction
 
 
%%Function:LibGetModelFileTag====================================================================
%%Abstract:
%%Returns_hand_cforheaderandsourcefiles,
%%respectivelywherefileNameisthenameofthemodelfile.
%%Thisisusefulforcreatingaheaderfilemultipleinclusionguaurd.Forexample,
%%__RTW_GENERATED_HEADER_FILE_%<LibGetModelFileTag()>__
%%
%function LibGetModelFileTag(fileIdx) void
  %assign mf = ModelFiles.ModelFile[fileIdx]
  %assign baseName = SLibDirectAccessGetFileAttribute(mf, "BaseName")
  %assign fileType = SLibDirectAccessGetFileAttribute(mf, "Type")
 
  %assign ext = fileType == "SystemBody" ? "_c" : "_h"
  %return "%<baseName>%<ext>"
%endfunction
 
 
%%Function:LibGetModelFileNeedHeaderGuard========================================================
%%Abstract:
%%Returntrueifaheaderfileguardisrequired,andfalseotherwise.
%%
%function LibGetModelFileNeedHeaderGuard(fileIdx) void
  %assign opFile = LibGetSourceFileFromIdx(fileIdx)
  %if LibGetModelFileAttribute(fileIdx,"Type") != "SystemHeader"
    %return 0
  %elseif LibGetSourceFileShared(fileIdx)
    %% Shared utility functions put out their own guard (in cache_sharedutils_lib.tlc)
    %% so return false here.
    %return 0
  %else
    %assign coderTypesFiles = SLibPotentialCoderTypesBaseNames()
    %assign nameForCompare = LibGetFileRecordName(opFile)
 
    %foreach fIdx = SIZE(coderTypesFiles, 1)
      %assign coderTypesFile = coderTypesFiles[fIdx]
      %if nameForCompare == coderTypesFile
        %return 0
      %endif
    %endforeach
  %endif
  %if CodeFormat == "S-Function"
    %assign tag = LibGetModelFileTag(fileIdx)
    %assign mdlName = LibGetModelName()
    %return tag != "%<mdlName>_mid_h" && tag != "%<mdlName>_sid_h"
  %else
    %return 1
  %endif
%endfunction
 
%%Function:LibGetSourceFileAttribute=============================================================
%%Abstract:
%%Getsaspecifiedattributeofafile.
%%Validattributesare:
%%Name(withfileextension)
%%BaseName
%%Type
%%Creator
%%SystemsInFile
%%RequiredIncludes
%%UtilityIncludes
%%Filter
%%IsEmpty
%%Indent
%%WrittenToDisk
%%Shared
%%SharedType
%%CodeTemplate
%%OutputDirectory
%%Group
%%
%%Arguments:
%%fileIdx-fileindex
%%attrib-Amodelattributename
%function LibGetSourceFileAttribute(fileIdx, attrib)
  %if TYPE(fileIdx) != "Number"
    %if TYPE(fileIdx) == "Scope"
      %assign fileIdx = fileIdx.Index
    %else
      %assign errTxt = "LibGetSourceFileSection expects an index or a " ...
        "reference to a file."
      %<LibReportError(errTxt)>
    %endif
  %endif
 
  %switch attrib
    %case "Name"
    %case "BaseName"
    %case "Type"
    %case "Creator"
    %case "Filter"
    %case "IsEmpty"
    %case "OutputDirectory"
    %case "Group"
    %case "WrittenToDisk"
    %case "CodeTemplate"
      %return LibGetModelFileAttribute(fileIdx,attrib)
    %case "SystemsInFile"
    %case "RequiredIncludes"
    %case "UtilityIncludes"
    %case "Indent"
    %case "Shared"
    %case "SharedType"
      %assign opFile = ModelFiles.ModelFile[fileIdx]
      %return SLibDirectAccessGetFileAttribute(opFile, attrib)
    %default
      %assign errTxt = "Unknown file attribute: %<attrib>"
      %<LibReportFatalError(errTxt)>
  %endswitch
%endfunction
 
%%Function:LibGetModelFileAttribute==============================================================
%%Abstract:
%%(MathWorksinternalfunction.Externalusers,useLibGetSourceFileSection
%%orLibGetSourceFileAttributeinstead.)
%%Getsaspecifiedsectionofafile.
%%
%%Arguments:
%%fileIdx-fileindex
%%attrib-eitheratop-levelfieldnameorasub-fieldofContents
 
%function LibGetModelFileAttribute(fileIdx, attrib) void
 
  %assign opFile = ModelFiles.ModelFile[fileIdx]
 
  %% After LibClearModelFileBuffers() is called, Contents will not
  %% exist. However, still allow access to Name, BaseName, Type and Creator.
  %if ISFIELD(opFile,"Contents")
    %assign c = opFile.Contents
  %endif
 
  %switch attrib
    %case "Name"
    %case "NameWithoutExtension"
      %return GET_FILE_ATTRIBUTE(opFile.Index, attrib)
    %case "BaseName"
      %assign baseName = GET_FILE_ATTRIBUTE(opFile.Index, "BaseName")
      %assign type = GET_FILE_ATTRIBUTE(opFile.Index, "Type")
      %return SLibGetFullFileName(baseName, type)
    %case "Type"
    %case "Creator"
    %case "Filter"
    %case "IsEmpty"
    %case "OutputDirectory"
    %case "Group"
    %case "WrittenToDisk"
    %case "CodeTemplate"
      %return SLibDirectAccessGetFileAttribute(opFile, attrib)
    %case "Banner"
      %return SLibDirectAccessGetFileContent(opFile, attrib)
    %case "Includes"
      %% This prepends the RequiredIncludes to the Includes,
      %% but otherwise goes through the same steps as the
      %% the other fields of Contents (below)
      %<FcnAppendMissingTokens(opFile,attrib)> %% inserts from CustomContents if needed
      %% Roll together the RequiredIncludes, if any.
      %% Note what we have in the array is just the include filenames,
      %% so the code below wraps these in an "#include /"/"" directive.
      %assign includesContent = SLibDirectAccessGetFileContent(opFile, attrib)
      %<FcnAddCoderTypesFilesToRequiredIncludes(opFile)>
 
      %assign retValue = ""
      %assign retValue = GET_FILE_ATTRIBUTE(opFile.Index, attrib)
      %return retValue
    %case "Defines"
    %case "IntrinsicTypes"
    %case "PrimitiveTypedefs"
    %case "UserTop"
    %case "Typedefs"
    %case "GuardedIncludes"
    %case "Enums"
    %case "Definitions"
    %case "ExternData"
    %case "ExternFcns"
    %case "FcnPrototypes"
    %case "Declarations"
    %case "Functions"
    %case "CompilerErrors"
    %case "CompilerWarnings"
    %case "Documentation"
    %case "UserBottom"
    %case "ModelTypesIncludes"
    %case "ModelTypesDefines"
    %case "ModelTypesTypedefs"
      %% This inserts from the CustomContents section, if needed
      %<FcnAppendMissingTokens(opFile,attrib)>
      %assign content = GET_FILE_ATTRIBUTE(opFile.Index, attrib)
      %if !WHITE_SPACE(content)
        %return "/n" + content
      %else
        %return ""
      %endif
    %default
      %assign errTxt = "Unknown file attribute: %<attrib>"
      %<LibReportFatalError(errTxt)>
  %endswitch
%endfunction %% LibGetModelFileAttribute
 
%%Function:LibClearModelFileBuffers==============================================================
%%Abstract:
%%ClearthevariablesassociatedwithModelFilecontents.
%%
%function LibClearModelFileBuffers() void
  %if ResetTLCGlobalsAfterUse
    %assign success = CLEAR_FILE_BUFFERS()
  %endif
%endfunction
 
 
%%Function:LibWriteToStandardOutput==============================================================
%%Abstract:
%%WritetexttotheMATLABcommandwindow.
%%
%function LibWriteToStandardOutput(txt) void
  %%
  %% DO NOT INDENT THIS TLC CODE !!!
  %%
  %selectfile STDOUT
  %if RTWVerbose
    %<txt>
  %endif
  %closefile STDOUT %% not really closing, but to diactivate the current buffer
  %% and return the previous buffer, if any.
%endfunction %% LibWriteToStandardOutput
 
 
%%Function:LibSetCodeTemplateComplianceLevel=====================================================
%%Abstract:
%%Synchronizeacustomcodetemplate.Thisfunctionmustbe
%%calledfromacodetemplate.
%%
%function LibSetCodeTemplateComplianceLevel(level) void
  %assign ::CompiledModel.ModelFiles.ComplianceLevel = level
%endfunction
 
%%[EOF]codetemplatelib.tlc