/******************************************************************************/
// @copyright   Copyright Notification
//   No part may be reproduced except as authorized by written permission.
//   The copyright and the foregoing restriction extend to reproduction in all media.
//   Trademark 2010, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC).
//   All rights reserved.
// @version: IWD_10wk37
// $Date: 2010-09-16 23:11:35 +0200 (Thu, 16 Sep 2010) $
// $Rev: 3943 $
/******************************************************************************/

module EUTRA_NASSteps {
  import from EUTRA_RRC_ASN1_Definitions language "ASN.1:1997" all;
  import from CommonDefs all;
  import from EUTRA_CommonDefs all;
  import from EUTRA_ASP_SrbDefs all;
  import from NAS_CommonTypeDefs all;
  import from EPS_NAS_MsgContainers all;
  import from EPS_NAS_TypeDefs all;
  import from EPS_NAS_Constants all;
  import from EUTRA_Component all;
  import from EUTRA_CellInfo all;
  import from EUTRA_AspCommon_Templates all;
  import from EUTRA_SRB_Templates all;
  import from EUTRA_RRCSteps all;
  import from UpperTesterFunctions all;
  import from EUTRA_RRC_Templates all;
  import from EUTRA_DRB_Templates all;
  import from EPS_NAS_Templates all;
  import from NAS_CommonTemplates all;
  import from Parameters all;
  import from EUTRA_SecuritySteps all;
  import from EUTRA_SecurityFunctions all;
  import from EUTRA_AuxiliaryFunctions all;
  import from EUTRA_ConfigurationSteps all;
  import from EUTRA_NASCommonTemplates all;

  // ===========================================================================
  type enumerated EUTRA_ATTACH_Type
    {NORMAL, EPS_Only, CombinedWithPTMSI, CombinedWithTMSI};  /* @status    APPROVED @sic R5-101021 sic@ */

  // ===========================================================================
  /*
   * @desc      Check correct setting of PICS and return true combined attach shall be applied
   * @return    boolean
   * @status    APPROVED
   */
  function fl_AttachTypeCheck () runs on EUTRA_PTC return boolean
  {
    var boolean v_IsCombined := false;
    if( pc_Combined_Attach) {
      if (pc_Attach) { // So both set to true
        if (px_AttachTypeTested == COMBINED_ATTACH) { // only now check the PIXIT value
          v_IsCombined := true;
        }
      } else { // only combined set to true
        v_IsCombined := true;
      }
    } else if (not pc_Attach) { // so neither set to true
      f_EUTRA_SetVerdictFailOrInconc(__FILE__, __LINE__, "Neither pc_Attach nor pc_Combined_Attach set to true");
    }
    return v_IsCombined;
  }

  /*
   * @desc      Check PICS and return corresponding EPS Attach Type value.
   * @return    NAS_AttDetValue_Type
   * @status    APPROVED
   */
  function f_GetEAttachType() runs on EUTRA_PTC return NAS_AttDetValue_Type
  { /* @sic R5-101021, R5-103673 sic@ */
    var NAS_AttDetValue_Type v_EAttachType := tsc_EAttachType_EpsOnly;
    
    if( fl_AttachTypeCheck ()) {
      v_EAttachType := tsc_EAttachType_Combined;
    }
    return v_EAttachType;
  }
  // ===========================================================================
  /*
   * @desc      Check PICS and return corresponding EPS TAU Type value usef in the TAU Request message.
   * @return    EPS_UpdateTypeValue
   * @status    APPROVED
   */
  function f_GetEPSTAUType() runs on EUTRA_PTC return EPS_UpdateTypeValue
  { // @sic R5s100029, R5-101021, R5-103673 sic@
    var EPS_UpdateTypeValue v_TAUType := tsc_EpsUpdate_TaUpdate;

    if( fl_AttachTypeCheck ()) {
      v_TAUType := tsc_EpsUpdate_Combined_TaLaUpdate;
    }
    return v_TAUType;
  }

  //----------------------------------------------------------------------------
  /*
   * @desc      Check PICS and return corresponding EMM Cause @sic R5-101021, R5-103673 sic@
   * @return    template (omit) EMM_Cause
   * @status    (APPROVED)
   */
  function f_GetEMMCause() return template (omit) EMM_Cause
  {
    var template (omit) EMM_Cause v_EMMCause;
    v_EMMCause := omit; // @sic R5-101021 sic@ cs_EMM_Cause_tv(tsc_EmmCause_UnknownIMSI);
    return v_EMMCause;
  }
  //----------------------------------------------------------------------------
  /*
   * @desc      Check PICS and return corresponding Additonal Update Type
   * @return    template AdditionalUpdateType
   * @status    APPROVED
   */
  function f_GetAdditionalUpdateType() runs on EUTRA_PTC return template AdditionalUpdateType
  { /* @sic R5-103681 sic@ */
    var template AdditionalUpdateType v_AdditionalUpdateType := omit;
    if( fl_AttachTypeCheck ()) {
      v_AdditionalUpdateType := cr_AdditionalUpdateTypeAny ifpresent;
    }
    return v_AdditionalUpdateType;
  }
  //----------------------------------------------------------------------------
  /*
   * @desc      Check PICS and return corresponding Additonal Update Result
   * @param     p_RcvdAddUpdateType
   * @return    template (omit) AdditionalUpdateResult
   * @status    APPROVED
   */
  function f_GetAdditionalUpdateResult(AdditionalUpdateType p_RcvdAddUpdateType) runs on EUTRA_PTC return template (omit) AdditionalUpdateResult
  { /* @sic R5-103681 sic@ */
    var template (omit) AdditionalUpdateResult v_AdditionalUpdateResult := omit;
    //var boolean v_IsCombined := false;
    if( fl_AttachTypeCheck () and (p_RcvdAddUpdateType.addUpdateTypeValue == '1'B)) {  // SMS Only and Combined
      v_AdditionalUpdateResult := cs_AdditionalUpdateResult_SMSOnly;
    }
    
    return v_AdditionalUpdateResult;
  }
  //----------------------------------------------------------------------------
  /*
   * @desc      Check PICS and return corresponding LAI value. @sic R5-103673 sic@
   * @param     p_PLMN
   * @param     p_LAC
   * @return    template (omit) LocAreaId
   * @status    APPROVED
   */
  function f_GetLAI(NAS_PlmnId p_PLMN,
                    NAS_Lac    p_LAC) runs on EUTRA_PTC return template (omit) LocAreaId
  {
    var template(omit) LocAreaId v_LAI := omit;
    if( fl_AttachTypeCheck ()) {
      v_LAI := cs_LAI ('13'O, p_PLMN, p_LAC);
    }
    return v_LAI;
  }

  //----------------------------------------------------------------------------
  /*
   * @desc      Get Location Area Identitiy of a particular cell.
   *            Note: Depending on the attach mode EPS only or combined, the resulting template may be omit
   * @param     p_CellId
   * @return    template (omit) LocAreaId
   * @status    APPROVED
   */
  function f_EUTRA_GetCellLAI(CellId_Type p_CellId) runs on EUTRA_PTC return template (omit) LocAreaId
  {
    var GutiParameters_Type v_GutiParams := f_EUTRA_CellInfo_GetGuti(p_CellId);
    var NAS_Lac v_LAC := f_EUTRA_CellInfo_GetLocationAreaCode ( p_CellId );
    var NAS_PlmnId v_PLMN := f_Asn2Nas_PlmnId (v_GutiParams.PLMN_Identity);
    return  (f_GetLAI(v_PLMN,v_LAC));
  }

  //----------------------------------------------------------------------------
  /*
   * @desc      Check PICS and return corresponding Mobile Id value.
   * @param     p_ForcedAttach      (default value: NORMAL)
   * @return    template (omit) MobileIdentity
   * @status    APPROVED
   */
  function f_GetMSId(EUTRA_ATTACH_Type p_ForcedAttach := NORMAL) runs on EUTRA_PTC return template (omit) MobileIdentity
  { /* @sic R5-103763 sic@ */
    var template(omit) MobileIdentity v_MSId := omit;
    if( fl_AttachTypeCheck ()) {
      if( p_ForcedAttach == CombinedWithPTMSI) { // @sic R5-101021 sic@
        v_MSId := cs_MobileIdTMSIorPTMSI ('23'O, px_PTMSI_Def);
      }
      else { // have just picked one
        v_MSId := cs_MobileIdTMSIorPTMSI ('23'O, px_TMSI_Def);
      }
    }
    return v_MSId;
  }
  //----------------------------------------------------------------------------
  /*
   * @desc      Check pc_IPv6/pc_IPv4 and return corresponding PDN Type.
   * @return    PdnTypeValue
   * @status    APPROVED
   */
  function f_GetPdnType() return PdnTypeValue
  {
    var PdnTypeValue v_PdnType := tsc_PdnType_IPv4;
    if( pc_IPv6 ) {
      if( pc_IPv4 ) {
        v_PdnType := tsc_PdnType_IPv4v6;
      } else {
        v_PdnType := tsc_PdnType_IPv6;
      }
    }
    return v_PdnType;
  }

  /*----------------------------------------------------------------------------
   * @desc      Extract UE security capabilities from Attach Request message and store for use later
   * @param     p_ATTACH_REQUEST
   * @return    UE_SecurityCapability
   * @status    APPROVED
   */
  function f_EUTRA_FillNAS_SecurityCapability (ATTACH_REQUEST p_ATTACH_REQUEST) return UE_SecurityCapability
  {
    var UE_SecurityCapability v_SecurityCapability;
    var B8_Type v_GEA := '00000000'B;
    var integer v_Length := 2;
    
    v_SecurityCapability.eeaCap := p_ATTACH_REQUEST.ueNetworkCapability.eeaCap;
    v_SecurityCapability.eiaCap := p_ATTACH_REQUEST.ueNetworkCapability.eiaCap;
    
    if (ispresent(p_ATTACH_REQUEST.ueNetworkCapability.ueaCap)) {
      v_SecurityCapability.ueaCap := p_ATTACH_REQUEST.ueNetworkCapability.ueaCap;
      v_Length := v_Length + 2; // if octet 5 is present, 6 will be too @sic R5s100485 sic@
      if (ispresent(p_ATTACH_REQUEST.ueNetworkCapability.uiaCap)) {
        v_SecurityCapability.uiaCap := p_ATTACH_REQUEST.ueNetworkCapability.uiaCap and4b '7f'O; // @sic R5s100520 sic@
      } else {
        v_SecurityCapability.uiaCap := '00'O; // @sic R5s100485 sic@
      }
    } else {
      v_SecurityCapability.ueaCap := omit;
      v_SecurityCapability.uiaCap := omit; // @sic R5s100184 sic@
    }

    if (ispresent(p_ATTACH_REQUEST.msNetworkCapability)) {
      if (p_ATTACH_REQUEST.msNetworkCapability.gea1 == '1'B) {
        v_GEA := v_GEA or4b '1000000'B;
      }
      if (p_ATTACH_REQUEST.msNetworkCapability.gea2 == '1'B) {
        v_GEA := v_GEA or4b '100000'B;
      }
      if (p_ATTACH_REQUEST.msNetworkCapability.gea3 == '1'B) {
        v_GEA := v_GEA or4b '10000'B;
      }
      if (p_ATTACH_REQUEST.msNetworkCapability.gea4 == '1'B) {
        v_GEA := v_GEA or4b '1000'B;
      }
      if (p_ATTACH_REQUEST.msNetworkCapability.gea5 == '1'B) {
        v_GEA := v_GEA or4b '100'B;
      }
      if (p_ATTACH_REQUEST.msNetworkCapability.gea6 == '1'B) {
        v_GEA := v_GEA or4b '10'B;
      }
      if (p_ATTACH_REQUEST.msNetworkCapability.gea7 == '1'B) {
        v_GEA := v_GEA or4b '1'B;
      }
      v_Length := v_Length + 1;
      v_SecurityCapability.geaCap := bit2oct (v_GEA); // Now store the completed GEA octet
      if (v_Length == 3) { // UE didn't report any UTRAN capabilities, so set them to 0 @sic R5s100485 sic@
        v_Length := 5;
        v_SecurityCapability.ueaCap := '00'O;
        v_SecurityCapability.uiaCap := '00'O;
      }
    } else {// MS Network Capability not present @sic R5s100184 sic@
      v_SecurityCapability.geaCap := omit;
    }
    
    v_SecurityCapability.iel := int2oct (v_Length, 1);  // Now store the length
    
    return v_SecurityCapability;
  }
  
  //----------------------------------------------------------------------------
  /*
   * @desc      This function calls NAS Security and RRC Security
   *            So in the majority of test cases, you don't need to do anything else
   * @param     p_CellId
   * @param     p_EIT_Flag   - true if UE requested ESM Information Transfer procedure
   * @param     p_PTI        - current ESM Procedure Transaction Identifier to be used
   * @param     p_SRB
   * @status
   */
  function f_EUTRA_NAS_AS_Security (CellId_Type p_CellId,
                                    boolean p_EIT_Flag,
                                    ProcedureTransactionIdentifier p_PTI,
                                    SRB_Identity_Type p_SRB) runs on EUTRA_PTC  return template (value) AccessPointName
  {
    var NasCount_Type v_NasCountUL;
    var EUTRA_SecurityParams_Type v_AuthParams := f_EUTRA_Security_Get();
    var template (omit) AccessPointName v_APN := omit;

    v_NasCountUL := f_EUTRA_NAS_ActivateSecurity(p_CellId,v_AuthParams, p_SRB);   // NAS SECURITY COMMAND & COMPLETE
    if (p_EIT_Flag) {
      v_APN := f_ESM_InformationTransfer_GetAPN (p_CellId, p_PTI);
    }
    if (not isvalue(v_APN)) {
      v_APN := cs_AccessPointName (px_AccessPointName);
    }
    v_AuthParams := f_EUTRA_RRC_ActivateSecurity(p_CellId, v_AuthParams, v_NasCountUL); // RRC SECURITY COMMAND & COMPLETE
    f_EUTRA_Security_Set ( v_AuthParams );//Saving security parameters
    return (v_APN);
  }

  // ===========================================================================
  /*
   * @desc      This function calls NAS Authentication, NAS Security and RRC Security
   * @param     p_CellId
   * @param     p_EIT_Flag   - true if UE requested ESM Information Transfer procedure
   * @param     p_PTI        - current ESM Procedure Transaction Identifier to be used
   * @param     p_SecurityContextActive (default value: true)
   * @return    template (value) AccessPointName
   * @status    APPROVED
   */
  function f_EUTRA_Authentication_NAS_AS_Security (CellId_Type p_CellId,
                                                   boolean p_EIT_Flag,
                                                   ProcedureTransactionIdentifier p_PTI,
                                                   boolean p_SecurityContextActive := true)
    runs on EUTRA_PTC return template (value) AccessPointName
  {
    var NasCount_Type v_NasCountUL;
    var EUTRA_SecurityParams_Type v_AuthParams := f_EUTRA_Security_Get();
    var GutiParameters_Type v_Guti := f_EUTRA_CellInfo_GetGuti ( p_CellId );
    var NAS_PlmnId  v_PLMN := f_Asn2Nas_PlmnId (v_Guti.PLMN_Identity);
    var template (omit) AccessPointName v_APN := omit;

    // Authentication Request / Authentication Response
    if ( p_SecurityContextActive ) { // sic@ R5s100008 sic@
       v_AuthParams:=f_EUTRA_NAS_Authentication(p_CellId,
                                             tsc_SRB1,
                                             v_AuthParams,
                                             tsc_SHT_IntegrityProtected_Ciphered,
                                             tsc_SHT_IntegrityProtected_Ciphered,
                                             v_PLMN);
    } else {
       v_AuthParams:=f_EUTRA_NAS_Authentication(p_CellId,
                                             tsc_SRB1,
                                             v_AuthParams,
                                             tsc_SHT_NoSecurityProtection,
                                             (tsc_SHT_NoSecurityProtection, tsc_SHT_IntegrityProtected), // @sic R5-102226 sic@
                                             v_PLMN);
                                             
   }

    // NAS Security Mode Command / NAS Security Mode Complete
    v_NasCountUL := f_EUTRA_NAS_ActivateSecurity(p_CellId, v_AuthParams);

    if (p_EIT_Flag) {
      v_APN := f_ESM_InformationTransfer_GetAPN (p_CellId, p_PTI);
    }
    if (not isvalue(v_APN)) {
      v_APN := cs_AccessPointName (px_AccessPointName);
    }
    // RRC Security Command / RRC Security Complete
    v_AuthParams := f_EUTRA_RRC_ActivateSecurity(p_CellId, v_AuthParams, v_NasCountUL);
    f_EUTRA_Security_Set ( v_AuthParams );//Saving security parameters

    return (v_APN);
  }

  //----------------------------------------------------------------------------
  /*
   * @desc      receive ATTACH COMPLETE from SRB2; ATTACH COMPLETE contains piggybacked ACTIVATE DEFAULT EPS BEARER CONTEXT ACCEPT (within ESM Message Container)
   * @param     p_CellId
   * @param     p_EpsBearerId
   * @status    APPROVED
   */
  function f_EUTRA_NAS_AttachComplete(CellId_Type p_CellId,
                                      HalfOctet_Type p_EpsBearerId ) runs on EUTRA_PTC
  {
    SRB.receive(car_SRB2_NasPdu_IND(p_CellId,
                                    cr_NAS_IndicationWithPiggybacking(tsc_SHT_IntegrityProtected_Ciphered,
                                                                      cr_508_ATTACH_COMPLETE,
                                                                      cr_508_ActivateDefEpsBearerContextAccept(
                                                                                                               p_EpsBearerId))));
  };

  //----------------------------------------------------------------------------
  /*
   * @desc      RRC connection setup procedure with optional check of
   *            piggybacked NAS message in RRC Connection Setup Complete. To
   *            perform the check, provide a receive constraint in
   *            p_NasMsgIndication (NAS_MSG_Indication_Type). Using a '?'
   *            here, just accepts any NAS message or even a RRC Connection
   *            Setup Complete without a piggybacked NAS message.
   * @param     p_CellId
   * @param     p_RRC_TI
   * @param     p_EstablishmentCause   expected establishment cause (RRC Connection Request)
   * @param     p_ExpectedNasMsg       expected NAS PDU (RRC Connection Setup Complete) or '?'
   * @return    NAS_MSG_Indication_Type
   * @status    APPROVED
   */
  function f_EUTRA_RRC_ConnEst_DefWithNas(CellId_Type p_CellId,
                                          RRC_TransactionIdentifier p_RRC_TI,
                                          template (present) EstablishmentCause p_EstablishmentCause,
                                          template (present) NAS_MSG_Indication_Type p_ExpectedNasMsg) runs on EUTRA_PTC return NAS_MSG_Indication_Type
  {
    var SRB_COMMON_IND v_ReceivedAsp;

    // receive RRC Connection Request on SRB0 (CCCH):
    SRB.receive(car_SRB0_RrcPdu_IND(p_CellId,
                                    cr_RRCConnectionRequest(p_EstablishmentCause)));

    // send RRC Connection Setup on SRB0 (CCCH) and switch on UL grant assignments:
    f_EUTRA_RRC_ConnectionSetup_Def (p_CellId, cs_TimingInfo_Now, p_RRC_TI);


    // UE shall establish SRB1 acc. to 36.331 cl. 5.3.3.4 and 5.3.9
    // UE enters RRC_CONNECTED state

    // receive RRC Connection Setup Complete with piggy-backed NAS message on SRB1 (DCCH):
    SRB.receive(car_SRB1_RrcNasPdu_IND(p_CellId,
                                       cr_508_RRCConnectionSetupComplete(p_RRC_TI, ?),
                                       p_ExpectedNasMsg))
      -> value v_ReceivedAsp;

    return (v_ReceivedAsp.Signalling.Nas[0]);
  };


  //----------------------------------------------------------------------------
  /*
   * @desc      This function configures an AM DRB at the UE
   * @param     p_CellId
   * @param     p_DRB_Id
   * @param     p_Id
   * @param     p_ProcTi
   * @param     p_LinkedId
   * @param     p_QoS
   * @param     p_Tft
   * @status    APPROVED
   */
  function f_EUTRA_TxDedicatedEpsBearerCtxtReq(CellId_Type p_CellId,
                                               DRB_Identity p_DRB_Id,
                                               EPS_BearerIdentity p_Id,
                                               template (value) ProcedureTransactionIdentifier p_ProcTi, // octet
                                               template (value) LinkedEpsBearerIdentity p_LinkedId, //  1/2 octet
                                               template (value) EPS_QualityOfService p_QoS,
                                               template (value) TrafficFlowTemplate p_Tft)
    runs on EUTRA_PTC
  { /* RRC connection reconfiguration acc. to 36.331 cl. 5.3.5 */
    // @desc send RRCConnectionReconfiguration with piggy-backed ACTIVATE DEDICATED EPS BEARER CONTEXT REQUEST
    var template (value) NAS_DL_Message_Type v_ActDedicatedEPSBearerCxtReq :=
      cs_508_ActDedicatedEPSBearerCxtReq(p_Id,
                                         p_ProcTi,
                                         p_LinkedId,
                                         p_QoS,
                                         p_Tft);
    var RRC_TransactionIdentifier v_RRC_TI := tsc_RRC_TI_Def;
    
    SRB.send(cas_SRB1_RrcNasPdu_REQ(p_CellId,
                                    cs_TimingInfo_Now,
                                    cs_RRCConnectionReconfiguration_Common(v_RRC_TI,
                                                                           omit,
                                                                           omit,
                                                                           cs_508_RadioResourceConfigDedicated_AddAmDrb(p_DRB_Id),
                                                                           omit),
                                    cs_NAS_Request(tsc_SHT_IntegrityProtected_Ciphered,
                                                   v_ActDedicatedEPSBearerCxtReq)));
    
    // receive RRCConnectionReconfigurationComplete
    SRB.receive(car_SRB1_RrcPdu_IND(p_CellId,
                                    cr_508_RRCConnectionReconfigurationComplete(v_RRC_TI)));
  };
  
  //----------------------------------------------------------------------------
  /*
   * @desc      This function turns the UE off, waits for a Detach message and releases the RRC connection
   * @param     p_CellId
   * @param     p_RRCState
   * @param     p_RRC_TI            (default value: tsc_RRC_TI_Def)
   * @param     p_DetachType        (default value: omit - which means it will be determind by the function) R5-103675
   * @status    APPROVED
   */
  function f_EUTRA_UE_Detach_SwitchOffUe ( CellId_Type p_CellId,
                                           EUTRA_RRC_STATE_Type p_RRCState,
                                           RRC_TransactionIdentifier p_RRC_TI := tsc_RRC_TI_Def,
                                           template (omit) DetachType p_DetachType := omit ) runs on EUTRA_PTC
  {
    var GutiParameters_Type v_Guti := f_EUTRA_CellInfo_GetGuti ( p_CellId );
    var template (present) NAS_MSG_Indication_Type v_ExpectedDetachRequest;
    var NAS_MSG_Indication_Type v_ReceivedNasMsg;   // used only to suppress compiler warning
    var template (present) DetachType v_DetachType;
    var NAS_AttDetValue_Type v_AttachType :=f_GetEAttachType();  //definition introduced to follow TTCN3 v411 standard
    
    if (isvalue(p_DetachType)) {  // R5-103675
      v_DetachType := p_DetachType;
    } else {
      v_DetachType := cr_DetachType( '1'B, v_AttachType);
    }
    
    v_ExpectedDetachRequest :=
      cr_NAS_Indication ( (tsc_SHT_IntegrityProtected, tsc_SHT_IntegrityProtected_Ciphered),
                          cr_508_DETACH_REQUEST_MO(cr_NAS_KeySetIdentifier (?, tsc_NasKsi_NativeSecurityContext),
                                                   f_GutiParameters2MobileIdentity(omit, v_Guti),  // @sic R5s090225, R5s090310 sic@
                                                   v_DetachType )); // R5-103675

    f_UT_SwitchOffUE (UT, false);

    if (pc_SwitchOnOff) // The UE can actually be switched off @sic R5s09225 sic@
    {
      select (p_RRCState)
      {
        case (RRC_IDLE)
          {
            v_ReceivedNasMsg := f_EUTRA_RRC_ConnEst_DefWithNas( p_CellId,
                                                                p_RRC_TI, mo_Signalling,
                                                                cr_NAS_Indication ( tsc_SHT_IntegrityProtected,
                                                                                    cr_508_DETACH_REQUEST_MO(cr_NAS_KeySetIdentifier (?, tsc_NasKsi_NativeSecurityContext),
                                                                                                             f_GutiParameters2MobileIdentity(omit, v_Guti),
                                                                                                             v_DetachType)) );
          }
        case (RRC_CONNECTED)
          {
            alt {
              [] SRB.receive ( car_SRB1_NasPdu_IND ( p_CellId, v_ExpectedDetachRequest ) ) { }
              [] SRB.receive ( car_SRB2_NasPdu_IND ( p_CellId, v_ExpectedDetachRequest ) ) { }
            }
          }
      }
      //Now the connection can be released
      f_EUTRA_RRC_ConnectionRelease(p_CellId, p_RRC_TI, other);
    }

  } //end of f_EUTRA_UE_Detach_SwitchOffUe

  //----------------------------------------------------------------------------
  /*
   * @desc      Tracking area update behaviour according to 36.523-1 cl. 6.0.3
   * @param     p_CellId
   * @param     p_RRC_TI
   * @param     p_ForcedAttach      (default value: NORMAL)
   * @status    APPROVED
   */
  function f_EUTRA_TrackingAreaUpdate ( CellId_Type p_CellId,
                                        RRC_TransactionIdentifier p_RRC_TI, EUTRA_ATTACH_Type p_ForcedAttach := NORMAL) runs on EUTRA_PTC
  {
    var NAS_MSG_Indication_Type v_NAS_Ind;
    var ReleaseCause v_ReleaseCause := other;
    var EstablishmentCause v_EstablishmentCause := mo_Signalling;
    var NAS_KsiValue v_KsiValue := f_EUTRA_SecurityKSIasme_Get ( );
    var GutiParameters_Type v_GutiParams:= f_EUTRA_CellInfo_GetGuti ( p_CellId );
    var NAS_PlmnId v_PLMN := f_Asn2Nas_PlmnId (v_GutiParams.PLMN_Identity);
    var B3_Type v_EpsUpdate_TypeValue := f_GetEPSTAUType(); // @sic R5s100029 sic@
    var TrackingAreaCode v_Tac := f_EUTRA_CellInfo_GetTAC ( p_CellId );
    var NAS_Lac v_LAC := f_EUTRA_CellInfo_GetLocationAreaCode ( p_CellId );
    var EPS_BearerContextStatus v_EPS_ContextStatus;
    var template (omit) LocAreaId v_LAI := f_GetLAI (v_PLMN, v_LAC);
    var template (omit) MobileIdentity v_MSId := f_GetMSId (p_ForcedAttach); // @sic R5-103673 sic@
    var template (value) TrackingAreaIdList v_TaiList := cds_TAIListNonConsecutive_tlv( v_PLMN, { bit2oct(v_Tac) } ); // @sic R5s100029 sic@
    var template AdditionalUpdateType v_AdditionalUpdateType := f_GetAdditionalUpdateType ();  //used to follow TTCN3 v411 standard
    
    /* Step 1 - 3 */
    /* The TAU Request shall be integrity-protected, but not confidentiality-protected.
       UE uses the cached security context algorithms to protect the TAU Request message.
       ( reuse of keys allocated during attach procedure )
       ( 33.401 cl. 9.1.2 Idle mode procedures in E-UTRAN ) */
    /* Check that TRACKING AREA UPDATE REQUEST message is present and conforms
       with default message ( 36.508 Table 4.7.2-27: TRACKING AREA UPDATE REQUEST ) */
    v_NAS_Ind := f_EUTRA_RRC_ConnEst_DefWithNas ( p_CellId, p_RRC_TI, v_EstablishmentCause,
                                                  cr_NAS_Indication(tsc_SHT_IntegrityProtected,
                                                                    cr_508_TAU_Request ( v_EpsUpdate_TypeValue, v_KsiValue, v_AdditionalUpdateType ))); // @sic R5-103681 sic@
    v_EPS_ContextStatus := v_NAS_Ind.Pdu.Msg.tRACKING_AREA_UPDATE_REQUEST.epsBearerContextStatus; // Send this back in the Accept
    // UE has now establish SRB1 acc. to 36.331 cl. 5.3.3.4 and entered RRC_CONNECTED state
    
    /* Step 4: Transmit TRACKING AREA UPDATE ACCEPT message */
    /* In case MME has the cached security context it verifies the TAU Request message
       and replies with TAU Accept message protected with the cached security context
       ( 33.401 cl. 9.1.2 Idle mode procedures in E-UTRAN ) */
    SRB.send ( cas_SRB1_NasPdu_REQ ( p_CellId,
                                     cs_TimingInfo_Now,
                                     cs_NAS_Request ( tsc_SHT_IntegrityProtected_Ciphered,
                                                      cs_508_TAU_Accept ( v_EpsUpdate_TypeValue,
                                                                          f_GutiParameters2MobileIdentity ('50'O, v_GutiParams ),
                                                                          v_TaiList,
                                                                          v_EPS_ContextStatus,
                                                                          v_LAI,
                                                                          v_MSId,
                                                                          f_GetAdditionalUpdateResult(v_NAS_Ind.Pdu.Msg.tRACKING_AREA_UPDATE_REQUEST.addUpdateType))) ) ); // @sic R5-103681 sic@
    
    /* Step 5: Receive TRACKING AREA UPDATE COMPLETE */
    /* According to 24.301 cl: 5.5.3.2.4:
       If the TRACKING AREA UPDATE ACCEPT message contained a GUTI,
       the UE shall return a TRACKING AREA UPDATE COMPLETE message to
       the MME to acknowledge the received GUTI */
    SRB.receive ( car_SRB1_NasPdu_IND ( p_CellId,
                                        cr_NAS_Indication ( tsc_SHT_IntegrityProtected_Ciphered,
                                                            cr_508_TAU_Complete ) ) );

    /* Step 6: Release RRC connection */
    f_EUTRA_RRC_ConnectionRelease ( p_CellId, p_RRC_TI, v_ReleaseCause );
  }


  //----------------------------------------------------------------------------
  /*
   * @desc      Tracking area update upon mobility from another RAT
   * @param     p_CellId
   * @param     p_RRC_TI
   * @param     p_ForcedAttach      (default value: NORMAL)
   */
  function f_EUTRA_TrackingAreaUpdateFromAnotherRAT ( CellId_Type p_CellId,
                                                      RRC_TransactionIdentifier p_RRC_TI,
                                                      EUTRA_ATTACH_Type p_ForcedAttach := NORMAL) runs on EUTRA_PTC
  {
    var NAS_MSG_Indication_Type v_NAS_Ind;
    var ReleaseCause v_ReleaseCause := other;
    var EstablishmentCause v_EstablishmentCause := mo_Signalling;
    var NAS_KsiValue v_KsiValue := f_EUTRA_SecurityKSIasme_Get ( );
    var GutiParameters_Type v_GutiParams:= f_EUTRA_CellInfo_GetGuti ( p_CellId );
    var NAS_PlmnId v_PLMN := f_Asn2Nas_PlmnId (v_GutiParams.PLMN_Identity);
    var B3_Type v_EpsUpdate_TypeValue := f_GetEPSTAUType(); // @sic R5s100029 sic@
    var TrackingAreaCode v_Tac := f_EUTRA_CellInfo_GetTAC ( p_CellId );
    var NAS_Lac v_LAC := f_EUTRA_CellInfo_GetLocationAreaCode ( p_CellId );
    var EPS_BearerContextStatus v_EPS_ContextStatus;
    var NasCount_Type v_NasCountUL;
    var EUTRA_SecurityParams_Type v_SecurityParams := f_EUTRA_Security_Get();
    var template (omit) LocAreaId v_LAI := f_GetLAI (v_PLMN, v_LAC);
    var template (omit) MobileIdentity v_MSId := f_GetMSId (p_ForcedAttach);
    var template (value) TrackingAreaIdList v_TaiList := cds_TAIListNonConsecutive_tlv( v_PLMN, { bit2oct(v_Tac) } );
    var template AdditionalUpdateType v_AdditionalUpdateType := f_GetAdditionalUpdateType ();
    // @sic R5s100029 sic@
    // @sic R5-102227
 //   var Common_AuthenticationParams_Type v_MappedAuthentParams; // to be initialised from  UMTS/GERAN PTC;
    //var O4_Type v_NonceUE ;

    
    /* Step 1 - 3 */
    /* The TAU Request shall be integrity-protected, but not confidentiality-protected.
       UE uses the cached security context algorithms to protect the TAU Request message.
       ( reuse of keys allocated during attach procedure )
       ( 33.401 cl. 9.1.2 Idle mode procedures in E-UTRAN ) */
    /* Check that TRACKING AREA UPDATE REQUEST message is present and conforms
       with default message ( 36.508 Table 4.7.2-27: TRACKING AREA UPDATE REQUEST ) */
    if ( v_SecurityParams.KSIasme == '111'B and v_SecurityParams.KSIsgsn == '111'B ) // No current EPS security context; Hence UE will use Mapped Security Context
       //@sic R5-102227 enforce usage of Mapped security context derived from UMTS/GERAN keys
       // It is assumed that UE has no stored EPS security context, i.e. since power on did not camp on EUTRA cell
    {
        v_NAS_Ind := f_EUTRA_RRC_ConnEst_DefWithNas ( p_CellId, p_RRC_TI, v_EstablishmentCause,
                                                  cr_NAS_Indication(tsc_SHT_NoSecurityProtection,
                                                                    cdr_TAU_RequestIdleMobilityDiffRAT ( v_EpsUpdate_TypeValue, v_KsiValue, v_AdditionalUpdateType )));
     // UE has now establish SRB1 acc. to 36.331 cl. 5.3.3.4 and entered RRC_CONNECTED state

     v_EPS_ContextStatus := v_NAS_Ind.Pdu.Msg.tRACKING_AREA_UPDATE_REQUEST.epsBearerContextStatus; // Send this back in the Accept
     v_SecurityParams.NonceUE := oct2bit(v_NAS_Ind.Pdu.Msg.tRACKING_AREA_UPDATE_REQUEST.nonce.nonceValue);
     // Store NonceUE
 //    v_SecurityParams:=f_EUTRA_MappedContext_InitNAS(v_SecurityParams,v_MappedAuthentParams);
     /* Step 4, 5: NAS Security Mode Command / NAS Security Mode Complete*/
    v_NasCountUL := f_EUTRA_NAS_ActivateSecurity_MappedContext(p_CellId, v_SecurityParams);

    }
     else // UE has current EPS NAS Security Context
     {
      // Do nothing;
      //Transmission of TAU Accept integrity and Ciphered will result in activating NAS security
      // But this is non conforment to 36.508 which always expects NAS SMC to be executed;
      // Prose can be changed;
     }
    

    /* Step 6: Transmit TRACKING AREA UPDATE ACCEPT message */
    /* In case MME has the cached security context it verifies the TAU Request message
       and replies with TAU Accept message protected with the cached security context
       ( 33.401 cl. 9.1.2 Idle mode procedures in E-UTRAN ) */
    SRB.send ( cas_SRB1_NasPdu_REQ ( p_CellId,
                                     cs_TimingInfo_Now,
                                     cs_NAS_Request ( tsc_SHT_IntegrityProtected_Ciphered,
                                                      cs_508_TAU_Accept ( v_EpsUpdate_TypeValue,
                                                                          f_GutiParameters2MobileIdentity ('50'O, v_GutiParams ),
                                                                          v_TaiList,
                                                                          v_EPS_ContextStatus,
                                                                          v_LAI,
                                                                          v_MSId,
                                                                          f_GetAdditionalUpdateResult(v_NAS_Ind.Pdu.Msg.tRACKING_AREA_UPDATE_REQUEST.addUpdateType))) ) ); // @sic R5-103681 sic@

    
    /* Step 7: Receive TRACKING AREA UPDATE COMPLETE */
    /* According to 24.301 cl: 5.5.3.2.4:
       If the TRACKING AREA UPDATE ACCEPT message contained a GUTI,
       the UE shall return a TRACKING AREA UPDATE COMPLETE message to
       the MME to acknowledge the received GUTI */
    SRB.receive ( car_SRB1_NasPdu_IND ( p_CellId,
                                        cr_NAS_Indication ( tsc_SHT_IntegrityProtected_Ciphered,
                                                            cr_508_TAU_Complete ) ) );

    /* Step 8: Release RRC connection */
    f_EUTRA_RRC_ConnectionRelease ( p_CellId, p_RRC_TI, v_ReleaseCause );
  }

  //----------------------------------------------------------------------------
  /*
   * @desc      Send the ESM Information_Request and receive the Response
   * @param     p_CellId
   * @param     p_PTI
   * @return    ESM_INFORMATION_RESPONSE
   * @status    APPROVED
   */
  function f_ESM_InformationTransfer (CellId_Type p_CellId,
                                      ProcedureTransactionIdentifier p_PTI) runs on EUTRA_PTC return ESM_INFORMATION_RESPONSE
  {
    var SRB_COMMON_IND v_ReceivedMsg;

    SRB.send ( cas_SRB1_NasPdu_REQ ( p_CellId,
                                     cs_TimingInfo_Now,
                                     cs_NAS_Request ( tsc_SHT_IntegrityProtected_Ciphered,
                                                      cs_508_Esm_Information_Request ( p_PTI ) ) ) );

    SRB.receive ( car_SRB1_NasPdu_IND ( p_CellId,
                                        cr_NAS_Indication ( tsc_SHT_IntegrityProtected_Ciphered,
                                                            cr_508_Esm_Information_Response ( p_PTI ) ) ) )
      -> value v_ReceivedMsg;
    return (v_ReceivedMsg.Signalling.Nas[0].Pdu.Msg.eSM_INFORMATION_RESPONSE);
  }
  //----------------------------------------------------------------------------
  /*
   * @desc      Send the ESM Information_Request and receive the Response
   *            rather than f_ESM_InformationTransfer this function returns the AccessPointName (or omit)
   * @param     p_CellId
   * @param     p_PTI
   * @return    template (omit) AccessPointName
   * @status    APPROVED
   */
  function f_ESM_InformationTransfer_GetAPN (CellId_Type p_CellId,
                                             ProcedureTransactionIdentifier p_PTI) runs on EUTRA_PTC return template (omit) AccessPointName
  {
    var template (omit) AccessPointName v_APN := omit;
    var ESM_INFORMATION_RESPONSE v_ESM_INFORMATION_RESPONSE;

    v_ESM_INFORMATION_RESPONSE := f_ESM_InformationTransfer (p_CellId, p_PTI);
    if (ispresent(v_ESM_INFORMATION_RESPONSE.accessPointName)) {
      v_APN := v_ESM_INFORMATION_RESPONSE.accessPointName;
      v_APN.iei := omit;  // @sic R5s100140 sic@
    }
    return v_APN;
  }
  //----------------------------------------------------------------------------
  // New types/templates for this function

  type record length (1..8) of EPS_QualityOfService EPS_QoSList_Type;   /* @status    APPROVED */
  type record length (1..8) of TrafficFlowTemplate Tft_List_Type;       /* @status    APPROVED */

  /*
   * @desc       Establishment of SRB1 + default DRB + n AM DRBs + m UM DRBs acc. to 36.508 cl. 4.5.3.2;
   *             This function starts by setting up an RRC Connection to receive a Service Request,
   *             then performs RRC Security and sends RRC Connection Reconfiguration to configure SRB2 and at least 1 AM DRB,
   *             with optionally activating up to 8 Dedictated Bearers
   *             This function DOES NOT configure the SS, but expects the appropriate DRBs to be already configured
   *             @params
   *               If no Dedicated bearers are required, set p_NoOfAddDRBs_AM and p_NoOfAddDRBs_UM to 0 and p_QoS and p_Tft to omit
   *               in this case only SRB2 and 1 AM DRB (for the already activated Default Bearer) are configured
   *               Otherwise, SRB2 and 1 AM DRB will be configured + p_NoOfAddDRBs_AMs and p_NoOfAddDRBs_UMs
   *             Note:
   *               usage of n and N in 36.508 is confusing:
   *               - acc. to Table 4.6.3-16 n is the total number of AM DRBs - including the default DRB;
   *               - in cl. 4.5.3.2 N is the number of add. DRBs (UM and AM), n = no of add. AM bearers, m = no of add. UM bearers (=> N = n+m; 0<=N<=7)
   *                 but here the default DRB is not taken into account
   * @param     p_CellId
   * @param     p_NoOfAddDRBs_AM             no of add. AM bearers not including the default DRB
   * @param     p_NoOfAddDRBs_UM             no of add. UM bearers
   * @param     p_DRB_ToAddModList           p_NoOfAddDRBs_AM+p_NoOfAddDRBs_UM+1 elements or omit;
   *                                         omit => default setiing acc. 36.508 cl. 4.8.2.1.7
   * @param     p_MAC_MainConfig             omit => default setting acc. 36.508 cl. 4.8.2.1.5
   * @param     p_PhysicalConfigDedicated    omit => default setting acc. 36.508 4.8.2.1.6
   * @param     p_QoS
   * @param     p_Tft
   * @param     p_PDCP_StatusReportRequired (default value: true)
   * @status    APPROVED
   */
  function f_EUTRA_ServiceRequestAndActivate_SRB2_DRB(CellId_Type p_CellId,
                                                      UInt_Type p_NoOfAddDRBs_AM,
                                                      UInt_Type p_NoOfAddDRBs_UM,
                                                      template (omit) DRB_ToAddModList p_DRB_ToAddModList,
                                                      template (omit) MAC_MainConfig_Type p_MAC_MainConfig,
                                                      template (omit) PhysicalConfigDedicated p_PhysicalConfigDedicated,
                                                      template (omit) EPS_QoSList_Type p_QoS,
                                                      template (omit) Tft_List_Type p_Tft,
                                                      boolean p_PDCP_StatusReportRequired := true) runs on EUTRA_PTC
  {
    var RRC_TransactionIdentifier v_RRC_TI := tsc_RRC_TI_Def;
    var NAS_MSG_Indication_Type v_NAS_Ind;
    var NAS_KsiValue v_KsiValue;

    // =====================================================
    // step 3-10 of procedure in 36.508 cl. 4.5.3.3

    // Step 3 - 5 of Generic RB establishment procedure
    //Check the Service Request message
    v_KsiValue := f_EUTRA_SecurityKSIasme_Get ( );
    v_NAS_Ind := f_EUTRA_RRC_ConnEst_DefWithNas ( p_CellId,
                                                  v_RRC_TI,
                                                  cr_EstablishmentCause_mt_Access,
                                                  cr_NAS_Indication(tsc_SHT_IntegrityProtected,
                                                                    cr_508_SERVICE_REQUEST ( v_KsiValue )));

    /* Step 6 - 8 */
    f_EUTRA_Activate_SRB2_DRB_SendRrcMsg ( p_CellId,
                                           v_RRC_TI,
                                           v_NAS_Ind.SecurityProtection.NasCount,
                                           p_NoOfAddDRBs_AM,
                                           p_NoOfAddDRBs_UM,
                                           p_DRB_ToAddModList,
                                           p_MAC_MainConfig,
                                           p_PhysicalConfigDedicated,
                                           p_QoS,
                                           p_Tft,
                                           p_PDCP_StatusReportRequired);      /* @sic R5s100315 sic@ */
    
    /* Step 9 - 10 */
    f_EUTRA_Activate_SRB2_DRB_ReceiveRrcAndNasMsg(p_CellId,
                                                  v_RRC_TI,
                                                  p_NoOfAddDRBs_AM,
                                                  p_NoOfAddDRBs_UM);          /* @sic R5s100315 sic@ */
  }

  //----------------------------------------------------------------------------
  /*
   * @desc       Establishment of SRB1 + default DRB + n AM DRBs + m UM DRBs acc. to 36.508 cl. 4.5.3.2;
   *             This function expects the Service Request to already be received.
   *             It starts with RRC Security and sends RRC Connection Reconfiguration to configure SRB2 and at least 1 AM DRB,
   *             with optionally activating up to 8 Dedictated Bearers
   *             This function DOES NOT configure the SS, but expects the appropriate DRBs to be already configured
   *             This procedure has been split into 2 as a result of R5-102180
   *             The function does only send the RRCConnectionReconfiguration;
   *             receiption of RRCConnectionReconfigurationComplete and optionally further NAS PDUs is done outside this function; @sic R5s100315 sic@
   *             @params
   *               If no Dedicated bearers are required, set p_NoOfAddDRBs_AM and p_NoOfAddDRBs_UM to 0 and p_QoS and p_Tft to omit
   *               in this case only SRB2 and 1 AM DRB (for the already activated Default Bearer) are configured
   *               Otherwise, SRB2 and 1 AM DRB will be configured + p_NoOfAddDRBs_AMs and p_NoOfAddDRBs_UMs
   *             Note:
   *               usage of n and N in 36.508 is confusing:
   *               - acc. to Table 4.6.3-16 n is the total number of AM DRBs - including the default DRB;
   *               - in cl. 4.5.3.2 N is the number of add. DRBs (UM and AM), n = no of add. AM bearers, m = no of add. UM bearers (=> N = n+m; 0<=N<=7)
   *                 but here the default DRB is not taken into account
   * @param     p_CellId
   * @param     p_RRC_TI                     tsc_RRC_TI_Def in general
   * @param     p_NasCountUL                 needed for RRC Security
   * @param     p_NoOfAddDRBs_AM             no of add. AM bearers not including the default DRB
   * @param     p_NoOfAddDRBs_UM             no of add. UM bearers
   * @param     p_DRB_ToAddModList           p_NoOfAddDRBs_AM+p_NoOfAddDRBs_UM+1 elements or omit;
   *                                         omit => default setiing acc. 36.508 cl. 4.8.2.1.7
   * @param     p_MAC_MainConfig             omit => default setting acc. 36.508 cl. 4.8.2.1.5
   * @param     p_PhysicalConfigDedicated    omit => default setting acc. 36.508 4.8.2.1.6
   * @param     p_QoS
   * @param     p_Tft
   * @param     p_PDCP_StatusReportRequired (default value: true)
   * @status    APPROVED
   */
  function f_EUTRA_Activate_SRB2_DRB_SendRrcMsg(CellId_Type p_CellId,
                                                RRC_TransactionIdentifier p_RRC_TI,
                                                NasCount_Type p_NasCountUL,
                                                UInt_Type p_NoOfAddDRBs_AM := 0,
                                                UInt_Type p_NoOfAddDRBs_UM := 0,
                                                template (omit) DRB_ToAddModList p_DRB_ToAddModList := omit,
                                                template (omit) MAC_MainConfig_Type p_MAC_MainConfig := omit,
                                                template (omit) PhysicalConfigDedicated p_PhysicalConfigDedicated := omit,
                                                template (omit) EPS_QoSList_Type p_QoS := omit,
                                                template (omit) Tft_List_Type p_Tft := omit,
                                                boolean p_PDCP_StatusReportRequired := true) runs on EUTRA_PTC
  {
    var integer n, m, i, v_DRB_Id;
    var EPS_BearerIdentity v_EpsBearerId;
    var integer v_NoOfQos := 0;
    var integer v_NoOfTft := 0;
    var integer v_NoOfAddDRBs := p_NoOfAddDRBs_AM + p_NoOfAddDRBs_UM;  /* number of bearers to be configured additionally (i.e. apart from the default bearer)
                                                                          if v_NoOfAddDRBs=0 => only the default DRB is established */
    var EUTRA_SecurityParams_Type v_AuthParams := f_EUTRA_Security_Get();
    var template (value) EUTRA_FDD_TDD_CellInfo_Type v_EUTRA_FDD_TDD_Info := f_EUTRA_CellInfo_GetFDD_TDD_Info (p_CellId); //Get FDD or TDD mode from Cell-configuration
    var template (value) DRB_ToAddModList v_DRB_ToAddModList;
    var template (value) MAC_MainConfig_Type v_MAC_MainConfig;
    var template (value) PhysicalConfigDedicated v_PhysicalConfigDedicated;
    var template (omit)  NAS_MSG_RequestList_Type v_NAS_MsgList;
    var template (value) RadioResourceConfigDedicated  v_RadioResourceConfigDedicated;
    var EUTRA_TimingAdvancePeriodMode_Type v_TimingAdvancePeriodMode := normal;
    var template (value) PhysicalConfigDedicated_AntennaInfo_Type v_AntennaInfo := f_EUTRA_CellInfo_GetAntennaInfoDedicated (p_CellId); //@sic R5-100786 sic@

    // -----------------------------------------------------
    // Check parameters are valid
    if (isvalue(p_QoS)) {
      v_NoOfQos := lengthof(p_QoS);
    }
    if (isvalue(p_Tft)) {
      v_NoOfTft := lengthof(p_Tft);
    }
    if (v_NoOfQos != v_NoOfAddDRBs) {
      FatalError (__FILE__, __LINE__, "invalid no. of QoS");
    }
    if (v_NoOfTft != v_NoOfAddDRBs) {
      FatalError (__FILE__, __LINE__, "invalid no. of TFT");
    }

    // -----------------------------------------------------
    // initialise v_DRB_ToAddModList

    if (isvalue(p_DRB_ToAddModList)) {                  // explicit setting for DRB_ToAddMod
      if (lengthof(p_DRB_ToAddModList) != v_NoOfAddDRBs+1) {
        FatalError (__FILE__, __LINE__, "invalid no. of DRB_ToAddMod");
      }
      v_DRB_ToAddModList := p_DRB_ToAddModList;
    } else {                                            // use default configuration
      v_DRB_Id := tsc_DRB1;                             // default bearer
      for (n := 0; n < (p_NoOfAddDRBs_AM + 1); n := n + 1) {                // default bearer included in the list (=> p_NoOfAddDRBs_AM + 1)
        if (p_PDCP_StatusReportRequired == true)
        {
          v_DRB_ToAddModList[n] := cs_508_DRB_ToAddMod_DEFAULT_AM (v_DRB_Id);
        }
        else
        {
          v_DRB_ToAddModList[n] := cs_DRB_ToAddMod_NoPDCP_StatusReport (v_DRB_Id);
        }
        v_DRB_Id := v_DRB_Id + 1;
      }
      for (m := 0; m < p_NoOfAddDRBs_UM; m := m + 1) {
        v_DRB_ToAddModList[n+m] := cs_508_DRB_ToAddMod_DEFAULT_UM (v_DRB_Id);
        v_DRB_Id := v_DRB_Id + 1;
      }
    }

    // -----------------------------------------------------
    // initialise RRCConnectionReconfiguration
    
    if ((p_NoOfAddDRBs_UM > 0) and f_TestcaseIsL2Testcase()) {  /* @sic R5-101177, R5-101178, R5-101050 sic@
                                                                   @sic R5s100116 sic@ */
      v_TimingAdvancePeriodMode := l2Um;     // => PUCCH sync needs to be reconfigured at the SS side to get short TA period
    }

    if (isvalue(p_MAC_MainConfig)) {
      v_MAC_MainConfig := p_MAC_MainConfig;
    } else {
      if (p_NoOfAddDRBs_UM > 0) {
        if (f_TestcaseIsL2Testcase()) {          // @sic R5-101177, R5-101178, R5-101050 sic@
          v_MAC_MainConfig := cs_508_MAC_MainConfig_Explicit_RBC_DrxS_L2;
        } else {
          v_MAC_MainConfig := cs_508_MAC_MainConfig_Explicit_RBC_DrxS; // short DRX cycle acc. to note in 36.508 table 4.6.3-16
        }
      } else {
        v_MAC_MainConfig := cs_508_MAC_MainConfig_Explicit_RBC_DrxL; // long DRX cycle acc. to note in 36.508 table 4.6.3-16
      }
    }
    if (isvalue(p_PhysicalConfigDedicated)) {
      v_PhysicalConfigDedicated := p_PhysicalConfigDedicated;
    } else {
      v_PhysicalConfigDedicated := cs_508_PhysicalConfigDedicated_Default_RBC(v_EUTRA_FDD_TDD_Info.cqi_ReportConfig,
                                                                              v_EUTRA_FDD_TDD_Info.soundingRS_UL_Config,
                                                                              v_AntennaInfo);
    }
    v_RadioResourceConfigDedicated := cs_508_RadioResourceConfigDedicated_Srb2(v_DRB_ToAddModList,
                                                                               v_MAC_MainConfig,
                                                                               v_PhysicalConfigDedicated);
    // -----------------------------------------------------
    // initialise NAS messages

    if (v_NoOfAddDRBs == 0) {
      v_NAS_MsgList := omit;                          // no NAS messages to be sent
    } else {
      for (i := 0; i < v_NoOfAddDRBs; i := i+1) {     // only for the additional DRBs (there is no ActDedEPSBearerCxtReq for the already existing default bearer)
        // get EpsBearerId from the corresponding DRB_ToAddModList; DRB_ToAddModList[0] is the default bearer which needs to be skipped
        v_EpsBearerId := int2hex(valueof(v_DRB_ToAddModList[i+1].eps_BearerIdentity), 1);  // i+1 to skip default DRB; valueof cannot be avoided here

        v_NAS_MsgList[i] := cs_NAS_Request(tsc_SHT_IntegrityProtected_Ciphered,
                                           cs_ActDedEPSBearerCxtReq_QoS(v_EpsBearerId, p_QoS[i], p_Tft[i]));
      }
    }

    // =====================================================
    // step 6-8 of procedure in 36.508 cl. 4.5.3.3

    /* Step 6 - 7 */
    v_AuthParams := f_EUTRA_Authentication_InitAS ( v_AuthParams, p_NasCountUL );
    v_AuthParams := f_EUTRA_RRC_ActivateSecurity ( p_CellId, v_AuthParams, p_NasCountUL );
    f_EUTRA_Security_Set ( v_AuthParams );

    if (v_TimingAdvancePeriodMode != normal) {   // @sic R5-101177, R5-101178, R5-101050 sic@
      /* reconfigure SS for short TA period to cope with the short DRX inactivity timer (i.e. prevent the UE from faling asleep) */
      f_EUTRA_PUCCH_AutoSync_SetAndConfigure(p_CellId, v_TimingAdvancePeriodMode);
    }

    /* Step 8 */
    SRB.send ( cas_SRB1_RrcNasPduList_REQ(p_CellId,
                                          cs_TimingInfo_Now,
                                          cs_RRCConnectionReconfiguration_Common(p_RRC_TI,
                                                                                 omit,
                                                                                 omit,
                                                                                 v_RadioResourceConfigDedicated,
                                                                                 omit ),
                                          v_NAS_MsgList) );
  }

  //----------------------------------------------------------------------------
  /*
   * @desc       Establishment of SRB1 + default DRB + n AM DRBs + m UM DRBs acc. to 36.508 cl. 4.5.3.2;
   *             This function receives the RRCConnectionReconfigurationComplete and - depending on the number of additional AM and UM bearers -
   *             additional NAS messages (ActDedicatedEPSBearerCxtAccept)
   * @param     p_CellId
   * @param     p_RRC_TI                     tsc_RRC_TI_Def in general
   * @param     p_NoOfAddDRBs_AM             no of add. AM bearers not including the default DRB
   * @param     p_NoOfAddDRBs_UM             no of add. UM bearers
   * @status    APPROVED
   */
  function f_EUTRA_Activate_SRB2_DRB_ReceiveRrcAndNasMsg(CellId_Type p_CellId,
                                                         RRC_TransactionIdentifier p_RRC_TI,
                                                         UInt_Type p_NoOfAddDRBs_AM := 0,
                                                         UInt_Type p_NoOfAddDRBs_UM := 0) runs on EUTRA_PTC
  { /* @sic R5s100315 sic@ */
    var integer v_NoOfExpectedRrcMsgs := 1;
    var integer v_NoOfExpectedNasMsgs := p_NoOfAddDRBs_AM + p_NoOfAddDRBs_UM;  /* number of bearers to be configured additionally (i.e. apart from the default bearer)
                                                                                  if v_NoOfAddDRBs=0 => only the default DRB is established */
    // =====================================================
    // step 9-10 of procedure in 36.508 cl. 4.5.3.3:
    // Step 9 and 10 can occur in any order.  Step 10 only occurs for number of Activate messages sent
    while (v_NoOfExpectedRrcMsgs + v_NoOfExpectedNasMsgs > 0) {
      alt {
        [v_NoOfExpectedRrcMsgs > 0] SRB.receive ( car_SRB1_RrcPdu_IND ( p_CellId,
                                                                        cr_508_RRCConnectionReconfigurationComplete(p_RRC_TI) ) )
          {
            v_NoOfExpectedRrcMsgs := v_NoOfExpectedRrcMsgs - 1;
          }
        [v_NoOfExpectedNasMsgs > 0] SRB.receive ( car_SRB2_NasPdu_IND(p_CellId,
                                                                      cr_NAS_Indication(tsc_SHT_IntegrityProtected_Ciphered,
                                                                                        cr_508_ActDedicatedEPSBearerCxtAccept(?)) ) )
          {
            v_NoOfExpectedNasMsgs := v_NoOfExpectedNasMsgs - 1;
          }
      }
    }
  }

  //----------------------------------------------------------------------------
  /*
   * @desc      Send RRCConnectionReconfiguration (with piggy-backed ATTACH_ACCEPT) and wait for RRCConnectionReconfigurationComplete
   * @param     p_CellId
   * @param     p_EpsBearerId
   * @param     p_RRC_TI
   * @param     p_EPS_TI
   * @param     p_EpsAttachResultValue
   * @param     p_PDN_Address
   * @param     p_Guti
   * @param     p_TaiList
   * @param     p_LAI
   * @param     p_MSId
   * @param     p_Cause
   * @param     p_APN
   * @param     p_Pco
   * @param     p_RcvdAddUpdateType
   * @status    APPROVED
   */
  function f_EUTRA_RRCConnectionReconfigurationWithAttachAcceptAllParams(CellId_Type p_CellId,
                                                                         HalfOctet_Type p_EpsBearerId,
                                                                         RRC_TransactionIdentifier p_RRC_TI,
                                                                         ProcedureTransactionIdentifier p_EPS_TI,
                                                                         NAS_AttDetValue_Type p_EpsAttachResultValue,
                                                                         template (omit) PDN_Address p_PDN_Address,
                                                                         template (omit) MobileIdentity p_Guti,
                                                                         template (value) TrackingAreaIdList p_TaiList,
                                                                         template (omit) LocAreaId p_LAI,
                                                                         template (omit) MobileIdentity p_MSId,
                                                                         template (omit) ESM_Cause p_Cause,  // @sic R5-104703 sic@
                                                                         template (omit) AccessPointName p_APN,
                                                                         template (omit) ProtocolConfigOptions p_Pco, // @sic R5-104703 sic@ Default value is PPP
                                                                         AdditionalUpdateType p_RcvdAddUpdateType)
    runs on EUTRA_PTC
  { /* RRC connection reconfiguration acc. to 36.331 cl. 5.3.5 */

    var template (value) NAS_MSG_Request_Type v_NAS_MSG_Request;
    var template (value) AccessPointName v_APN;

    if (isvalue(p_APN)) {
      v_APN := p_APN;
    } else {
      v_APN := cs_AccessPointName (px_AccessPointName);
    }

    v_NAS_MSG_Request := cs_NAS_RequestWithPiggybacking(tsc_SHT_IntegrityProtected_Ciphered,
                                                        cs_508_ATTACH_ACCEPT(p_EpsAttachResultValue,
                                                                             p_TaiList,
                                                                             p_Guti,
                                                                             p_LAI,
                                                                             p_MSId,
                                                                             omit, // @sic R5-104703 sic@
                                                                             f_GetAdditionalUpdateResult(p_RcvdAddUpdateType)),  // @sic R5-103681 sic@
                                                        cs_508_ActivateDefEpsBearerContextRequest(p_EpsBearerId,
                                                                                                  p_EPS_TI,
                                                                                                  v_APN,
                                                                                                  p_PDN_Address,
                                                                                                  omit,
                                                                                                  p_Cause, // @sic R5-104703 sic@
                                                                                                  p_Pco));
    f_EUTRA_RRCConnectionReconfigurationWithPiggyNAS(p_CellId,
                                                     p_RRC_TI,
                                                     v_NAS_MSG_Request);
  };

  //----------------------------------------------------------------------------
  /**
   * @desc Send an ATTACH ACCEPT message embedded in an RRC Connection Reconfiguration including
   *       a list of equivalent PLMNs.
   */
  function f_TxAttachAcceptWithEquivalentPLMNList(CellId_Type p_CellId,
                                                  HalfOctet_Type p_EpsBearerId,
                                                  RRC_TransactionIdentifier p_RRC_TI,
                                                  ProcedureTransactionIdentifier p_EPS_TI,
                                                  NAS_AttDetValue_Type p_EpsAttachResultValue,
                                                  template (omit) PDN_Address p_PDN_Address,
                                                  template (value) MobileIdentity p_Guti,
                                                  template (value) TrackingAreaIdList p_TaiList,
                                                  template (omit) LocAreaId p_Lai,
                                                  template (omit) MobileIdentity p_MSId,
                                                  template (omit) ESM_Cause p_ESM_Cause,
                                                  template (omit) AccessPointName p_APN,
                                                  template (omit)  PLMN_List p_EquivalentPlmnList,
                                                  template (omit) ProtocolConfigOptions p_Pco,
                                                  AdditionalUpdateType p_RcvdAddUpdateType)
    runs on EUTRA_PTC
  {
    /* RRC connection reconfiguration acc. to 36.331 cl. 5.3.5 */

    // send RRCConnectionReconfiguration with piggy-backed ATTACH ACCEPT
    // and piggy-backed ACTIVATE DEFAULT EPS BEARER CONTEXT REQUEST
    var template (value) NAS_DL_Message_Type v_ActDefEpsBearerCtxtReq;
    var template (value) NAS_DL_Message_Type v_AttachAccept :=
      cds_ATTACH_ACCEPT_equivalentPLMNList(p_EpsAttachResultValue,
                                           p_TaiList,
                                           p_Guti,
                                           p_Lai,
                                           p_MSId,
                                           omit,
                                           f_GetAdditionalUpdateResult(p_RcvdAddUpdateType),  // @sic R5-103681 sic@)
                                           p_EquivalentPlmnList);
    var template (value) AccessPointName v_APN;

    if (isvalue(p_APN)) {
      v_APN := p_APN;
    } else {
      v_APN := cs_AccessPointName (px_AccessPointName);
    }

    v_ActDefEpsBearerCtxtReq := cs_508_ActivateDefEpsBearerContextRequest(p_EpsBearerId,
                                                p_EPS_TI,
                                                v_APN,
                                                p_PDN_Address,
                                                omit,
                                                p_ESM_Cause,
                                                p_Pco);

    f_EUTRA_RRCConnectionReconfigurationWithPiggyNAS(p_CellId,
                                                   p_RRC_TI,
                                                   cs_NAS_RequestWithPiggybacking(tsc_SHT_IntegrityProtected_Ciphered,
                                                                                  v_AttachAccept,
                                                                                  v_ActDefEpsBearerCtxtReq));
  } // f_TxAttachAcceptWithEquivalentPLMNList

}
