diff --git a/cmake_targets/CMakeLists.txt b/cmake_targets/CMakeLists.txt
index b24db90edbf1fb502b304d49863fd95f308d09f7..da0c3fbc1f54198c7bd7f8dde3fe876447200736 100644
--- a/cmake_targets/CMakeLists.txt
+++ b/cmake_targets/CMakeLists.txt
@@ -803,6 +803,8 @@ include_directories("${OPENAIR_DIR}/targets/ARCH/EXMIMO/USERSPACE/LIB/")
 include_directories("${OPENAIR_DIR}/targets/ARCH/EXMIMO/DEFS")
 include_directories("${OPENAIR2_DIR}/ENB_APP")
 include_directories("${OPENAIR2_DIR}/ENB_APP/CONTROL_MODULES/MAC")
+include_directories("${OPENAIR2_DIR}/ENB_APP/CONTROL_MODULES/RRC")
+include_directories("${OPENAIR2_DIR}/ENB_APP/CONTROL_MODULES/PDCP")
 include_directories("${OPENAIR2_DIR}/UTIL/OSA")
 include_directories("${OPENAIR2_DIR}/UTIL/LFDS/liblfds6.1.1/liblfds611/inc")
 include_directories("${OPENAIR2_DIR}/UTIL/LFDS/liblfds7.0.0/liblfds700/inc")
@@ -888,8 +890,12 @@ if (FLEXRAN_AGENT_SB_IF)
  add_library(FLEXRAN_AGENT
     ${OPENAIR2_DIR}/ENB_APP/flexran_agent_handler.c
     ${OPENAIR2_DIR}/ENB_APP/flexran_agent_common.c
+    ${OPENAIR2_DIR}/ENB_APP/flexran_agent_ran_api.c
+    ${OPENAIR2_DIR}/ENB_APP/flexran_agent_timer.c
     ${OPENAIR2_DIR}/ENB_APP/flexran_agent_common_internal.c
     ${OPENAIR2_DIR}/ENB_APP/CONTROL_MODULES/MAC/flexran_agent_mac.c
+    ${OPENAIR2_DIR}/ENB_APP/CONTROL_MODULES/RRC/flexran_agent_rrc.c
+    ${OPENAIR2_DIR}/ENB_APP/CONTROL_MODULES/PDCP/flexran_agent_pdcp.c
     ${OPENAIR2_DIR}/ENB_APP/flexran_agent.c
     ${OPENAIR2_DIR}/ENB_APP/flexran_agent_task_manager.c
     ${OPENAIR2_DIR}/ENB_APP/flexran_agent_net_comm.c
@@ -1189,6 +1195,7 @@ if (FLEXRAN_AGENT_SB_IF)
 
 set (MAC_SRC ${MAC_SRC}
   ${MAC_DIR}/flexran_agent_scheduler_dlsch_ue.c
+  ${MAC_DIR}/flexran_agent_scheduler_ulsch_ue.c
   ${MAC_DIR}/flexran_agent_scheduler_dataplane.c
   ${MAC_DIR}/flexran_agent_scheduler_dlsch_ue_remote.c
 )
@@ -1212,6 +1219,9 @@ if (FLEXRAN_AGENT_SB_IF)
 add_library(default_sched SHARED ${MAC_DIR}/flexran_agent_scheduler_dlsch_ue.c)
 add_library(remote_sched SHARED ${MAC_DIR}/flexran_agent_scheduler_dlsch_ue_remote.c)
 
+add_library(default_ul_sched SHARED ${MAC_DIR}/flexran_agent_scheduler_ulsch_ue.c)
+
+
 endif()
 
 # L3 Libs
@@ -1915,12 +1925,12 @@ add_executable(oaisim
 target_include_directories(oaisim PUBLIC  ${OPENAIR_TARGETS}/SIMU/USER)
 target_link_libraries (oaisim
   -Wl,-ldl,--start-group
-  RRC_LIB S1AP_LIB S1AP_ENB X2AP_LIB GTPV1U SECU_CN UTIL HASHTABLE SCTP_CLIENT UDP SCHED_LIB PHY LFDS ${MSC_LIB} L2 ${RAL_LIB} LIB_NAS_UE SIMU SECU_OSA ${ITTI_LIB}  ${MIH_LIB}
+  RRC_LIB S1AP_LIB S1AP_ENB X2AP_LIB GTPV1U SECU_CN UTIL HASHTABLE SCTP_CLIENT UDP SCHED_LIB PHY LFDS ${MSC_LIB} L2 ${RAL_LIB} LIB_NAS_UE SIMU SECU_OSA ${ITTI_LIB}  ${MIH_LIB} ${FLPT_MSG_LIB} ${ASYNC_IF_LIB} ${FLEXRAN_AGENT_LIB} LFDS7
   -Wl,--end-group )
 
 target_link_libraries (oaisim ${LIBXML2_LIBRARIES} ${LAPACK_LIBRARIES})
 target_link_libraries (oaisim pthread m ${CONFIG_LIBRARIES} rt crypt ${CRYPTO_LIBRARIES} ${OPENSSL_LIBRARIES}  ${NETTLE_LIBRARIES} sctp 
-  ${ATLAS_LIBRARIES} ${XFORMS_LIBRARIES} ${OPENPGM_LIBRARIES})
+  ${ATLAS_LIBRARIES} ${XFORMS_LIBRARIES} ${OPENPGM_LIBRARIES} ${PROTOBUF_LIB} ${CMAKE_DL_LIBS} ${LIBYAML_LIBRARIES})
 #Force link with forms, regardless XFORMS option
 target_link_libraries (oaisim forms)
 target_link_libraries (oaisim ${T_LIB})
diff --git a/common/utils/itti/intertask_interface.c b/common/utils/itti/intertask_interface.c
index 6c9a95732bccddc1d96f19f6529e4f2d980554fe..155723729128392a8fda00a3b4261bdb32e2df16 100644
--- a/common/utils/itti/intertask_interface.c
+++ b/common/utils/itti/intertask_interface.c
@@ -778,15 +778,19 @@ void itti_mark_task_ready(task_id_t task_id)
 
 void itti_exit_task(void)
 {
-#if defined(OAI_EMU) || defined(RTAI)
   task_id_t task_id = itti_get_current_task_id();
+  thread_id_t thread_id = TASK_GET_THREAD_ID(task_id);
 
+#if defined(OAI_EMU) || defined(RTAI)
   if (task_id > TASK_UNKNOWN) {
     VCD_SIGNAL_DUMPER_DUMP_VARIABLE_BY_NAME(VCD_SIGNAL_DUMPER_VARIABLE_ITTI_RECV_MSG,
                                             __sync_and_and_fetch (&itti_desc.vcd_receive_msg, ~(1L << task_id)));
   }
-
 #endif
+
+  itti_desc.threads[thread_id].task_state = TASK_STATE_NOT_CONFIGURED;
+  itti_desc.created_tasks--;
+  ITTI_DEBUG(ITTI_DEBUG_EXIT, "Thread for task %s (%d) exits\n", itti_get_task_name(task_id), task_id);
   pthread_exit (NULL);
 }
 
diff --git a/common/utils/msc/msc.c b/common/utils/msc/msc.c
index 307eeb30a51c8a1216d57f87f4c89a327a93d166..bb88b9b4b6a4441eba3b65ee40b31198efb8b5b0 100644
--- a/common/utils/msc/msc.c
+++ b/common/utils/msc/msc.c
@@ -99,6 +99,7 @@ void *msc_task(void *args_p)
         break;
 
         case TERMINATE_MESSAGE: {
+          fprintf(stderr, " *** Exiting MSC thread\n");
           timer_remove(timer_id);
     	  msc_end();
           itti_exit_task();
diff --git a/openair2/ENB_APP/CONTROL_MODULES/MAC/flexran_agent_mac.c b/openair2/ENB_APP/CONTROL_MODULES/MAC/flexran_agent_mac.c
index fcf9fb537c013180a016509d5873505b1b60c961..02350eb0c1b594300a044ac7224eda424258557f 100644
--- a/openair2/ENB_APP/CONTROL_MODULES/MAC/flexran_agent_mac.c
+++ b/openair2/ENB_APP/CONTROL_MODULES/MAC/flexran_agent_mac.c
@@ -31,6 +31,8 @@
 #include "flexran_agent_common.h"
 #include "flexran_agent_mac_internal.h"
 #include "flexran_agent_net_comm.h"
+#include "flexran_agent_timer.h"
+#include "flexran_agent_ran_api.h"
 
 #include "LAYER2/MAC/proto.h"
 #include "LAYER2/MAC/flexran_agent_mac_proto.h"
@@ -54,683 +56,499 @@ struct lfds700_ringbuffer_element *dl_mac_config_array[NUM_MAX_ENB];
 struct lfds700_ringbuffer_state ringbuffer_state[NUM_MAX_ENB];
 
 
-int flexran_agent_mac_handle_stats(mid_t mod_id, const void *params, Protocol__FlexranMessage **msg){
+int flexran_agent_mac_stats_reply(mid_t mod_id,       
+          const report_config_t *report_config,
+           Protocol__FlexUeStatsReport **ue_report,
+           Protocol__FlexCellStatsReport **cell_report) {
 
-  // TODO: Must deal with sanitization of input
-  // TODO: Must check if RNTIs and cell ids of the request actually exist
-  // TODO: Must resolve conflicts among stats requests
 
-  int i;
-  err_code_t err_code;
-  xid_t xid;
-  uint32_t usec_interval, sec_interval;
-
-  //TODO: We do not deal with multiple CCs at the moment and eNB id is 0
+  // Protocol__FlexHeader *header;
+  int i, j, k;
+  // int cc_id = 0;
   int enb_id = mod_id;
 
-  //eNB_MAC_INST *eNB = &eNB_mac_inst[enb_id];
-  //UE_list_t *eNB_UE_list=  &eNB->UE_list;
-
-  report_config_t report_config;
-
-  uint32_t ue_flags = 0;
-  uint32_t c_flags = 0;
-
-  Protocol__FlexranMessage *input = (Protocol__FlexranMessage *)params;
-
-  Protocol__FlexStatsRequest *stats_req = input->stats_request_msg;
-  xid = (stats_req->header)->xid;
-
-  // Check the type of request that is made
-  switch(stats_req->body_case) {
-  case PROTOCOL__FLEX_STATS_REQUEST__BODY_COMPLETE_STATS_REQUEST: ;
-    Protocol__FlexCompleteStatsRequest *comp_req = stats_req->complete_stats_request;
-    if (comp_req->report_frequency == PROTOCOL__FLEX_STATS_REPORT_FREQ__FLSRF_OFF) {
-      /*Disable both periodic and continuous updates*/
-      flexran_agent_disable_cont_mac_stats_update(mod_id);
-      flexran_agent_destroy_timer_by_task_id(xid);
-      *msg = NULL;
-      return 0;
-    } else { //One-off, periodical or continuous reporting
-      //Set the proper flags
-      ue_flags = comp_req->ue_report_flags;
-      c_flags = comp_req->cell_report_flags;
-      //Create a list of all eNB RNTIs and cells
-
-      //Set the number of UEs and create list with their RNTIs stats configs
-      report_config.nr_ue = flexran_get_num_ues(mod_id); //eNB_UE_list->num_UEs
-      report_config.ue_report_type = (ue_report_type_t *) malloc(sizeof(ue_report_type_t) * report_config.nr_ue);
-      if (report_config.ue_report_type == NULL) {
-	// TODO: Add appropriate error code
-	err_code = -100;
-	goto error;
-      }
-      for (i = 0; i < report_config.nr_ue; i++) {
-	report_config.ue_report_type[i].ue_rnti = flexran_get_ue_crnti(enb_id, i); //eNB_UE_list->eNB_UE_stats[UE_PCCID(enb_id,i)][i].crnti;
-	report_config.ue_report_type[i].ue_report_flags = ue_flags;
-      }
-      //Set the number of CCs and create a list with the cell stats configs
-      report_config.nr_cc = MAX_NUM_CCs;
-      report_config.cc_report_type = (cc_report_type_t *) malloc(sizeof(cc_report_type_t) * report_config.nr_cc);
-      if (report_config.cc_report_type == NULL) {
-	// TODO: Add appropriate error code
-	err_code = -100;
-	goto error;
-      }
-      for (i = 0; i < report_config.nr_cc; i++) {
-	//TODO: Must fill in the proper cell ids
-	report_config.cc_report_type[i].cc_id = i;
-	report_config.cc_report_type[i].cc_report_flags = c_flags;
-      }
-      /* Check if request was periodical */
-      if (comp_req->report_frequency == PROTOCOL__FLEX_STATS_REPORT_FREQ__FLSRF_PERIODICAL) {
-	/* Create a one off flexran message as an argument for the periodical task */
-	Protocol__FlexranMessage *timer_msg;
-	stats_request_config_t request_config;
-	request_config.report_type = PROTOCOL__FLEX_STATS_TYPE__FLST_COMPLETE_STATS;
-	request_config.report_frequency = PROTOCOL__FLEX_STATS_REPORT_FREQ__FLSRF_ONCE;
-	request_config.period = 0;
-	/* Need to make sure that the ue flags are saved (Bug) */
-	if (report_config.nr_ue == 0) {
-	  report_config.nr_ue = 1;
-	  report_config.ue_report_type = (ue_report_type_t *) malloc(sizeof(ue_report_type_t));
-	   if (report_config.ue_report_type == NULL) {
-	     // TODO: Add appropriate error code
-	     err_code = -100;
-	     goto error;
-	   }
-	   report_config.ue_report_type[0].ue_rnti = 0; // Dummy value
-	   report_config.ue_report_type[0].ue_report_flags = ue_flags;
-	}
-	request_config.config = &report_config;
-	flexran_agent_mac_stats_request(enb_id, xid, &request_config, &timer_msg);
-	/* Create a timer */
-	long timer_id = 0;
-	flexran_agent_timer_args_t *timer_args;
-	timer_args = malloc(sizeof(flexran_agent_timer_args_t));
-	memset (timer_args, 0, sizeof(flexran_agent_timer_args_t));
-	timer_args->mod_id = enb_id;
-	timer_args->msg = timer_msg;
-	/*Convert subframes to usec time*/
-	usec_interval = 1000*comp_req->sf;
-	sec_interval = 0;
-	/*add seconds if required*/
-	if (usec_interval >= 1000*1000) {
-	  sec_interval = usec_interval/(1000*1000);
-	  usec_interval = usec_interval%(1000*1000);
-	}
-	flexran_agent_create_timer(sec_interval, usec_interval, FLEXRAN_AGENT_DEFAULT, enb_id, FLEXRAN_AGENT_TIMER_TYPE_PERIODIC, xid, flexran_agent_handle_timed_task,(void*) timer_args, &timer_id);
-      } else if (comp_req->report_frequency == PROTOCOL__FLEX_STATS_REPORT_FREQ__FLSRF_CONTINUOUS) {
-	/*If request was for continuous updates, disable the previous configuration and
-	  set up a new one*/
-	flexran_agent_disable_cont_mac_stats_update(mod_id);
-	stats_request_config_t request_config;
-	request_config.report_type = PROTOCOL__FLEX_STATS_TYPE__FLST_COMPLETE_STATS;
-	request_config.report_frequency = PROTOCOL__FLEX_STATS_REPORT_FREQ__FLSRF_ONCE;
-	request_config.period = 0;
-	/* Need to make sure that the ue flags are saved (Bug) */
-	if (report_config.nr_ue == 0) {
-	  report_config.nr_ue = 1;
-	  report_config.ue_report_type = (ue_report_type_t *) malloc(sizeof(ue_report_type_t));
-	  if (report_config.ue_report_type == NULL) {
-	    // TODO: Add appropriate error code
-	    err_code = -100;
-	    goto error;
-	  }
-	  report_config.ue_report_type[0].ue_rnti = 0; // Dummy value
-	  report_config.ue_report_type[0].ue_report_flags = ue_flags;
-	}
-	request_config.config = &report_config;
-	flexran_agent_enable_cont_mac_stats_update(enb_id, xid, &request_config);
-      }
-    }
-    break;
-  case PROTOCOL__FLEX_STATS_REQUEST__BODY_CELL_STATS_REQUEST:;
-    Protocol__FlexCellStatsRequest *cell_req = stats_req->cell_stats_request;
-    // UE report config will be blank
-    report_config.nr_ue = 0;
-    report_config.ue_report_type = NULL;
-    report_config.nr_cc = cell_req->n_cell;
-    report_config.cc_report_type = (cc_report_type_t *) malloc(sizeof(cc_report_type_t) * report_config.nr_cc);
-    if (report_config.cc_report_type == NULL) {
-      // TODO: Add appropriate error code
-      err_code = -100;
-      goto error;
-    }
-    for (i = 0; i < report_config.nr_cc; i++) {
-	//TODO: Must fill in the proper cell ids
-      report_config.cc_report_type[i].cc_id = cell_req->cell[i];
-      report_config.cc_report_type[i].cc_report_flags = cell_req->flags;
-    }
-    break;
-  case PROTOCOL__FLEX_STATS_REQUEST__BODY_UE_STATS_REQUEST:;
-    Protocol__FlexUeStatsRequest *ue_req = stats_req->ue_stats_request;
-    // Cell report config will be blank
-    report_config.nr_cc = 0;
-    report_config.cc_report_type = NULL;
-    report_config.nr_ue = ue_req->n_rnti;
-    report_config.ue_report_type = (ue_report_type_t *) malloc(sizeof(ue_report_type_t) * report_config.nr_ue);
-    if (report_config.ue_report_type == NULL) {
-      // TODO: Add appropriate error code
-      err_code = -100;
-      goto error;
-    }
-    for (i = 0; i < report_config.nr_ue; i++) {
-      report_config.ue_report_type[i].ue_rnti = ue_req->rnti[i];
-      report_config.ue_report_type[i].ue_report_flags = ue_req->flags;
-    }
-    break;
-  default:
-    //TODO: Add appropriate error code
-    err_code = -100;
-    goto error;
-  }
+  /* Allocate memory for list of UE reports */
+  if (report_config->nr_ue > 0) {
 
-  if (flexran_agent_mac_stats_reply(enb_id, xid, &report_config, msg) < 0 ){
-    err_code = PROTOCOL__FLEXRAN_ERR__MSG_BUILD;
-    goto error;
-  }
+          
+          for (i = 0; i < report_config->nr_ue; i++) {
+
+
+
+                /* Check flag for creation of buffer status report */
+                if (report_config->ue_report_type[i].ue_report_flags & PROTOCOL__FLEX_UE_STATS_TYPE__FLUST_BSR) {
+                      //TODO should be automated
+                        ue_report[i]->n_bsr = 4; 
+                        uint32_t *elem;
+                        elem = (uint32_t *) malloc(sizeof(uint32_t)*ue_report[i]->n_bsr);
+                        if (elem == NULL)
+                               goto error;
+                        for (j = 0; j < ue_report[i]->n_bsr; j++) {
+                                // NN: we need to know the cc_id here, consider the first one 
+                                elem[j] = flexran_get_ue_bsr (enb_id, i, j); 
+                        }
+                          
+                        ue_report[i]->bsr = elem;
+                }
+                
+                /* Check flag for creation of PHR report */
+                if (report_config->ue_report_type[i].ue_report_flags & PROTOCOL__FLEX_UE_STATS_TYPE__FLUST_PHR) {
+                        ue_report[i]->phr = flexran_get_ue_phr (enb_id, i); // eNB_UE_list->UE_template[UE_PCCID(enb_id,i)][i].phr_info;
+                        ue_report[i]->has_phr = 1;
+                      
+                }
+
+                /* Check flag for creation of RLC buffer status report */
+                if (report_config->ue_report_type[i].ue_report_flags & PROTOCOL__FLEX_UE_STATS_TYPE__FLUST_RLC_BS) {
+                        ue_report[i]->n_rlc_report = 3; // Set this to the number of LCs for this UE. This needs to be generalized for for LCs
+                        Protocol__FlexRlcBsr ** rlc_reports;
+                        rlc_reports = malloc(sizeof(Protocol__FlexRlcBsr *) * ue_report[i]->n_rlc_report);
+                        if (rlc_reports == NULL)
+                              goto error;
+
+                        // NN: see LAYER2/openair2_proc.c for rlc status
+                        for (j = 0; j < ue_report[i]->n_rlc_report; j++) {
+
+                              rlc_reports[j] = malloc(sizeof(Protocol__FlexRlcBsr));
+                              if (rlc_reports[j] == NULL)
+                                 goto error;
+                              protocol__flex_rlc_bsr__init(rlc_reports[j]);
+                              rlc_reports[j]->lc_id = j+1;
+                              rlc_reports[j]->has_lc_id = 1;
+                              rlc_reports[j]->tx_queue_size = flexran_get_tx_queue_size(enb_id, i, j + 1);
+                              rlc_reports[j]->has_tx_queue_size = 1;
+
+                              //TODO:Set tx queue head of line delay in ms
+                              rlc_reports[j]->tx_queue_hol_delay = flexran_get_hol_delay(enb_id, i, j + 1);
+                              rlc_reports[j]->has_tx_queue_hol_delay = 1;
+                              //TODO:Set retransmission queue size in bytes
+                              rlc_reports[j]->retransmission_queue_size = 10;
+                              rlc_reports[j]->has_retransmission_queue_size = 0;
+                              //TODO:Set retransmission queue head of line delay in ms
+                              rlc_reports[j]->retransmission_queue_hol_delay = 100;
+                              rlc_reports[j]->has_retransmission_queue_hol_delay = 0;
+                              //TODO DONE:Set current size of the pending message in bytes
+                              rlc_reports[j]->status_pdu_size = flexran_get_num_pdus_buffer(enb_id , i, j + 1);
+                              rlc_reports[j]->has_status_pdu_size = 1;
+
+                        }
+                        // Add RLC buffer status reports to the full report
+                        if (ue_report[i]->n_rlc_report > 0)
+                            ue_report[i]->rlc_report = rlc_reports;
+
+                      
+                }
+
+                /* Check flag for creation of MAC CE buffer status report */
+                if (report_config->ue_report_type[i].ue_report_flags & PROTOCOL__FLEX_UE_STATS_TYPE__FLUST_MAC_CE_BS) {
+                        // TODO: Fill in the actual MAC CE buffer status report
+                        ue_report[i]->pending_mac_ces = (flexran_get_MAC_CE_bitmap_TA(enb_id,i,0) | (0 << 1) | (0 << 2) | (0 << 3)) & 15; 
+                                      // Use as bitmap. Set one or more of the; /* Use as bitmap. Set one or more of the
+                                       // PROTOCOL__FLEX_CE_TYPE__FLPCET_ values
+                                       // found in stats_common.pb-c.h. See
+                                       // flex_ce_type in FlexRAN specification 
+                        ue_report[i]->has_pending_mac_ces = 1;
+                  
+                }
+
+                /* Check flag for creation of DL CQI report */
+                if (report_config->ue_report_type[i].ue_report_flags & PROTOCOL__FLEX_UE_STATS_TYPE__FLUST_DL_CQI) {
+                        // TODO: Fill in the actual DL CQI report for the UE based on its configuration
+                        Protocol__FlexDlCqiReport * dl_report;
+                        dl_report = malloc(sizeof(Protocol__FlexDlCqiReport));
+                        if (dl_report == NULL)
+                          goto error;
+                        protocol__flex_dl_cqi_report__init(dl_report);
+
+                        dl_report->sfn_sn = flexran_get_sfn_sf(enb_id);
+                        dl_report->has_sfn_sn = 1;
+                        //Set the number of DL CQI reports for this UE. One for each CC
+                        dl_report->n_csi_report = flexran_get_active_CC(enb_id,i);
+                        dl_report->n_csi_report = 1 ;
+                        //Create the actual CSI reports.
+                        Protocol__FlexDlCsi **csi_reports;
+                        csi_reports = malloc(sizeof(Protocol__FlexDlCsi *)*dl_report->n_csi_report);
+                        if (csi_reports == NULL)
+                          goto error;                    
+                        for (j = 0; j < dl_report->n_csi_report; j++) {
+
+                              csi_reports[j] = malloc(sizeof(Protocol__FlexDlCsi));
+                              if (csi_reports[j] == NULL)
+                                goto error;
+                              protocol__flex_dl_csi__init(csi_reports[j]);
+                              //The servCellIndex for this report
+                              csi_reports[j]->serv_cell_index = j;
+                              csi_reports[j]->has_serv_cell_index = 1;
+                              //The rank indicator value for this cc
+                              csi_reports[j]->ri = flexran_get_current_RI(enb_id,i,j);
+                              csi_reports[j]->has_ri = 1;
+                              //TODO: the type of CSI report based on the configuration of the UE
+                              //For now we only support type P10, which only needs a wideband value
+                              //The full set of types can be found in stats_common.pb-c.h and
+                              //in the FlexRAN specifications
+                              csi_reports[j]->type =  PROTOCOL__FLEX_CSI_TYPE__FLCSIT_P10;
+                              csi_reports[j]->has_type = 1;
+                              csi_reports[j]->report_case = PROTOCOL__FLEX_DL_CSI__REPORT_P10CSI;
+
+                              if(csi_reports[j]->report_case == PROTOCOL__FLEX_DL_CSI__REPORT_P10CSI){
+
+                                    Protocol__FlexCsiP10 *csi10;
+                                    csi10 = malloc(sizeof(Protocol__FlexCsiP10));
+                                    if (csi10 == NULL)
+                                    goto error;
+                                    protocol__flex_csi_p10__init(csi10);
+                                    //TODO: set the wideband value
+                                    // NN: this is also depends on cc_id
+                                    csi10->wb_cqi = flexran_get_ue_wcqi (enb_id, i); //eNB_UE_list->eNB_UE_stats[UE_PCCID(enb_id,i)][i].dl_cqi;
+                                    csi10->has_wb_cqi = 1;
+                                    //Add the type of measurements to the csi report in the proper union type
+                                    csi_reports[j]->p10csi = csi10;
+                              }
+
+                              else if(csi_reports[j]->report_case == PROTOCOL__FLEX_DL_CSI__REPORT_P11CSI){
+
+
+                                    Protocol__FlexCsiP11 *csi11;
+                                    csi11 = malloc(sizeof(Protocol__FlexCsiP11));
+                                    if (csi11 == NULL)
+                                    goto error;
+                                    protocol__flex_csi_p11__init(csi11);
+                                  
+                                    csi11->wb_cqi = malloc(sizeof(csi11->wb_cqi));  
+				    csi11->n_wb_cqi = 1;
+				    csi11->wb_cqi[0] = flexran_get_ue_wcqi (enb_id, i);                                       		    
+                                    // According To spec 36.213                                  
+                                     
+                                    if (flexran_get_antenna_ports(enb_id, j) == 2 && csi_reports[j]->ri == 1) {
+                                        // TODO PMI
+                                        csi11->wb_pmi = flexran_get_ue_pmi(enb_id);                          
+                                        csi11->has_wb_pmi = 1;
+
+                                       }   
+
+                                      else if (flexran_get_antenna_ports(enb_id, j) == 2 && csi_reports[j]->ri == 2){
+                                        // TODO PMI
+                                        csi11->wb_pmi = flexran_get_ue_pmi(enb_id);                                      
+                                        csi11->has_wb_pmi = 1;
+
+                                      }
+
+                                      else if (flexran_get_antenna_ports(enb_id, j) == 4 && csi_reports[j]->ri == 2){
+                                        // TODO PMI
+                                        csi11->wb_pmi = flexran_get_ue_pmi(enb_id);                                      
+                                        csi11->has_wb_pmi = 1;
+
+
+                                      }
+
+                                      csi11->has_wb_pmi = 0;                                      
+
+                                      csi_reports[j]->p11csi = csi11;
+
+                               }
+
+                                      
+                                     
+
+
+                              else if(csi_reports[j]->report_case == PROTOCOL__FLEX_DL_CSI__REPORT_P20CSI){
+
+                                    Protocol__FlexCsiP20 *csi20;
+                                    csi20 = malloc(sizeof(Protocol__FlexCsiP20));
+                                    if (csi20 == NULL)
+                                    goto error;
+                                    protocol__flex_csi_p20__init(csi20);
+                                    
+                                    csi20->wb_cqi = flexran_get_ue_wcqi (enb_id, i);                                       
+                                    csi20->has_wb_cqi = 1;
 
-  free(report_config.ue_report_type);
-  free(report_config.cc_report_type);
+                                      
+                                    csi20->bandwidth_part_index = 1 ;//TODO
+                                    csi20->has_bandwidth_part_index = 1;
 
-  return 0;
+                                    csi20->sb_index = 1 ;//TODO
+                                    csi20->has_sb_index = 1 ;                                     
 
- error :
-  LOG_E(FLEXRAN_AGENT, "errno %d occured\n", err_code);
-  return err_code;
-}
 
-int flexran_agent_mac_stats_request(mid_t mod_id,
-				    xid_t xid,
-				    const stats_request_config_t *report_config,
-				    Protocol__FlexranMessage **msg) {
-  Protocol__FlexHeader *header;
-  int i;
+                                    csi_reports[j]->p20csi = csi20;
 
-  Protocol__FlexStatsRequest *stats_request_msg;
-  stats_request_msg = malloc(sizeof(Protocol__FlexStatsRequest));
-  if(stats_request_msg == NULL)
-    goto error;
-  protocol__flex_stats_request__init(stats_request_msg);
 
-  if (flexran_create_header(xid, PROTOCOL__FLEX_TYPE__FLPT_STATS_REQUEST, &header) != 0)
-    goto error;
+                              }
 
-  stats_request_msg->header = header;
+                              else if(csi_reports[j]->report_case == PROTOCOL__FLEX_DL_CSI__REPORT_P21CSI){
 
-  stats_request_msg->type = report_config->report_type;
-  stats_request_msg->has_type = 1;
+                                  // Protocol__FlexCsiP21 *csi21;
+                                  // csi21 = malloc(sizeof(Protocol__FlexCsiP21));
+                                  // if (csi21 == NULL)
+                                  // goto error;
+                                  // protocol__flex_csi_p21__init(csi21);
+                                
+                                  // csi21->wb_cqi = flexran_get_ue_wcqi (enb_id, i);                                       
+                                  
+                                  
+                                  // csi21->wb_pmi = flexran_get_ue_pmi(enb_id); //TDO inside
+                                  // csi21->has_wb_pmi = 1;
 
-  switch (report_config->report_type) {
-  case PROTOCOL__FLEX_STATS_TYPE__FLST_COMPLETE_STATS:
-    stats_request_msg->body_case =  PROTOCOL__FLEX_STATS_REQUEST__BODY_COMPLETE_STATS_REQUEST;
-    Protocol__FlexCompleteStatsRequest *complete_stats;
-    complete_stats = malloc(sizeof(Protocol__FlexCompleteStatsRequest));
-    if(complete_stats == NULL)
-      goto error;
-    protocol__flex_complete_stats_request__init(complete_stats);
-    complete_stats->report_frequency = report_config->report_frequency;
-    complete_stats->has_report_frequency = 1;
-    complete_stats->sf = report_config->period;
-    complete_stats->has_sf = 1;
-    complete_stats->has_cell_report_flags = 1;
-    complete_stats->has_ue_report_flags = 1;
-    if (report_config->config->nr_cc > 0) {
-      complete_stats->cell_report_flags = report_config->config->cc_report_type[0].cc_report_flags;
-    }
-    if (report_config->config->nr_ue > 0) {
-      complete_stats->ue_report_flags = report_config->config->ue_report_type[0].ue_report_flags;
-    }
-    stats_request_msg->complete_stats_request = complete_stats;
-    break;
-  case  PROTOCOL__FLEX_STATS_TYPE__FLST_CELL_STATS:
-    stats_request_msg->body_case = PROTOCOL__FLEX_STATS_REQUEST__BODY_CELL_STATS_REQUEST;
-     Protocol__FlexCellStatsRequest *cell_stats;
-     cell_stats = malloc(sizeof(Protocol__FlexCellStatsRequest));
-    if(cell_stats == NULL)
-      goto error;
-    protocol__flex_cell_stats_request__init(cell_stats);
-    cell_stats->n_cell = report_config->config->nr_cc;
-    cell_stats->has_flags = 1;
-    if (cell_stats->n_cell > 0) {
-      uint32_t *cells;
-      cells = (uint32_t *) malloc(sizeof(uint32_t)*cell_stats->n_cell);
-      for (i = 0; i < cell_stats->n_cell; i++) {
-	cells[i] = report_config->config->cc_report_type[i].cc_id;
-      }
-      cell_stats->cell = cells;
-      cell_stats->flags = report_config->config->cc_report_type[i].cc_report_flags;
-    }
-    stats_request_msg->cell_stats_request = cell_stats;
-    break;
-  case PROTOCOL__FLEX_STATS_TYPE__FLST_UE_STATS:
-    stats_request_msg->body_case = PROTOCOL__FLEX_STATS_REQUEST__BODY_UE_STATS_REQUEST;
-     Protocol__FlexUeStatsRequest *ue_stats;
-     ue_stats = malloc(sizeof(Protocol__FlexUeStatsRequest));
-    if(ue_stats == NULL)
-      goto error;
-    protocol__flex_ue_stats_request__init(ue_stats);
-    ue_stats->n_rnti = report_config->config->nr_ue;
-    ue_stats->has_flags = 1;
-    if (ue_stats->n_rnti > 0) {
-      uint32_t *ues;
-      ues = (uint32_t *) malloc(sizeof(uint32_t)*ue_stats->n_rnti);
-      for (i = 0; i < ue_stats->n_rnti; i++) {
-	ues[i] = report_config->config->ue_report_type[i].ue_rnti;
-      }
-      ue_stats->rnti = ues;
-      ue_stats->flags = report_config->config->ue_report_type[i].ue_report_flags;
-    }
-    stats_request_msg->ue_stats_request = ue_stats;
-    break;
-  default:
-    goto error;
-  }
-  *msg = malloc(sizeof(Protocol__FlexranMessage));
-  if(*msg == NULL)
-    goto error;
-  protocol__flexran_message__init(*msg);
-  (*msg)->msg_case = PROTOCOL__FLEXRAN_MESSAGE__MSG_STATS_REQUEST_MSG;
-  (*msg)->msg_dir = PROTOCOL__FLEXRAN_DIRECTION__INITIATING_MESSAGE;
-  (*msg)->stats_request_msg = stats_request_msg;
-  return 0;
+                                  // csi21->sb_cqi = 1; // TODO 
+                                   
+                                  // csi21->bandwidth_part_index = 1 ; //TDO inside
+                                  // csi21->has_bandwidth_part_index = 1 ;   
 
- error:
-  // TODO: Need to make proper error handling
-  if (header != NULL)
-    free(header);
-  if (stats_request_msg != NULL)
-    free(stats_request_msg);
-  if(*msg != NULL)
-    free(*msg);
-  //LOG_E(MAC, "%s: an error occured\n", __FUNCTION__);
-  return -1;
-}
+                                  // csi21->sb_index = 1 ;//TODO
+                                  // csi21->has_sb_index = 1 ;                                     
 
-int flexran_agent_mac_destroy_stats_request(Protocol__FlexranMessage *msg) {
-   if(msg->msg_case != PROTOCOL__FLEXRAN_MESSAGE__MSG_STATS_REQUEST_MSG)
-    goto error;
-  free(msg->stats_request_msg->header);
-  if (msg->stats_request_msg->body_case == PROTOCOL__FLEX_STATS_REQUEST__BODY_CELL_STATS_REQUEST) {
-    free(msg->stats_request_msg->cell_stats_request->cell);
-  }
-  if (msg->stats_request_msg->body_case == PROTOCOL__FLEX_STATS_REQUEST__BODY_UE_STATS_REQUEST) {
-    free(msg->stats_request_msg->ue_stats_request->rnti);
-  }
-  free(msg->stats_request_msg);
-  free(msg);
-  return 0;
 
- error:
-  //LOG_E(MAC, "%s: an error occured\n", __FUNCTION__);
-  return -1;
-}
+                                  // csi_reports[j]->p20csi = csi21;
 
-int flexran_agent_mac_stats_reply(mid_t mod_id,
-				  xid_t xid,
-				  const report_config_t *report_config,
-				  Protocol__FlexranMessage **msg) {
-  Protocol__FlexHeader *header;
-  int i, j, k;
-  int enb_id = mod_id;
-  //eNB_MAC_INST *eNB = &eNB_mac_inst[enb_id];
-  //UE_list_t *eNB_UE_list=  &eNB->UE_list;
-
-  Protocol__FlexStatsReply *stats_reply_msg;
-  stats_reply_msg = malloc(sizeof(Protocol__FlexStatsReply));
-  if (stats_reply_msg == NULL)
-    goto error;
-  protocol__flex_stats_reply__init(stats_reply_msg);
-
-  if (flexran_create_header(xid, PROTOCOL__FLEX_TYPE__FLPT_STATS_REPLY, &header) != 0)
-    goto error;
-
-  stats_reply_msg->header = header;
+                              }
 
-  stats_reply_msg->n_ue_report = report_config->nr_ue;
-  stats_reply_msg->n_cell_report = report_config->nr_cc;
+                              else if(csi_reports[j]->report_case == PROTOCOL__FLEX_DL_CSI__REPORT_A12CSI){
 
-  Protocol__FlexUeStatsReport **ue_report;
-  Protocol__FlexCellStatsReport **cell_report;
-
-
-  /* Allocate memory for list of UE reports */
-  if (report_config->nr_ue > 0) {
-    ue_report = malloc(sizeof(Protocol__FlexUeStatsReport *) * report_config->nr_ue);
-    if (ue_report == NULL)
-      goto error;
-    for (i = 0; i < report_config->nr_ue; i++) {
-      ue_report[i] = malloc(sizeof(Protocol__FlexUeStatsReport));
-      protocol__flex_ue_stats_report__init(ue_report[i]);
-      ue_report[i]->rnti = report_config->ue_report_type[i].ue_rnti;
-      ue_report[i]->has_rnti = 1;
-      ue_report[i]->flags = report_config->ue_report_type[i].ue_report_flags;
-      ue_report[i]->has_flags = 1;
-      /* Check the types of reports that need to be constructed based on flag values */
-
-      /* Check flag for creation of buffer status report */
-      if (report_config->ue_report_type[i].ue_report_flags & PROTOCOL__FLEX_UE_STATS_TYPE__FLUST_BSR) {
-	ue_report[i]->n_bsr = 4;
-	uint32_t *elem;
-	elem = (uint32_t *) malloc(sizeof(uint32_t)*ue_report[i]->n_bsr);
-	if (elem == NULL)
-	  goto error;
-	for (j = 0; j < ue_report[i]->n_bsr; j++) {
-	  // NN: we need to know the cc_id here, consider the first one
-	  elem[j] = flexran_get_ue_bsr (enb_id, i, j); 
-	}
-	ue_report[i]->bsr = elem;
-      }
 
-      /* Check flag for creation of PRH report */
-      if (report_config->ue_report_type[i].ue_report_flags & PROTOCOL__FLEX_UE_STATS_TYPE__FLUST_PRH) {
-	ue_report[i]->phr = flexran_get_ue_phr (enb_id, i); // eNB_UE_list->UE_template[UE_PCCID(enb_id,i)][i].phr_info;
-	ue_report[i]->has_phr = 1;
-      }
+                                  // Protocol__FlexCsiA12 *csi12;
+                                  // csi12 = malloc(sizeof(Protocol__FlexCsiA12));
+                                  // if (csi12 == NULL)
+                                  // goto error;
+                                  // protocol__flex_csi_a12__init(csi12);
+                                
+                                  // csi12->wb_cqi = flexran_get_ue_wcqi (enb_id, i);                                       
+                                  
+                                  // csi12->sb_pmi = 1 ; //TODO inside                                                                      
 
-      /* Check flag for creation of RLC buffer status report */
-      if (report_config->ue_report_type[i].ue_report_flags & PROTOCOL__FLEX_UE_STATS_TYPE__FLUST_RLC_BS) {
-	ue_report[i]->n_rlc_report = 3; // Set this to the number of LCs for this UE. This needs to be generalized for for LCs
-	Protocol__FlexRlcBsr ** rlc_reports;
-	rlc_reports = malloc(sizeof(Protocol__FlexRlcBsr *) * ue_report[i]->n_rlc_report);
-	if (rlc_reports == NULL)
-	  goto error;
-
-	// NN: see LAYER2/openair2_proc.c for rlc status
-	for (j = 0; j < ue_report[i]->n_rlc_report; j++) {
-	  rlc_reports[j] = malloc(sizeof(Protocol__FlexRlcBsr));
-	  if (rlc_reports[j] == NULL)
-	    goto error;
-	  protocol__flex_rlc_bsr__init(rlc_reports[j]);
-	  rlc_reports[j]->lc_id = j + 1;
-	  rlc_reports[j]->has_lc_id = 1;
-	  rlc_reports[j]->tx_queue_size = flexran_get_tx_queue_size(enb_id,i,j + 1);
-	  rlc_reports[j]->has_tx_queue_size = 1;
-	  
-	  //TODO:Set tx queue head of line delay in ms
-	  rlc_reports[j]->tx_queue_hol_delay = flexran_get_hol_delay(enb_id, i, j+1);
-	  rlc_reports[j]->has_tx_queue_hol_delay = 1;
-	  //TODO:Set retransmission queue size in bytes
-	  rlc_reports[j]->retransmission_queue_size = 10;
-	  rlc_reports[j]->has_retransmission_queue_size = 0;
-	  //TODO:Set retransmission queue head of line delay in ms
-	  rlc_reports[j]->retransmission_queue_hol_delay = 100;
-	  rlc_reports[j]->has_retransmission_queue_hol_delay = 0;
-	  //TODO:Set current size of the pending message in bytes
-	  rlc_reports[j]->status_pdu_size = 100;
-	  rlc_reports[j]->has_status_pdu_size = 0;
-	}
-	// Add RLC buffer status reports to the full report
-	if (ue_report[i]->n_rlc_report > 0)
-	  ue_report[i]->rlc_report = rlc_reports;
-      }
+                                  // TODO continou
+                              }
 
-      /* Check flag for creation of MAC CE buffer status report */
-      if (report_config->ue_report_type[i].ue_report_flags & PROTOCOL__FLEX_UE_STATS_TYPE__FLUST_MAC_CE_BS) {
-	// TODO: Fill in the actual MAC CE buffer status report
-	ue_report[i]->pending_mac_ces = (flexran_get_MAC_CE_bitmap_TA(enb_id,i,0) | (0 << 1) | (0 << 2) | (0 << 3)) & 15;  /* Use as bitmap. Set one or more of the
-					       PROTOCOL__FLEX_CE_TYPE__FLPCET_ values
-					       found in stats_common.pb-c.h. See
-					       flex_ce_type in FlexRAN specification */
-	ue_report[i]->has_pending_mac_ces = 1;
-      }
+                              else if(csi_reports[j]->report_case == PROTOCOL__FLEX_DL_CSI__REPORT_A22CSI){
 
-      /* Check flag for creation of DL CQI report */
-      if (report_config->ue_report_type[i].ue_report_flags & PROTOCOL__FLEX_UE_STATS_TYPE__FLUST_DL_CQI) {
-	// TODO: Fill in the actual DL CQI report for the UE based on its configuration
-	Protocol__FlexDlCqiReport * dl_report;
-	dl_report = malloc(sizeof(Protocol__FlexDlCqiReport));
-	if (dl_report == NULL)
-	  goto error;
-	protocol__flex_dl_cqi_report__init(dl_report);
-
-	dl_report->sfn_sn = flexran_get_sfn_sf(enb_id);
-	dl_report->has_sfn_sn = 1;
-	//Set the number of DL CQI reports for this UE. One for each CC
-	dl_report->n_csi_report = flexran_get_active_CC(enb_id,i);
-
-	//Create the actual CSI reports.
-	Protocol__FlexDlCsi **csi_reports;
-	csi_reports = malloc(sizeof(Protocol__FlexDlCsi *)*dl_report->n_csi_report);
-	if (csi_reports == NULL)
-	  goto error;
-	for (j = 0; j < dl_report->n_csi_report; j++) {
-	  csi_reports[j] = malloc(sizeof(Protocol__FlexDlCsi));
-	  if (csi_reports[j] == NULL)
-	    goto error;
-	  protocol__flex_dl_csi__init(csi_reports[j]);
-	  //The servCellIndex for this report
-	  csi_reports[j]->serv_cell_index = j;
-	  csi_reports[j]->has_serv_cell_index = 1;
-	  //The rank indicator value for this cc
-	  csi_reports[j]->ri = flexran_get_current_RI(enb_id,i,j);
-	  csi_reports[j]->has_ri = 1;
-	  //TODO: the type of CSI report based on the configuration of the UE
-	  //For now we only support type P10, which only needs a wideband value
-	  //The full set of types can be found in stats_common.pb-c.h and
-	  //in the FlexRAN specifications
-    csi_reports[j]->type =  PROTOCOL__FLEX_CSI_TYPE__FLCSIT_P10;
-		  csi_reports[j]->has_type = 1;
-		  csi_reports[j]->report_case = PROTOCOL__FLEX_DL_CSI__REPORT_P10CSI;
-		  if(csi_reports[j]->report_case == PROTOCOL__FLEX_DL_CSI__REPORT_P10CSI){
-			  Protocol__FlexCsiP10 *csi10;
-			  csi10 = malloc(sizeof(Protocol__FlexCsiP10));
-			  if (csi10 == NULL)
-				goto error;
-			  protocol__flex_csi_p10__init(csi10);
-			  //TODO: set the wideband value
-			  // NN: this is also depends on cc_id
-			  csi10->wb_cqi = flexran_get_ue_wcqi (enb_id, i); //eNB_UE_list->eNB_UE_stats[UE_PCCID(enb_id,i)][i].dl_cqi;
-			  csi10->has_wb_cqi = 1;
-			  //Add the type of measurements to the csi report in the proper union type
-			  csi_reports[j]->p10csi = csi10;
-		  }
-		  else if(csi_reports[j]->report_case == PROTOCOL__FLEX_DL_CSI__REPORT_P11CSI){
-
-		  }
-		  else if(csi_reports[j]->report_case == PROTOCOL__FLEX_DL_CSI__REPORT_P20CSI){
-
-		  }
-		  else if(csi_reports[j]->report_case == PROTOCOL__FLEX_DL_CSI__REPORT_P21CSI){
-
-		  }
-		  else if(csi_reports[j]->report_case == PROTOCOL__FLEX_DL_CSI__REPORT_A12CSI){
-
-		  }
-		  else if(csi_reports[j]->report_case == PROTOCOL__FLEX_DL_CSI__REPORT_A22CSI){
-
-		  }
-		  else if(csi_reports[j]->report_case == PROTOCOL__FLEX_DL_CSI__REPORT_A20CSI){
-
-		  }
-		  else if(csi_reports[j]->report_case == PROTOCOL__FLEX_DL_CSI__REPORT_A30CSI){
-
-		  }
-		  else if(csi_reports[j]->report_case == PROTOCOL__FLEX_DL_CSI__REPORT_A31CSI){
-
-		  }
-		}
-	//Add the csi reports to the full DL CQI report
-	dl_report->csi_report = csi_reports;
-	//Add the DL CQI report to the stats report
-	ue_report[i]->dl_cqi_report = dl_report;
-      }
+                                    // Protocol__FlexCsiA22 *csi22;
+                                    // csi22 = malloc(sizeof(Protocol__FlexCsiA22));
+                                    // if (csi22 == NULL)
+                                    // goto error;
+                                    // protocol__flex_csi_a22__init(csi22);
+                                  
+                                    // csi22->wb_cqi = flexran_get_ue_wcqi (enb_id, i);                                       
+                                    
+                                    // csi22->sb_cqi = 1 ; //TODO inside                                      
 
-      /* Check flag for creation of paging buffer status report */
-      if (report_config->ue_report_type[i].ue_report_flags & PROTOCOL__FLEX_UE_STATS_TYPE__FLUST_PBS) {
-	//TODO: Fill in the actual paging buffer status report. For this field to be valid, the RNTI
-	//set in the report must be a P-RNTI
-	Protocol__FlexPagingBufferReport *paging_report;
-	paging_report = malloc(sizeof(Protocol__FlexPagingBufferReport));
-	if (paging_report == NULL)
-	  goto error;
-	protocol__flex_paging_buffer_report__init(paging_report);
-	//Set the number of pending paging messages
-	paging_report->n_paging_info = 1;
-	//Provide a report for each pending paging message
-	Protocol__FlexPagingInfo **p_info;
-	p_info = malloc(sizeof(Protocol__FlexPagingInfo *) * paging_report->n_paging_info);
-	if (p_info == NULL)
-	  goto error;
-	for (j = 0; j < paging_report->n_paging_info; j++) {
-	  p_info[j] = malloc(sizeof(Protocol__FlexPagingInfo));
-	  if(p_info[j] == NULL)
-	    goto error;
-	  protocol__flex_paging_info__init(p_info[j]);
-	  //TODO: Set paging index. This index is the same that will be used for the scheduling of the
-	  //paging message by the controller
-	  p_info[j]->paging_index = 10;
-	  p_info[j]->has_paging_index = 0;
-	  //TODO:Set the paging message size
-	  p_info[j]->paging_message_size = 100;
-	  p_info[j]->has_paging_message_size = 0;
-	  //TODO: Set the paging subframe
-	  p_info[j]->paging_subframe = 10;
-	  p_info[j]->has_paging_subframe = 0;
-	  //TODO: Set the carrier index for the pending paging message
-	  p_info[j]->carrier_index = 0;
-	  p_info[j]->has_carrier_index = 0;
-	}
-	//Add all paging info to the paging buffer rerport
-	paging_report->paging_info = p_info;
-	//Add the paging report to the UE report
-	ue_report[i]->pbr = paging_report;
-      }
+                                    // csi22->wb_pmi = flexran_get_ue_wcqi (enb_id, i);                                       
+                                    // csi22->has_wb_pmi = 1;
+                                    
+                                    // csi22->sb_pmi = 1 ; //TODO inside                                                                            
+                                    // csi22->has_wb_pmi = 1;
 
-      /* Check flag for creation of UL CQI report */
-      if (report_config->ue_report_type[i].ue_report_flags & PROTOCOL__FLEX_UE_STATS_TYPE__FLUST_UL_CQI) {
-	//Fill in the full UL CQI report of the UE
-	Protocol__FlexUlCqiReport *full_ul_report;
-	full_ul_report = malloc(sizeof(Protocol__FlexUlCqiReport));
-	if(full_ul_report == NULL)
-	  goto error;
-	protocol__flex_ul_cqi_report__init(full_ul_report);
-	//TODO:Set the SFN and SF of the generated report
-	full_ul_report->sfn_sn = flexran_get_sfn_sf(enb_id);
-	full_ul_report->has_sfn_sn = 1;
-	//TODO:Set the number of UL measurement reports based on the types of measurements
-	//configured for this UE and on the servCellIndex
-	full_ul_report->n_cqi_meas = 1;
-	Protocol__FlexUlCqi **ul_report;
-	ul_report = malloc(sizeof(Protocol__FlexUlCqi *) * full_ul_report->n_cqi_meas);
-	if(ul_report == NULL)
-	  goto error;
-	//Fill each UL report of the UE for each of the configured report types
-	for(j = 0; j < full_ul_report->n_cqi_meas; j++) {
-	  ul_report[j] = malloc(sizeof(Protocol__FlexUlCqi));
-	  if(ul_report[j] == NULL)
-	  goto error;
-	  protocol__flex_ul_cqi__init(ul_report[j]);
-	  //TODO: Set the type of the UL report. As an example set it to SRS UL report
-	  // See enum flex_ul_cqi_type in FlexRAN specification for more details
-	  ul_report[j]->type = PROTOCOL__FLEX_UL_CQI_TYPE__FLUCT_SRS;
-	  ul_report[j]->has_type = 1;
-	  //TODO:Set the number of SINR measurements based on the report type
-	  //See struct flex_ul_cqi in FlexRAN specification for more details
-	  ul_report[j]->n_sinr = 0;
-	  uint32_t *sinr_meas;
-	  sinr_meas = (uint32_t *) malloc(sizeof(uint32_t) * ul_report[j]->n_sinr);
-	  if (sinr_meas == NULL)
-	    goto error;
-	  //TODO:Set the SINR measurements for the specified type
-	  for (k = 0; k < ul_report[j]->n_sinr; k++) {
-	    sinr_meas[k] = 10;
-	  }
-	  ul_report[j]->sinr = sinr_meas;
-	  //TODO: Set the servCellIndex for this report
-	  ul_report[j]->serv_cell_index = 0;
-	  ul_report[j]->has_serv_cell_index = 1;
-	  
-	  //Set the list of UL reports of this UE to the full UL report
-	  full_ul_report->cqi_meas = ul_report;
-
-	  full_ul_report->n_pucch_dbm = MAX_NUM_CCs;
-	  full_ul_report->pucch_dbm = malloc(sizeof(Protocol__FlexPucchDbm *) * full_ul_report->n_pucch_dbm);
-
-	  for (j = 0; j < MAX_NUM_CCs; j++) {
-	    full_ul_report->pucch_dbm[j] = malloc(sizeof(Protocol__FlexPucchDbm));
-	    protocol__flex_pucch_dbm__init(full_ul_report->pucch_dbm[j]);
-	    full_ul_report->pucch_dbm[j]->has_serv_cell_index = 1;
-	    full_ul_report->pucch_dbm[j]->serv_cell_index = j;
-	    if(flexran_get_p0_pucch_dbm(enb_id,i, j) != -1){
-	      full_ul_report->pucch_dbm[j]->p0_pucch_dbm = flexran_get_p0_pucch_dbm(enb_id,i,j);
-	      full_ul_report->pucch_dbm[j]->has_p0_pucch_dbm = 1;
-	    }
-	    full_ul_report->pucch_dbm[j]->has_p0_pucch_updated = 1;
-	    full_ul_report->pucch_dbm[j]->p0_pucch_updated = flexran_get_p0_pucch_status(enb_id, i, j);
-	  }
+                                    // csi22->sb_list = flexran_get_ue_wcqi (enb_id, i);                                       
 
-	  //Add full UL CQI report to the UE report
-	  ue_report[i]->ul_cqi_report = full_ul_report;
-	}
-      }
-    }
-    /* Add list of all UE reports to the message */
-    stats_reply_msg->ue_report = ue_report;
-  }
+
+                                }
+
+                                else if(csi_reports[j]->report_case == PROTOCOL__FLEX_DL_CSI__REPORT_A20CSI){
+
+                                    // Protocol__FlexCsiA20 *csi20;
+                                    // csi20 = malloc(sizeof(Protocol__FlexCsiA20));
+                                    // if (csi20 == NULL)
+                                    // goto error;
+                                    // protocol__flex_csi_a20__init(csi20);
+
+                                    // csi20->wb_cqi = flexran_get_ue_wcqi (enb_id, i);                                       
+                                    // csi20->has_wb_cqi = 1;
+
+                                    // csi20>sb_cqi = 1 ; //TODO inside                                      
+                                    // csi20>has_sb_cqi = 1 ;
+
+                                    // csi20->sb_list = 1; // TODO inside
+
+
+                                }
+
+                                else if(csi_reports[j]->report_case == PROTOCOL__FLEX_DL_CSI__REPORT_A30CSI){
+
+                                }
+
+                                else if(csi_reports[j]->report_case == PROTOCOL__FLEX_DL_CSI__REPORT_A31CSI){
+
+                                }
+
+                        }
+                     //Add the csi reports to the full DL CQI report
+                    dl_report->csi_report = csi_reports;
+                    //Add the DL CQI report to the stats report
+                     ue_report[i]->dl_cqi_report = dl_report;
+                      
+                }
+
+                /* Check flag for creation of paging buffer status report */
+                if (report_config->ue_report_type[i].ue_report_flags & PROTOCOL__FLEX_UE_STATS_TYPE__FLUST_PBS) {
+                            //TODO: Fill in the actual paging buffer status report. For this field to be valid, the RNTI
+                            //set in the report must be a P-RNTI
+                            Protocol__FlexPagingBufferReport *paging_report;
+                            paging_report = malloc(sizeof(Protocol__FlexPagingBufferReport));
+                            if (paging_report == NULL)
+                              goto error;
+                            protocol__flex_paging_buffer_report__init(paging_report);
+                            //Set the number of pending paging messages
+                            paging_report->n_paging_info = 1;
+                            //Provide a report for each pending paging message
+                            Protocol__FlexPagingInfo **p_info;
+                            p_info = malloc(sizeof(Protocol__FlexPagingInfo *) * paging_report->n_paging_info);
+                            if (p_info == NULL)
+                              goto error;
+
+                            for (j = 0; j < paging_report->n_paging_info; j++) {
+
+                                    p_info[j] = malloc(sizeof(Protocol__FlexPagingInfo));
+                                    if(p_info[j] == NULL)
+                                      goto error;
+                                    protocol__flex_paging_info__init(p_info[j]);
+                                    //TODO: Set paging index. This index is the same that will be used for the scheduling of the
+                                    //paging message by the controller
+                                    p_info[j]->paging_index = 10;
+                                    p_info[j]->has_paging_index = 1;
+                                    //TODO:Set the paging message size
+                                    p_info[j]->paging_message_size = 100;
+                                    p_info[j]->has_paging_message_size = 1;
+                                    //TODO: Set the paging subframe
+                                    p_info[j]->paging_subframe = 10;
+                                    p_info[j]->has_paging_subframe = 1;
+                                    //TODO: Set the carrier index for the pending paging message
+                                    p_info[j]->carrier_index = 0;
+                                    p_info[j]->has_carrier_index = 1;
+
+                            }
+                            //Add all paging info to the paging buffer rerport
+                            paging_report->paging_info = p_info;
+                            //Add the paging report to the UE report
+                            ue_report[i]->pbr = paging_report;
+                }
+
+                  /* Check flag for creation of UL CQI report */
+                if (report_config->ue_report_type[i].ue_report_flags & PROTOCOL__FLEX_UE_STATS_TYPE__FLUST_UL_CQI) {
+
+                      //Fill in the full UL CQI report of the UE
+                      Protocol__FlexUlCqiReport *full_ul_report;
+                      full_ul_report = malloc(sizeof(Protocol__FlexUlCqiReport));
+                      if(full_ul_report == NULL)
+                        goto error;
+                      protocol__flex_ul_cqi_report__init(full_ul_report);
+                      //TODO:Set the SFN and SF of the generated report
+                      full_ul_report->sfn_sn = flexran_get_sfn_sf(enb_id);
+                      full_ul_report->has_sfn_sn = 1;
+                      //TODO:Set the number of UL measurement reports based on the types of measurements
+                      //configured for this UE and on the servCellIndex
+                      full_ul_report->n_cqi_meas = 1;
+                      Protocol__FlexUlCqi **ul_report;
+                      ul_report = malloc(sizeof(Protocol__FlexUlCqi *) * full_ul_report->n_cqi_meas);
+                      if(ul_report == NULL)
+                        goto error;
+                      //Fill each UL report of the UE for each of the configured report types
+                      for(j = 0; j < full_ul_report->n_cqi_meas; j++) {
+
+                              ul_report[j] = malloc(sizeof(Protocol__FlexUlCqi));
+                              if(ul_report[j] == NULL)
+                              goto error;
+                              protocol__flex_ul_cqi__init(ul_report[j]);
+                              //TODO: Set the type of the UL report. As an example set it to SRS UL report
+                              // See enum flex_ul_cqi_type in FlexRAN specification for more details
+                              ul_report[j]->type = PROTOCOL__FLEX_UL_CQI_TYPE__FLUCT_SRS;
+                              ul_report[j]->has_type = 1;
+                              //TODO:Set the number of SINR measurements based on the report type
+                              //See struct flex_ul_cqi in FlexRAN specification for more details
+                              ul_report[j]->n_sinr = 0;
+                              uint32_t *sinr_meas;
+                              sinr_meas = (uint32_t *) malloc(sizeof(uint32_t) * ul_report[j]->n_sinr);
+                              if (sinr_meas == NULL)
+                                goto error;
+                              //TODO:Set the SINR measurements for the specified type
+                              for (k = 0; k < ul_report[j]->n_sinr; k++) {
+                                      sinr_meas[k] = 10;
+                              }
+                              ul_report[j]->sinr = sinr_meas;
+                              //TODO: Set the servCellIndex for this report
+                              ul_report[j]->serv_cell_index = 0;
+                              ul_report[j]->has_serv_cell_index = 1;
+                              
+                              //Set the list of UL reports of this UE to the full UL report
+                              full_ul_report->cqi_meas = ul_report;
+
+                              full_ul_report->n_pucch_dbm = MAX_NUM_CCs;
+                              full_ul_report->pucch_dbm = malloc(sizeof(Protocol__FlexPucchDbm *) * full_ul_report->n_pucch_dbm);
+
+                              for (j = 0; j < MAX_NUM_CCs; j++) {
+
+                                      full_ul_report->pucch_dbm[j] = malloc(sizeof(Protocol__FlexPucchDbm));
+                                      protocol__flex_pucch_dbm__init(full_ul_report->pucch_dbm[j]);
+                                      full_ul_report->pucch_dbm[j]->has_serv_cell_index = 1;
+                                      full_ul_report->pucch_dbm[j]->serv_cell_index = j;
+
+                                      if(flexran_get_p0_pucch_dbm(enb_id,i, j) != -1){
+                                        full_ul_report->pucch_dbm[j]->p0_pucch_dbm = flexran_get_p0_pucch_dbm(enb_id,i,j);
+                                        full_ul_report->pucch_dbm[j]->has_p0_pucch_dbm = 1;
+                                      }
+                              }
+
+
+                          }
+                        //  Add full UL CQI report to the UE report
+                        ue_report[i]->ul_cqi_report = full_ul_report;
+                      
+
+                     }    
+                             
+                 
+
+                            
+             }       
+
+          
+         
+         
+     } 
 
   /* Allocate memory for list of cell reports */
   if (report_config->nr_cc > 0) {
-    cell_report = malloc(sizeof(Protocol__FlexCellStatsReport *) * report_config->nr_cc);
-    if (cell_report == NULL)
-      goto error;
-    // Fill in the Cell reports
-    for (i = 0; i < report_config->nr_cc; i++) {
-      cell_report[i] = malloc(sizeof(Protocol__FlexCellStatsReport));
-      if(cell_report[i] == NULL)
-	goto error;
-      protocol__flex_cell_stats_report__init(cell_report[i]);
-      cell_report[i]->carrier_index = report_config->cc_report_type[i].cc_id;
-      cell_report[i]->has_carrier_index = 1;
-      cell_report[i]->flags = report_config->cc_report_type[i].cc_report_flags;
-      cell_report[i]->has_flags = 1;
-
-      /* Check flag for creation of noise and interference report */
-      if(report_config->cc_report_type[i].cc_report_flags & PROTOCOL__FLEX_CELL_STATS_TYPE__FLCST_NOISE_INTERFERENCE) {
-	// TODO: Fill in the actual noise and interference report for this cell
-	Protocol__FlexNoiseInterferenceReport *ni_report;
-	ni_report = malloc(sizeof(Protocol__FlexNoiseInterferenceReport));
-	if(ni_report == NULL)
-	  goto error;
-	protocol__flex_noise_interference_report__init(ni_report);
-	// Current frame and subframe number
-	ni_report->sfn_sf = flexran_get_sfn_sf(enb_id);
-	ni_report->has_sfn_sf = 1;
-	//TODO:Received interference power in dbm
-	ni_report->rip = 0;
-	ni_report->has_rip = 0;
-	//TODO:Thermal noise power in dbm
-	ni_report->tnp = 0;
-	ni_report->has_tnp = 0;
-
-	ni_report->p0_nominal_pucch = flexran_get_p0_nominal_pucch(enb_id, 0);
-	ni_report->has_p0_nominal_pucch = 1;
-	cell_report[i]->noise_inter_report = ni_report;
-      }
-    }
-    /* Add list of all cell reports to the message */
-    stats_reply_msg->cell_report = cell_report;
+    
+            
+            // Fill in the Cell reports
+            for (i = 0; i < report_config->nr_cc; i++) {
+
+
+                      /* Check flag for creation of noise and interference report */
+                      if(report_config->cc_report_type[i].cc_report_flags & PROTOCOL__FLEX_CELL_STATS_TYPE__FLCST_NOISE_INTERFERENCE) {
+                            // TODO: Fill in the actual noise and interference report for this cell
+                            Protocol__FlexNoiseInterferenceReport *ni_report;
+                            ni_report = malloc(sizeof(Protocol__FlexNoiseInterferenceReport));
+                            if(ni_report == NULL)
+                              goto error;
+                            protocol__flex_noise_interference_report__init(ni_report);
+                            // Current frame and subframe number
+                            ni_report->sfn_sf = flexran_get_sfn_sf(enb_id);
+                            ni_report->has_sfn_sf = 1;
+                            //TODO:Received interference power in dbm
+                            ni_report->rip = 0;
+                            ni_report->has_rip = 1;
+                            //TODO:Thermal noise power in dbm
+                            ni_report->tnp = 0;
+                            ni_report->has_tnp = 1;
+
+                            ni_report->p0_nominal_pucch = flexran_get_p0_nominal_pucch(enb_id, 0);
+                            ni_report->has_p0_nominal_pucch = 1;
+                            cell_report[i]->noise_inter_report = ni_report;
+                      }
+            }
+            
+
+      
+            
   }
 
-  *msg = malloc(sizeof(Protocol__FlexranMessage));
-  if(*msg == NULL)
-    goto error;
-  protocol__flexran_message__init(*msg);
-  (*msg)->msg_case = PROTOCOL__FLEXRAN_MESSAGE__MSG_STATS_REPLY_MSG;
-  (*msg)->msg_dir =  PROTOCOL__FLEXRAN_DIRECTION__SUCCESSFUL_OUTCOME;
-  (*msg)->stats_reply_msg = stats_reply_msg;
   return 0;
 
  error:
-  // TODO: Need to make proper error handling
-  if (header != NULL)
-    free(header);
-  if (stats_reply_msg != NULL)
-    free(stats_reply_msg);
-  if(*msg != NULL)
-    free(*msg);
-  //LOG_E(MAC, "%s: an error occured\n", __FUNCTION__);
+
+  if (cell_report != NULL)
+        free(cell_report);
+  if (ue_report != NULL)
+        free(ue_report);
+
   return -1;
 }
 
@@ -1226,6 +1044,78 @@ int flexran_agent_mac_destroy_dl_config(Protocol__FlexranMessage *msg) {
   return -1;
 }
 
+int flexran_agent_mac_create_empty_ul_config(mid_t mod_id, Protocol__FlexranMessage **msg) {
+
+  int xid = 0;
+  Protocol__FlexHeader *header;
+  if (flexran_create_header(xid, PROTOCOL__FLEX_TYPE__FLPT_UL_MAC_CONFIG, &header) != 0)
+    goto error;
+
+  Protocol__FlexUlMacConfig *ul_mac_config_msg;
+  ul_mac_config_msg = malloc(sizeof(Protocol__FlexUlMacConfig));
+  if (ul_mac_config_msg == NULL) {
+    goto error;
+  }
+  protocol__flex_ul_mac_config__init(ul_mac_config_msg);
+
+  ul_mac_config_msg->header = header;
+  ul_mac_config_msg->has_sfn_sf = 1;
+  ul_mac_config_msg->sfn_sf = flexran_get_sfn_sf(mod_id);
+
+  *msg = malloc(sizeof(Protocol__FlexranMessage));
+  if(*msg == NULL)
+    goto error;
+  protocol__flexran_message__init(*msg);
+  (*msg)->msg_case = PROTOCOL__FLEXRAN_MESSAGE__MSG_UL_MAC_CONFIG_MSG;
+  (*msg)->msg_dir =  PROTOCOL__FLEXRAN_DIRECTION__INITIATING_MESSAGE;
+  (*msg)->ul_mac_config_msg = ul_mac_config_msg;
+
+  return 0;
+
+ error:
+  return -1;
+}
+
+
+int flexran_agent_mac_destroy_ul_config(Protocol__FlexranMessage *msg) {
+  int i; //,j, k;
+  if(msg->msg_case != PROTOCOL__FLEXRAN_MESSAGE__MSG_UL_MAC_CONFIG_MSG)
+    goto error;
+
+  // Protocol__FlexUlDci *ul_dci;
+
+  free(msg->ul_mac_config_msg->header);
+  for (i = 0; i < msg->ul_mac_config_msg->n_ul_ue_data; i++) {
+    // TODO  uplink rlc ...
+    // free(msg->ul_mac_config_msg->dl_ue_data[i]->ce_bitmap); 
+  //   for (j = 0; j < msg->ul_mac_config_msg->ul_ue_data[i]->n_rlc_pdu; j++) {
+  //     for (k = 0; k <  msg->ul_mac_config_msg->ul_ue_data[i]->rlc_pdu[j]->n_rlc_pdu_tb; k++) {
+  // free(msg->ul_mac_config_msg->dl_ue_data[i]->rlc_pdu[j]->rlc_pdu_tb[k]);
+  //     }
+  //     free(msg->ul_mac_config_msg->ul_ue_data[i]->rlc_pdu[j]->rlc_pdu_tb);
+  //     free(msg->ul_mac_config_msg->ul_ue_data[i]->rlc_pdu[j]);
+  //   }
+    // free(msg->ul_mac_config_msg->ul_ue_data[i]->rlc_pdu);
+    // ul_dci = msg->ul_mac_config_msg->ul_ue_data[i]->ul_dci;
+    // free(dl_dci->tbs_size);
+    // free(ul_dci->mcs);
+    // free(ul_dci->ndi);
+    // free(ul_dci->rv);
+    // free(ul_dci);
+    // free(msg->ul_mac_config_msg->ul_ue_data[i]);
+  }
+  free(msg->ul_mac_config_msg->ul_ue_data);
+  
+  free(msg->ul_mac_config_msg);
+  free(msg);
+
+  return 0;
+
+ error:
+  return -1;
+}
+
+
 void flexran_agent_get_pending_dl_mac_config(mid_t mod_id, Protocol__FlexranMessage **msg) {
 
   struct lfds700_misc_prng_state ls;
@@ -1346,59 +1236,8 @@ void flexran_agent_send_sf_trigger(mid_t mod_id) {
   LOG_D(FLEXRAN_AGENT, "Could not send sf trigger message\n");
 }
 
-void flexran_agent_send_update_mac_stats(mid_t mod_id) {
-
-  Protocol__FlexranMessage *current_report = NULL;
-  void *data;
-  int size;
-  err_code_t err_code;
-  int priority = 0;
-  
-  if (pthread_mutex_lock(mac_stats_context[mod_id].mutex)) {
-    goto error;
-  }
-
-  if (mac_stats_context[mod_id].cont_update == 1) {
-  
-    /*Create a fresh report with the required flags*/
-    err_code = flexran_agent_mac_handle_stats(mod_id, (void *) mac_stats_context[mod_id].stats_req, &current_report);
-    if (err_code < 0) {
-      goto error;
-    }
-  }
-  /* /\*TODO:Check if a previous reports exists and if yes, generate a report */
-  /*  *that is the diff between the old and the new report, */
-  /*  *respecting the thresholds. Otherwise send the new report*\/ */
-  /* if (mac_stats_context[mod_id].prev_stats_reply != NULL) { */
-
-  /*   msg = flexran_agent_generate_diff_mac_stats_report(current_report, mac_stats_context[mod_id].prev_stats_reply); */
-
-  /*   /\*Destroy the old stats*\/ */
-  /*    flexran_agent_destroy_flexran_message(mac_stats_context[mod_id].prev_stats_reply); */
-  /* } */
-  /* /\*Use the current report for future comparissons*\/ */
-  /* mac_stats_context[mod_id].prev_stats_reply = current_report; */
 
 
-  if (pthread_mutex_unlock(mac_stats_context[mod_id].mutex)) {
-    goto error;
-  }
-
-  if (current_report != NULL){
-    data=flexran_agent_pack_message(current_report, &size);
-    /*Send any stats updates using the MAC channel of the eNB*/
-    if (flexran_agent_msg_send(mod_id, FLEXRAN_AGENT_MAC, data, size, priority)) {
-      err_code = PROTOCOL__FLEXRAN_ERR__MSG_ENQUEUING;
-      goto error;
-    }
-
-    LOG_D(FLEXRAN_AGENT,"sent message with size %d\n", size);
-    return;
-  }
- error:
-  LOG_D(FLEXRAN_AGENT, "Could not send sf trigger message\n");
-}
-
 int flexran_agent_register_mac_xface(mid_t mod_id, AGENT_MAC_xface *xface) {
   if (mac_agent_registered[mod_id]) {
     LOG_E(MAC, "MAC agent for eNB %d is already registered\n", mod_id);
@@ -1408,14 +1247,14 @@ int flexran_agent_register_mac_xface(mid_t mod_id, AGENT_MAC_xface *xface) {
   //xface->agent_ctxt = &shared_ctxt[mod_id];
   xface->flexran_agent_send_sr_info = flexran_agent_send_sr_info;
   xface->flexran_agent_send_sf_trigger = flexran_agent_send_sf_trigger;
-  xface->flexran_agent_send_update_mac_stats = flexran_agent_send_update_mac_stats;
-  xface->flexran_agent_schedule_ue_spec = flexran_schedule_ue_spec_default;
+  //xface->flexran_agent_send_update_mac_stats = flexran_agent_send_update_mac_stats;
+  xface->flexran_agent_schedule_ue_spec = flexran_schedule_ue_dl_spec_default;
+  xface->flexran_agent_schedule_ul_spec = flexran_schedule_ue_ul_spec_default;
   //xface->flexran_agent_schedule_ue_spec = flexran_schedule_ue_spec_remote;
   xface->flexran_agent_get_pending_dl_mac_config = flexran_agent_get_pending_dl_mac_config;
-  xface->flexran_agent_notify_ue_state_change = flexran_agent_ue_state_change;
   
   xface->dl_scheduler_loaded_lib = NULL;
-
+  xface->ul_scheduler_loaded_lib = NULL;
   mac_agent_registered[mod_id] = 1;
   agent_mac_xface[mod_id] = xface;
 
@@ -1427,13 +1266,13 @@ int flexran_agent_unregister_mac_xface(mid_t mod_id, AGENT_MAC_xface *xface) {
   //xface->agent_ctxt = NULL;
   xface->flexran_agent_send_sr_info = NULL;
   xface->flexran_agent_send_sf_trigger = NULL;
-  xface->flexran_agent_send_update_mac_stats = NULL;
+  //xface->flexran_agent_send_update_mac_stats = NULL;
   xface->flexran_agent_schedule_ue_spec = NULL;
   xface->flexran_agent_get_pending_dl_mac_config = NULL;
-  xface->flexran_agent_notify_ue_state_change = NULL;
+  xface->flexran_agent_schedule_ul_spec = NULL;
 
   xface->dl_scheduler_loaded_lib = NULL;
-
+  xface->ul_scheduler_loaded_lib = NULL;
   mac_agent_registered[mod_id] = 0;
   agent_mac_xface[mod_id] = NULL;
 
@@ -1441,89 +1280,7 @@ int flexran_agent_unregister_mac_xface(mid_t mod_id, AGENT_MAC_xface *xface) {
 }
 
 
-/******************************************************
- *Implementations of flexran_agent_mac_internal.h functions
- ******************************************************/
-
-err_code_t flexran_agent_init_cont_mac_stats_update(mid_t mod_id) {
-
-  /*Initialize the Mac stats update structure*/
-  /*Initially the continuous update is set to false*/
-  mac_stats_context[mod_id].cont_update = 0;
-  mac_stats_context[mod_id].is_initialized = 1;
-  mac_stats_context[mod_id].stats_req = NULL;
-  mac_stats_context[mod_id].prev_stats_reply = NULL;
-  mac_stats_context[mod_id].mutex = calloc(1, sizeof(pthread_mutex_t));
-  if (mac_stats_context[mod_id].mutex == NULL)
-    goto error;
-  if (pthread_mutex_init(mac_stats_context[mod_id].mutex, NULL))
-    goto error;;
-
-  return 0;
-
- error:
-  return -1;
-}
-
-err_code_t flexran_agent_destroy_cont_mac_stats_update(mid_t mod_id) {
-  /*Disable the continuous updates for the MAC*/
-  mac_stats_context[mod_id].cont_update = 0;
-  mac_stats_context[mod_id].is_initialized = 0;
-  flexran_agent_destroy_flexran_message(mac_stats_context[mod_id].stats_req);
-  flexran_agent_destroy_flexran_message(mac_stats_context[mod_id].prev_stats_reply);
-  free(mac_stats_context[mod_id].mutex);
-
-  mac_agent_registered[mod_id] = 0;
-  return 1;
-}
-
-
-err_code_t flexran_agent_enable_cont_mac_stats_update(mid_t mod_id,
-						      xid_t xid, stats_request_config_t *stats_req) {
-  /*Enable the continuous updates for the MAC*/
-  if (pthread_mutex_lock(mac_stats_context[mod_id].mutex)) {
-    goto error;
-  }
-
-  Protocol__FlexranMessage *req_msg;
 
-  flexran_agent_mac_stats_request(mod_id, xid, stats_req, &req_msg);
-  mac_stats_context[mod_id].stats_req = req_msg;
-  mac_stats_context[mod_id].prev_stats_reply = NULL;
 
-  mac_stats_context[mod_id].cont_update = 1;
-  mac_stats_context[mod_id].xid = xid;
 
-  if (pthread_mutex_unlock(mac_stats_context[mod_id].mutex)) {
-    goto error;
-  }
-  return 0;
 
- error:
-  LOG_E(FLEXRAN_AGENT, "mac_stats_context for eNB %d is not initialized\n", mod_id);
-  return -1;
-}
-
-err_code_t flexran_agent_disable_cont_mac_stats_update(mid_t mod_id) {
-  /*Disable the continuous updates for the MAC*/
-  if (pthread_mutex_lock(mac_stats_context[mod_id].mutex)) {
-    goto error;
-  }
-  mac_stats_context[mod_id].cont_update = 0;
-  mac_stats_context[mod_id].xid = 0;
-  if (mac_stats_context[mod_id].stats_req != NULL) {
-    flexran_agent_destroy_flexran_message(mac_stats_context[mod_id].stats_req);
-  }
-  if (mac_stats_context[mod_id].prev_stats_reply != NULL) {
-    flexran_agent_destroy_flexran_message(mac_stats_context[mod_id].prev_stats_reply);
-  }
-  if (pthread_mutex_unlock(mac_stats_context[mod_id].mutex)) {
-    goto error;
-  }
-  return 0;
-
- error:
-  LOG_E(FLEXRAN_AGENT, "mac_stats_context for eNB %d is not initialized\n", mod_id);
-  return -1;
-
-}
diff --git a/openair2/ENB_APP/CONTROL_MODULES/MAC/flexran_agent_mac.h b/openair2/ENB_APP/CONTROL_MODULES/MAC/flexran_agent_mac.h
index 090a599abef7bbdf81176013ddb4292b6fbcd1ca..03e7def95e04610e57503917c38dbafe9e6fb3d4 100644
--- a/openair2/ENB_APP/CONTROL_MODULES/MAC/flexran_agent_mac.h
+++ b/openair2/ENB_APP/CONTROL_MODULES/MAC/flexran_agent_mac.h
@@ -37,50 +37,10 @@
 #include "flexran_agent_common.h"
 #include "flexran_agent_extern.h"
 
-/* These types will be used to give
-   instructions for the type of stats reports
-   we need to create */
-typedef struct {
-  uint16_t ue_rnti;
-  uint32_t ue_report_flags; /* Indicates the report elements
-			       required for this UE id. See
-			       FlexRAN specification 1.2.4.2 */
-} ue_report_type_t;
-
-typedef struct {
-  uint16_t cc_id;
-  uint32_t cc_report_flags; /* Indicates the report elements
-			      required for this CC index. See
-			      FlexRAN specification 1.2.4.3 */
-} cc_report_type_t;
-
-typedef struct {
-  int nr_ue;
-  ue_report_type_t *ue_report_type;
-  int nr_cc;
-  cc_report_type_t *cc_report_type;
-} report_config_t;
-
-typedef struct stats_request_config_s{
-  uint8_t report_type;
-  uint8_t report_frequency;
-  uint16_t period; /*In number of subframes*/
-  report_config_t *config;
-} stats_request_config_t;
 
 /* Initialization function for the agent structures etc */
 void flexran_agent_init_mac_agent(mid_t mod_id);
 
-int flexran_agent_mac_handle_stats(mid_t mod_id, const void *params, Protocol__FlexranMessage **msg);
-
-/* Statistics request protocol message constructor and destructor */
-int flexran_agent_mac_stats_request(mid_t mod_id, xid_t xid, const stats_request_config_t *report_config, Protocol__FlexranMessage **msg);
-int flexran_agent_mac_destroy_stats_request(Protocol__FlexranMessage *msg);
-
-/* Statistics reply protocol message constructor and destructor */
-int flexran_agent_mac_stats_reply(mid_t mod_id, xid_t xid, const report_config_t *report_config, Protocol__FlexranMessage **msg);
-int flexran_agent_mac_destroy_stats_reply(Protocol__FlexranMessage *msg);
-
 /* Scheduling request information protocol message constructor and estructor */
 int flexran_agent_mac_sr_info(mid_t mod_id, const void *params, Protocol__FlexranMessage **msg);
 int flexran_agent_mac_destroy_sr_info(Protocol__FlexranMessage *msg);
@@ -89,10 +49,18 @@ int flexran_agent_mac_destroy_sr_info(Protocol__FlexranMessage *msg);
 int flexran_agent_mac_sf_trigger(mid_t mod_id, const void *params, Protocol__FlexranMessage **msg);
 int flexran_agent_mac_destroy_sf_trigger(Protocol__FlexranMessage *msg);
 
+/* Statistics reply protocol message constructor and destructor */
+int flexran_agent_mac_stats_reply(mid_t mod_id, const report_config_t *report_config, Protocol__FlexUeStatsReport **ue_report, Protocol__FlexCellStatsReport **cell_report);
+int flexran_agent_mac_destroy_stats_reply(Protocol__FlexranMessage *msg);
+
 /* DL MAC scheduling decision protocol message constructor (empty command) and destructor */ 
 int flexran_agent_mac_create_empty_dl_config(mid_t mod_id, Protocol__FlexranMessage **msg);
 int flexran_agent_mac_destroy_dl_config(Protocol__FlexranMessage *msg);
 
+/* UL MAC scheduling decision protocol message constructor (empty command) and destructor */ 
+int flexran_agent_mac_create_empty_ul_config(mid_t mod_id, Protocol__FlexranMessage **msg);
+int flexran_agent_mac_destroy_ul_config(Protocol__FlexranMessage *msg);
+
 int flexran_agent_mac_handle_dl_mac_config(mid_t mod_id, const void *params, Protocol__FlexranMessage **msg);
 
 
diff --git a/openair2/ENB_APP/CONTROL_MODULES/MAC/flexran_agent_mac_defs.h b/openair2/ENB_APP/CONTROL_MODULES/MAC/flexran_agent_mac_defs.h
index 70254bd7ba4ed28154820443b8f31954ecae4447..769ddbb1b64989e9b6a574d2ad3ae254014d9a6c 100644
--- a/openair2/ENB_APP/CONTROL_MODULES/MAC/flexran_agent_mac_defs.h
+++ b/openair2/ENB_APP/CONTROL_MODULES/MAC/flexran_agent_mac_defs.h
@@ -48,7 +48,7 @@ typedef struct {
 
   /// Send to the controller all the mac stat updates that occured during this subframe
   /// based on the stats request configuration
-  void (*flexran_agent_send_update_mac_stats)(mid_t mod_id);
+  // void (*flexran_agent_send_update_mac_stats)(mid_t mod_id);
 
   /// Provide to the scheduler a pending dl_mac_config message
   void (*flexran_agent_get_pending_dl_mac_config)(mid_t mod_id,
@@ -60,14 +60,19 @@ typedef struct {
   void (*flexran_agent_schedule_ue_spec)(mid_t mod_id, uint32_t frame, uint32_t subframe,
 					 int *mbsfn_flag, Protocol__FlexranMessage **dl_info);
   
+  /// Run the UE UL scheduler and fill the Protocol__FlexranMessage. Assumes that
+  
+ void (*flexran_agent_schedule_ul_spec)(mid_t module_idP,  uint32_t frameP, uint32_t cooperation_flag,
+        int subframeP, unsigned char sched_subframe, Protocol__FlexranMessage **ul_info);
 
   /// Notify the controller for a state change of a particular UE, by sending the proper
   /// UE state change message (ACTIVATION, DEACTIVATION, HANDOVER)
-  int (*flexran_agent_notify_ue_state_change)(mid_t mod_id, uint32_t rnti,
-					       uint8_t state_change);
+  // int (*flexran_agent_notify_ue_state_change)(mid_t mod_id, uint32_t rnti,
+		// 			       uint8_t state_change);
   
   
   void *dl_scheduler_loaded_lib;
+  void *ul_scheduler_loaded_lib;
   /*TODO: Fill in with the rest of the MAC layer technology specific callbacks (UL/DL scheduling, RACH info etc)*/
 
 } AGENT_MAC_xface;
diff --git a/openair2/ENB_APP/CONTROL_MODULES/MAC/flexran_agent_mac_internal.c b/openair2/ENB_APP/CONTROL_MODULES/MAC/flexran_agent_mac_internal.c
index 5c37ba81321076b1e6ec26d070b31285dfa7fd99..7239ca82338a55d859b771e37d4b7e77c3f98026 100644
--- a/openair2/ENB_APP/CONTROL_MODULES/MAC/flexran_agent_mac_internal.c
+++ b/openair2/ENB_APP/CONTROL_MODULES/MAC/flexran_agent_mac_internal.c
@@ -180,10 +180,12 @@ Protocol__FlexUeStatsReport * copy_ue_stats_report(Protocol__FlexUeStatsReport *
     }
   }
 
-  if (copy->flags & PROTOCOL__FLEX_UE_STATS_TYPE__FLUST_PRH) {
-    copy->has_phr = original->has_phr;
-    copy->phr = original->phr;
-  }
+  
+
+   if (copy->flags & PROTOCOL__FLEX_UE_STATS_TYPE__FLUST_PHR) { 
+     copy->has_phr = original->has_phr;
+     copy->phr = original->phr;
+   }
 
   if (copy->flags & PROTOCOL__FLEX_UE_STATS_TYPE__FLUST_RLC_BS) {
     copy->n_rlc_report = original->n_rlc_report; 
@@ -605,7 +607,10 @@ int parse_mac_config(mid_t mod_id, yaml_parser_t *parser) {
       } else if (strcmp((char *) event.data.scalar.value, "ul_scheduler") == 0) {
 	// Call the proper handler
 	LOG_D(ENB_APP, "This is for the ul_scheduler subsystem\n");
-	goto error;
+	if (parse_ul_scheduler_config(mod_id, parser) == -1) {
+    LOG_D(ENB_APP, "An error occured\n");
+    goto error;
+  }
 	// TODO
       } else if (strcmp((char *) event.data.scalar.value, "ra_scheduler") == 0) {
 	// Call the proper handler
@@ -698,6 +703,56 @@ int parse_dl_scheduler_config(mid_t mod_id, yaml_parser_t *parser) {
   return -1;
 }
 
+int parse_ul_scheduler_config(mid_t mod_id, yaml_parser_t *parser) {
+  
+  yaml_event_t event;
+
+  int done = 0;
+  int mapping_started = 0;
+
+  while (!done) {
+    
+    if (!yaml_parser_parse(parser, &event))
+      goto error;
+
+    switch (event.type) {
+      // We are expecting a mapping (behavior and parameters)
+    case YAML_MAPPING_START_EVENT:
+      LOG_D(ENB_APP, "The mapping of the subsystem started\n");
+      mapping_started = 1;
+      break;
+    case YAML_MAPPING_END_EVENT:
+      LOG_D(ENB_APP, "The mapping of the subsystem ended\n");
+      mapping_started = 0;
+      break;
+    case YAML_SCALAR_EVENT:
+      if (!mapping_started) {
+  goto error;
+      }
+      // Check what key needs to be set
+      if (strcmp((char *) event.data.scalar.value, "parameters") == 0) {
+  LOG_D(ENB_APP, "Now it is time to set the parameters for this subsystem\n");
+  if (parse_ul_scheduler_parameters(mod_id, parser) == -1) {
+    goto error;
+  }
+      }
+      break;
+    default:
+      goto error;
+    }
+
+    done = (event.type == YAML_MAPPING_END_EVENT);
+    yaml_event_delete(&event);
+  }
+
+  return 0;
+
+ error:
+  yaml_event_delete(&event);
+  return -1;
+}
+
+
 int parse_dl_scheduler_parameters(mid_t mod_id, yaml_parser_t *parser) {
   yaml_event_t event;
   
@@ -753,6 +808,61 @@ int parse_dl_scheduler_parameters(mid_t mod_id, yaml_parser_t *parser) {
   return -1;
 }
 
+int parse_ul_scheduler_parameters(mid_t mod_id, yaml_parser_t *parser) {
+  yaml_event_t event;
+  
+  void *param;
+  
+  int done = 0;
+  int mapping_started = 0;
+
+  while (!done) {
+    
+    if (!yaml_parser_parse(parser, &event))
+      goto error;
+
+    switch (event.type) {
+      // We are expecting a mapping of parameters
+    case YAML_MAPPING_START_EVENT:
+      LOG_D(ENB_APP, "The mapping of the parameters started\n");
+      mapping_started = 1;
+      break;
+    case YAML_MAPPING_END_EVENT:
+      LOG_D(ENB_APP, "The mapping of the parameters ended\n");
+      mapping_started = 0;
+      break;
+    case YAML_SCALAR_EVENT:
+      if (!mapping_started) {
+  goto error;
+      }
+      // Check what key needs to be set
+      if (mac_agent_registered[mod_id]) {
+  LOG_D(ENB_APP, "Setting parameter %s\n", event.data.scalar.value);
+  param = dlsym(agent_mac_xface[mod_id]->ul_scheduler_loaded_lib,
+          (char *) event.data.scalar.value);
+  if (param == NULL) {
+    goto error;
+  }
+  apply_parameter_modification(param, parser);
+      } else {
+  goto error;
+      }
+      break;
+    default:
+      goto error;
+    }
+
+    done = (event.type == YAML_MAPPING_END_EVENT);
+    yaml_event_delete(&event);
+  }
+
+  return 0;
+  
+ error:
+  yaml_event_delete(&event);
+  return -1;
+}
+
 int load_dl_scheduler_function(mid_t mod_id, const char *function_name) {
   void *lib;
 
diff --git a/openair2/ENB_APP/CONTROL_MODULES/MAC/flexran_agent_mac_internal.h b/openair2/ENB_APP/CONTROL_MODULES/MAC/flexran_agent_mac_internal.h
index 263b85eb87fef9dfd70a13ba15d702ea14c06e5b..f69e2cde4098ad5d035a522c9815632bffb37312 100644
--- a/openair2/ENB_APP/CONTROL_MODULES/MAC/flexran_agent_mac_internal.h
+++ b/openair2/ENB_APP/CONTROL_MODULES/MAC/flexran_agent_mac_internal.h
@@ -101,6 +101,10 @@ int parse_dl_scheduler_config(mid_t mod_id, yaml_parser_t *parser);
 
 int parse_dl_scheduler_parameters(mid_t mod_id, yaml_parser_t *parser);
 
+int parse_ul_scheduler_config(mid_t mod_id, yaml_parser_t *parser);
+
+int parse_ul_scheduler_parameters(mid_t mod_id, yaml_parser_t *parser);
+
 int load_dl_scheduler_function(mid_t mod_id, const char *function_name);
 
 #endif /*FLEXRAN_AGENT_MAC_INTERNAL_H_*/
diff --git a/openair2/ENB_APP/CONTROL_MODULES/PDCP/flexran_agent_pdcp.c b/openair2/ENB_APP/CONTROL_MODULES/PDCP/flexran_agent_pdcp.c
new file mode 100644
index 0000000000000000000000000000000000000000..25ec91912742b7a3fd38f026edd2da40395fce63
--- /dev/null
+++ b/openair2/ENB_APP/CONTROL_MODULES/PDCP/flexran_agent_pdcp.c
@@ -0,0 +1,171 @@
+/*
+ * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The OpenAirInterface Software Alliance licenses this file to You under
+ * the OAI Public License, Version 1.0  (the "License"); you may not use this file
+ * except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.openairinterface.org/?page_id=698
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *-------------------------------------------------------------------------------
+ * For more information about the OpenAirInterface (OAI) Software Alliance:
+ *      contact@openairinterface.org
+ */ 
+
+/*! \file flexran_agent_pdcp.c
+ * \brief FlexRAN agent Control Module PDCP 
+ * \author Navid Nikaein and shahab SHARIAT BAGHERI
+ * \date 2017
+ * \version 0.1
+ */
+
+#include "flexran_agent_pdcp.h"
+
+
+/*Trigger boolean for PDCP measurement*/
+bool triggered_pdcp = false;
+/*Flags showing if a pdcp agent has already been registered*/
+unsigned int pdcp_agent_registered[NUM_MAX_ENB];
+
+/*Array containing the Agent-PDCP interfaces*/
+AGENT_PDCP_xface *agent_pdcp_xface[NUM_MAX_ENB];
+
+// NUMBER_OF_UE_MAX
+
+void flexran_agent_pdcp_aggregate_stats(const mid_t mod_id,
+					const mid_t ue_id,
+					Protocol__FlexPdcpStats *pdcp_aggr_stats){
+
+  int lcid=0;
+  /* only calculate the DRBs */ 
+  //LOG_I(FLEXRAN_AGENT, "enb %d ue %d \n", mod_id, ue_id);
+  
+  for (lcid=NUM_MAX_SRB ; lcid < NUM_MAX_SRB + NUM_MAX_DRB; lcid++){
+    
+    pdcp_aggr_stats->pkt_tx += flexran_get_pdcp_tx(mod_id,ue_id,lcid);
+    pdcp_aggr_stats->pkt_tx_bytes += flexran_get_pdcp_tx_bytes(mod_id,ue_id,lcid);
+    pdcp_aggr_stats->pkt_tx_w += flexran_get_pdcp_tx_w(mod_id,ue_id,lcid);
+    pdcp_aggr_stats->pkt_tx_bytes_w += flexran_get_pdcp_tx_bytes_w(mod_id,ue_id,lcid);
+    pdcp_aggr_stats->pkt_tx_aiat += flexran_get_pdcp_tx_aiat(mod_id,ue_id,lcid);
+    pdcp_aggr_stats->pkt_tx_aiat_w += flexran_get_pdcp_tx_aiat_w(mod_id,ue_id,lcid);
+    
+      
+    pdcp_aggr_stats->pkt_rx += flexran_get_pdcp_rx(mod_id,ue_id,lcid);
+    pdcp_aggr_stats->pkt_rx_bytes += flexran_get_pdcp_rx_bytes(mod_id,ue_id,lcid);
+    pdcp_aggr_stats->pkt_rx_w += flexran_get_pdcp_rx_w(mod_id,ue_id,lcid);
+    pdcp_aggr_stats->pkt_rx_bytes_w += flexran_get_pdcp_rx_bytes_w(mod_id,ue_id,lcid);
+    pdcp_aggr_stats->pkt_rx_aiat += flexran_get_pdcp_rx_aiat(mod_id,ue_id,lcid);
+    pdcp_aggr_stats->pkt_rx_aiat_w += flexran_get_pdcp_rx_aiat_w(mod_id,ue_id,lcid);
+    pdcp_aggr_stats->pkt_rx_oo += flexran_get_pdcp_rx_oo(mod_id,ue_id,lcid);
+    
+  }
+  
+}
+
+
+int flexran_agent_pdcp_stats_reply(mid_t mod_id,       
+				   const report_config_t *report_config,
+				   Protocol__FlexUeStatsReport **ue_report,
+				   Protocol__FlexCellStatsReport **cell_report) {
+  
+  
+  // Protocol__FlexHeader *header;
+  int i;
+  // int cc_id = 0;
+ 
+  
+  /* Allocate memory for list of UE reports */
+  if (report_config->nr_ue > 0) {
+    
+    for (i = 0; i < report_config->nr_ue; i++) {
+
+      /* Check flag for creation of buffer status report */
+      if (report_config->ue_report_type[i].ue_report_flags & PROTOCOL__FLEX_UE_STATS_TYPE__FLUST_PDCP_STATS) {
+	
+	Protocol__FlexPdcpStats *pdcp_aggr_stats;
+	pdcp_aggr_stats = malloc(sizeof(Protocol__FlexPdcpStats));
+	if (pdcp_aggr_stats == NULL)
+	  goto error;
+	protocol__flex_pdcp_stats__init(pdcp_aggr_stats);
+	
+	flexran_agent_pdcp_aggregate_stats(mod_id, i, pdcp_aggr_stats);
+
+	pdcp_aggr_stats->has_pkt_tx=1;
+	pdcp_aggr_stats->has_pkt_tx_bytes =1;
+	pdcp_aggr_stats->has_pkt_tx_w=1; 
+	pdcp_aggr_stats->has_pkt_tx_bytes_w =1;
+	pdcp_aggr_stats->has_pkt_tx_aiat =1; 
+	pdcp_aggr_stats->has_pkt_tx_aiat_w =1;
+
+	pdcp_aggr_stats->pkt_tx_sn = flexran_get_pdcp_tx_sn(mod_id, i, DEFAULT_DRB);
+	pdcp_aggr_stats->has_pkt_tx_sn =1;
+	
+	pdcp_aggr_stats->has_pkt_rx =1;
+	pdcp_aggr_stats->has_pkt_rx_bytes =1; 
+	pdcp_aggr_stats->has_pkt_rx_w =1;
+	pdcp_aggr_stats->has_pkt_rx_bytes_w =1;
+	pdcp_aggr_stats->has_pkt_rx_aiat =1;
+	pdcp_aggr_stats->has_pkt_rx_aiat_w =1;
+	pdcp_aggr_stats->has_pkt_rx_oo =1;
+
+	pdcp_aggr_stats->pkt_rx_sn = flexran_get_pdcp_rx_sn(mod_id, i, DEFAULT_DRB);
+	pdcp_aggr_stats->has_pkt_rx_sn =1;
+
+	pdcp_aggr_stats->sfn = flexran_get_pdcp_sfn(mod_id);
+	pdcp_aggr_stats->has_sfn =1;
+
+	ue_report[i]->pdcp_stats = pdcp_aggr_stats;
+
+      }
+    }
+  }  else {
+    LOG_D(FLEXRAN_AGENT, "no UE\n");
+  }     
+  
+  return 0;
+  
+ error:
+  LOG_W(FLEXRAN_AGENT, "Can't allocate PDCP stats\n");
+  
+  /* if (cell_report != NULL)
+        free(cell_report);
+  if (ue_report != NULL)
+        free(ue_report);
+  */
+  return -1;
+}
+
+
+
+int flexran_agent_register_pdcp_xface(mid_t mod_id, AGENT_PDCP_xface *xface) {
+  if (pdcp_agent_registered[mod_id]) {
+    LOG_E(PDCP, "PDCP agent for eNB %d is already registered\n", mod_id);
+    return -1;
+  }
+
+  //xface->flexran_pdcp_stats_measurement = NULL;
+
+  pdcp_agent_registered[mod_id] = 1;
+  agent_pdcp_xface[mod_id] = xface;
+
+  return 0;
+}
+
+int flexran_agent_unregister_pdcp_xface(mid_t mod_id, AGENT_PDCP_xface *xface) {
+
+  //xface->agent_ctxt = NULL;
+  //xface->flexran_pdcp_stats_measurement = NULL;
+
+  
+  pdcp_agent_registered[mod_id] = 0;
+  agent_pdcp_xface[mod_id] = NULL;
+
+  return 0;
+}
diff --git a/openair2/ENB_APP/CONTROL_MODULES/PDCP/flexran_agent_pdcp.h b/openair2/ENB_APP/CONTROL_MODULES/PDCP/flexran_agent_pdcp.h
new file mode 100644
index 0000000000000000000000000000000000000000..a962390c00eaea5560f8717293ee76e40d49c76e
--- /dev/null
+++ b/openair2/ENB_APP/CONTROL_MODULES/PDCP/flexran_agent_pdcp.h
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The OpenAirInterface Software Alliance licenses this file to You under
+ * the OAI Public License, Version 1.0  (the "License"); you may not use this file
+ * except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.openairinterface.org/?page_id=698
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *-------------------------------------------------------------------------------
+ * For more information about the OpenAirInterface (OAI) Software Alliance:
+ *      contact@openairinterface.org
+ */ 
+
+/*! \file flexran_agent_pdcp.h
+ * \brief FlexRAN agent Control Module PDCP header
+ * \author shahab SHARIAT BAGHERI 
+ * \date 2017
+ * \version 0.1
+ */
+
+#ifndef FLEXRAN_AGENT_PDCP_H_
+#define FLEXRAN_AGENT_PDCP_H_
+
+#include "header.pb-c.h"
+#include "flexran.pb-c.h"
+#include "stats_messages.pb-c.h"
+#include "stats_common.pb-c.h"
+
+
+#include "flexran_agent_common.h"
+#include "flexran_agent_defs.h"
+#include "flexran_agent_pdcp_defs.h"
+#include "flexran_agent_ran_api.h"
+
+/**********************************
+ * FlexRAN agent - technology PDCP API
+ **********************************/
+
+/* Send to the controller all the pdcp stat updates that occured during this subframe*/
+int flexran_agent_pdcp_stats_reply(mid_t mod_id,       
+          const report_config_t *report_config,
+           Protocol__FlexUeStatsReport **ue_report,
+           Protocol__FlexCellStatsReport **cell_report);
+
+/* Get the stats from RAN API and aggregate them per USER*/
+void flexran_agent_pdcp_aggregate_stats(const mid_t mod_id,
+					const mid_t ue_id,
+					Protocol__FlexPdcpStats *pdcp_aggr_stats);
+
+/*Register technology specific interface callbacks*/
+int flexran_agent_register_pdcp_xface(mid_t mod_id, AGENT_PDCP_xface *xface);
+
+/*Unregister technology specific callbacks*/
+int flexran_agent_unregister_pdcp_xface(mid_t mod_id, AGENT_PDCP_xface*xface);
+
+#endif
diff --git a/openair2/ENB_APP/CONTROL_MODULES/PDCP/flexran_agent_pdcp_defs.h b/openair2/ENB_APP/CONTROL_MODULES/PDCP/flexran_agent_pdcp_defs.h
new file mode 100644
index 0000000000000000000000000000000000000000..46bdf744de1a03008551f2e2193c339dc25d3ab1
--- /dev/null
+++ b/openair2/ENB_APP/CONTROL_MODULES/PDCP/flexran_agent_pdcp_defs.h
@@ -0,0 +1,63 @@
+/*
+ * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The OpenAirInterface Software Alliance licenses this file to You under
+ * the OAI Public License, Version 1.0  (the "License"); you may not use this file
+ * except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.openairinterface.org/?page_id=698
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *-------------------------------------------------------------------------------
+ * For more information about the OpenAirInterface (OAI) Software Alliance:
+ *      contact@openairinterface.org
+ */ 
+#ifndef __FLEXRAN_AGENT_PDCP_PRIMITIVES_H__
+#define __FLEXRAN_AGENT_PDCP_PRIMITIVES_H__
+
+#include "flexran_agent_defs.h"
+#include "flexran.pb-c.h"
+#include "header.pb-c.h"
+
+ /*PDCP aggregated Packet stats  */
+/*
+typedef struct  pdcp_aggr_stats_s {
+  int32_t rnti; 
+
+  int32_t pkt_tx;
+  int32_t pkt_tx_bytes;
+  int32_t pkt_tx_sn;
+  int32_t pkt_tx_rate_s;
+  int32_t pkt_tx_throughput_s;
+  int32_t pkt_tx_aiat;
+  int32_t pkt_tx_aiat_s;
+
+  int32_t pkt_rx;
+  int32_t pkt_rx_bytes;
+  int32_t pkt_rx_sn;
+  int32_t pkt_rx_rate_s;
+  int32_t pkt_rx_goodput_s;
+  int32_t pkt_rx_aiat;
+  int32_t pkt_rx_aiat_s;
+  int32_t pkt_rx_oo;
+
+  
+} pdcp_aggr_stats_t;
+*/
+
+/* FLEXRAN AGENT-PDCP Interface */
+typedef struct {
+  
+  
+  // PDCP statistics
+  void (*flexran_pdcp_stats_measurement)(mid_t mod_id, uint16_t rnti, uint16_t seq_num,  uint32_t size);
+  
+} AGENT_PDCP_xface;
+
+#endif
diff --git a/openair2/ENB_APP/CONTROL_MODULES/RRC/flexran_agent_rrc.c b/openair2/ENB_APP/CONTROL_MODULES/RRC/flexran_agent_rrc.c
new file mode 100644
index 0000000000000000000000000000000000000000..6f42d1da9726073f085aa233db9c6dd2debb565b
--- /dev/null
+++ b/openair2/ENB_APP/CONTROL_MODULES/RRC/flexran_agent_rrc.c
@@ -0,0 +1,672 @@
+/*
+ * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The OpenAirInterface Software Alliance licenses this file to You under
+ * the OAI Public License, Version 1.0  (the "License"); you may not use this file
+ * except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.openairinterface.org/?page_id=698
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *-------------------------------------------------------------------------------
+ * For more information about the OpenAirInterface (OAI) Software Alliance:
+ *      contact@openairinterface.org
+ */ 
+
+/*! \file flexran_agent_mac.c
+ * \brief FlexRAN agent Control Module RRC 
+ * \author shahab SHARIAT BAGHERI
+ * \date 2017
+ * \version 0.1
+ */
+
+#include "flexran_agent_rrc.h"
+
+
+#include "liblfds700.h"
+
+#include "log.h"
+
+/*Trigger boolean for RRC measurement*/
+bool triggered_rrc = false;
+
+/*Flags showing if an rrc agent has already been registered*/
+unsigned int rrc_agent_registered[NUM_MAX_ENB];
+
+/*Array containing the Agent-RRC interfaces*/
+AGENT_RRC_xface *agent_rrc_xface[NUM_MAX_ENB];
+
+
+void flexran_agent_ue_state_change(mid_t mod_id, uint32_t rnti, uint8_t state_change) {
+  int size;
+  Protocol__FlexranMessage *msg;
+  Protocol__FlexHeader *header;
+  void *data;
+  int priority = 0;
+  err_code_t err_code;
+
+  int xid = 0;
+
+  if (flexran_create_header(xid, PROTOCOL__FLEX_TYPE__FLPT_UE_STATE_CHANGE, &header) != 0)
+    goto error;
+
+  Protocol__FlexUeStateChange *ue_state_change_msg;
+  ue_state_change_msg = malloc(sizeof(Protocol__FlexUeStateChange));
+  if(ue_state_change_msg == NULL) {
+    goto error;
+  }
+  protocol__flex_ue_state_change__init(ue_state_change_msg);
+  ue_state_change_msg->has_type = 1;
+  ue_state_change_msg->type = state_change;
+
+  Protocol__FlexUeConfig *config;
+  config = malloc(sizeof(Protocol__FlexUeConfig));
+  if (config == NULL) {
+    goto error;
+  }
+  protocol__flex_ue_config__init(config);
+  if (state_change == PROTOCOL__FLEX_UE_STATE_CHANGE_TYPE__FLUESC_DEACTIVATED) {
+    // Simply set the rnti of the UE
+    config->has_rnti = 1;
+    config->rnti = rnti;
+  } else if (state_change == PROTOCOL__FLEX_UE_STATE_CHANGE_TYPE__FLUESC_UPDATED
+       || state_change == PROTOCOL__FLEX_UE_STATE_CHANGE_TYPE__FLUESC_ACTIVATED) {
+        int i = find_UE_id(mod_id, rnti);
+      config->has_rnti = 1;
+      config->rnti = rnti;
+        if(flexran_get_time_alignment_timer(mod_id,i) != -1) {
+          config->time_alignment_timer = flexran_get_time_alignment_timer(mod_id,i);
+          config->has_time_alignment_timer = 1;
+        }
+        if(flexran_get_meas_gap_config(mod_id,i) != -1){
+          config->meas_gap_config_pattern = flexran_get_meas_gap_config(mod_id,i);
+            config->has_meas_gap_config_pattern = 1;
+        }
+        if(config->has_meas_gap_config_pattern == 1 &&
+         config->meas_gap_config_pattern != PROTOCOL__FLEX_MEAS_GAP_CONFIG_PATTERN__FLMGCP_OFF) {
+        config->meas_gap_config_sf_offset = flexran_get_meas_gap_config_offset(mod_id,i);
+        config->has_meas_gap_config_sf_offset = 1;
+        }
+        //TODO: Set the SPS configuration (Optional)
+        //Not supported for now, so we do not set it
+
+        //TODO: Set the SR configuration (Optional)
+        //We do not set it for now
+
+        //TODO: Set the CQI configuration (Optional)
+        //We do not set it for now
+      
+      if(flexran_get_ue_transmission_mode(mod_id,i) != -1) {
+          config->transmission_mode = flexran_get_ue_transmission_mode(mod_id,i);
+          config->has_transmission_mode = 1;
+        }
+
+      config->ue_aggregated_max_bitrate_ul = flexran_get_ue_aggregated_max_bitrate_ul(mod_id,i);
+        config->has_ue_aggregated_max_bitrate_ul = 1;
+
+      config->ue_aggregated_max_bitrate_dl = flexran_get_ue_aggregated_max_bitrate_dl(mod_id,i);
+        config->has_ue_aggregated_max_bitrate_dl = 1;
+
+        //TODO: Set the UE capabilities
+        Protocol__FlexUeCapabilities *c_capabilities;
+        c_capabilities = malloc(sizeof(Protocol__FlexUeCapabilities));
+        protocol__flex_ue_capabilities__init(c_capabilities);
+        //TODO: Set half duplex (FDD operation)
+        c_capabilities->has_half_duplex = 0;
+        c_capabilities->half_duplex = 1;//flexran_get_half_duplex(i);
+        //TODO: Set intra-frame hopping flag
+        c_capabilities->has_intra_sf_hopping = 0;
+        c_capabilities->intra_sf_hopping = 1;//flexran_get_intra_sf_hopping(i);
+        //TODO: Set support for type 2 hopping with n_sb > 1
+        c_capabilities->has_type2_sb_1 = 0;
+        c_capabilities->type2_sb_1 = 1;//flexran_get_type2_sb_1(i);
+        //TODO: Set ue category
+        c_capabilities->has_ue_category = 0;
+        c_capabilities->ue_category = 1;//flexran_get_ue_category(i);
+        //TODO: Set UE support for resource allocation type 1
+        c_capabilities->has_res_alloc_type1 = 0;
+        c_capabilities->res_alloc_type1 = 1;//flexran_get_res_alloc_type1(i);
+        //Set the capabilites to the message
+        config->capabilities = c_capabilities;
+      
+        if(flexran_get_ue_transmission_antenna(mod_id,i) != -1) {
+        config->has_ue_transmission_antenna = 1;
+        config->ue_transmission_antenna = flexran_get_ue_transmission_antenna(mod_id,i);
+        }
+
+        if(flexran_get_tti_bundling(mod_id,i) != -1) {
+        config->has_tti_bundling = 1;
+        config->tti_bundling = flexran_get_tti_bundling(mod_id,i);
+        }
+
+        if(flexran_get_maxHARQ_TX(mod_id,i) != -1){
+        config->has_max_harq_tx = 1;
+        config->max_harq_tx = flexran_get_maxHARQ_TX(mod_id,i);
+        }
+
+        if(flexran_get_beta_offset_ack_index(mod_id,i) != -1) {
+        config->has_beta_offset_ack_index = 1;
+        config->beta_offset_ack_index = flexran_get_beta_offset_ack_index(mod_id,i);
+        }
+
+        if(flexran_get_beta_offset_ri_index(mod_id,i) != -1) {
+        config->has_beta_offset_ri_index = 1;
+        config->beta_offset_ri_index = flexran_get_beta_offset_ri_index(mod_id,i);
+        }
+
+        if(flexran_get_beta_offset_cqi_index(mod_id,i) != -1) {
+        config->has_beta_offset_cqi_index = 1;
+        config->beta_offset_cqi_index = flexran_get_beta_offset_cqi_index(mod_id,i);
+        }
+
+        if(flexran_get_ack_nack_simultaneous_trans(mod_id,i) != -1) {
+        config->has_ack_nack_simultaneous_trans = 1;
+        config->ack_nack_simultaneous_trans = flexran_get_ack_nack_simultaneous_trans(mod_id,i);
+        }
+
+        if(flexran_get_simultaneous_ack_nack_cqi(mod_id,i) != -1) {
+        config->has_simultaneous_ack_nack_cqi = 1;
+        config->simultaneous_ack_nack_cqi = flexran_get_simultaneous_ack_nack_cqi(mod_id,i);
+        }
+
+        if(flexran_get_aperiodic_cqi_rep_mode(mod_id,i) != -1) {
+        config->has_aperiodic_cqi_rep_mode = 1;
+        int mode = flexran_get_aperiodic_cqi_rep_mode(mod_id,i);
+        if (mode > 4) {
+          config->aperiodic_cqi_rep_mode = PROTOCOL__FLEX_APERIODIC_CQI_REPORT_MODE__FLACRM_NONE;
+        } else {
+          config->aperiodic_cqi_rep_mode = mode;
+        }
+        }
+
+        if(flexran_get_tdd_ack_nack_feedback(mod_id, i) != -1) {
+        config->has_tdd_ack_nack_feedback = 1;
+        config->tdd_ack_nack_feedback = flexran_get_tdd_ack_nack_feedback(mod_id,i);
+        }
+
+        if(flexran_get_ack_nack_repetition_factor(mod_id, i) != -1) {
+        config->has_ack_nack_repetition_factor = 1;
+        config->ack_nack_repetition_factor = flexran_get_ack_nack_repetition_factor(mod_id,i);
+        }
+
+        if(flexran_get_extended_bsr_size(mod_id, i) != -1) {
+        config->has_extended_bsr_size = 1;
+        config->extended_bsr_size = flexran_get_extended_bsr_size(mod_id,i);
+        }
+
+      config->has_pcell_carrier_index = 1;
+      config->pcell_carrier_index = UE_PCCID(mod_id, i);
+        //TODO: Set carrier aggregation support (boolean)
+        config->has_ca_support = 0;
+        config->ca_support = 0;
+        if(config->has_ca_support){
+        //TODO: Set cross carrier scheduling support (boolean)
+        config->has_cross_carrier_sched_support = 1;
+        config->cross_carrier_sched_support = 0;
+        //TODO: Set secondary cells configuration
+        // We do not set it for now. No carrier aggregation support
+        
+        //TODO: Set deactivation timer for secondary cell
+        config->has_scell_deactivation_timer = 0;
+        config->scell_deactivation_timer = 0;
+        }
+  } else if (state_change == PROTOCOL__FLEX_UE_STATE_CHANGE_TYPE__FLUESC_MOVED) {
+    // TODO: Not supported for now. Leave blank
+  }
+
+  ue_state_change_msg->config = config;
+  msg = malloc(sizeof(Protocol__FlexranMessage));
+  if (msg == NULL) {
+    goto error;
+  }
+  protocol__flexran_message__init(msg);
+  msg->msg_case = PROTOCOL__FLEXRAN_MESSAGE__MSG_UE_STATE_CHANGE_MSG;
+  msg->msg_dir = PROTOCOL__FLEXRAN_DIRECTION__INITIATING_MESSAGE;
+  msg->ue_state_change_msg = ue_state_change_msg;
+
+  data = flexran_agent_pack_message(msg, &size);
+  /*Send sr info using the MAC channel of the eNB*/
+  if (flexran_agent_msg_send(mod_id, FLEXRAN_AGENT_DEFAULT, data, size, priority)) {
+    err_code = PROTOCOL__FLEXRAN_ERR__MSG_ENQUEUING;
+    goto error;
+  }
+
+  LOG_D(FLEXRAN_AGENT,"sent message with size %d\n", size);
+  return;
+ error:
+  LOG_E(FLEXRAN_AGENT, "Could not send UE state message becasue of %d \n",err_code);
+}
+
+
+
+int flexran_agent_destroy_ue_state_change(Protocol__FlexranMessage *msg) {
+  if(msg->msg_case != PROTOCOL__FLEXRAN_MESSAGE__MSG_UE_STATE_CHANGE_MSG)
+    goto error;
+  free(msg->ue_state_change_msg->header);
+  //TODO: Free the contents of the UE config structure
+  free(msg->ue_state_change_msg);
+  free(msg);
+  return 0;
+
+ error:
+  //LOG_E(MAC, "%s: an error occured\n", __FUNCTION__);
+  return -1;
+}
+
+/* this is called by RRC as a part of rrc xface  . The controller previously requested  this*/ 
+void flexran_trigger_rrc_measurements (mid_t mod_id, MeasResults_t*  measResults) {
+
+  int i;
+  // int                   priority = 0; // Warning Preventing
+  // void                  *data;
+  // int                   size;
+  // err_code_t             err_code = -100;
+  triggered_rrc = true;
+  int num;
+
+  num = flexran_get_num_ues (mod_id);
+
+  meas_stats = malloc(sizeof(rrc_meas_stats) * num); 
+
+  for (i = 0; i < num; i++){
+    meas_stats[i].rnti = flexran_get_ue_crnti(mod_id, i);
+    meas_stats[i].meas_id = flexran_get_rrc_pcell_measid(mod_id,i);
+    meas_stats[i].rsrp =  flexran_get_rrc_pcell_rsrp(mod_id,i) - 140;
+    // measResults->measResultPCell.rsrpResult - 140;
+    meas_stats[i].rsrq =  flexran_get_rrc_pcell_rsrq(mod_id,i)/2 - 20;
+    // (measResults->measResultPCell.rsrqResult)/2 - 20;                          
+    
+  }
+    // repl->neigh_meas = NULL;
+
+  // if (meas->measResultNeighCells != NULL) {
+  //   /*
+  //   * Neighboring cells measurements performed by UE.
+  //   */
+  //   NeighCellsMeasurements *neigh_meas;
+  //   neigh_meas = malloc(sizeof(NeighCellsMeasurements));
+  //   if (neigh_meas == NULL)
+  //     goto error;
+  //   neigh_cells_measurements__init(neigh_meas);
+
+  //   /* EUTRAN RRC Measurements. */
+  //   if (meas->measResultNeighCells->present ==
+  //         MeasResults__measResultNeighCells_PR_measResultListEUTRA) {
+
+  //     MeasResultListEUTRA_t meas_list = meas->measResultNeighCells->
+  //                         choice.measResultListEUTRA;
+  //     /* Set the number of EUTRAN measurements present in report. */
+  //     neigh_meas->n_eutra_meas = meas_list.list.count;
+  //     if (neigh_meas->n_eutra_meas > 0) {
+  //       /* Initialize EUTRAN measurements. */
+  //       EUTRAMeasurements **eutra_meas;
+  //       eutra_meas = malloc(sizeof(EUTRAMeasurements *) *
+  //                         neigh_meas->n_eutra_meas);
+  //       for (i = 0; i < neigh_meas->n_eutra_meas; i++) {
+  //         eutra_meas[i] = malloc(sizeof(EUTRAMeasurements));
+  //         eutra_measurements__init(eutra_meas[i]);
+  //         /* Fill in the physical cell identifier. */
+  //         eutra_meas[i]->has_phys_cell_id = 1;
+  //         eutra_meas[i]->phys_cell_id = meas_list.list.array[i]->
+  //                                 physCellId;
+  //         // log_i(agent,"PCI of Target %d", eutra_meas[i]->phys_cell_id);
+  //         /* Check for Reference signal measurements. */
+  //         if (&(meas_list.list.array[i]->measResult)) {
+  //           /* Initialize Ref. signal measurements. */
+  //           EUTRARefSignalMeas *meas_result;
+  //           meas_result = malloc(sizeof(EUTRARefSignalMeas));
+  //           eutra_ref_signal_meas__init(meas_result);
+
+  //           if (meas_list.list.array[i]->measResult.rsrpResult) {
+  //             meas_result->has_rsrp = 1;
+  //             meas_result->rsrp = RSRP_meas_mapping[*(meas_list.
+  //                   list.array[i]->measResult.rsrpResult)];
+  //             // log_i(agent,"RSRP of Target %d", meas_result->rsrp);
+  //           }
+
+  //           if (meas_list.list.array[i]->measResult.rsrqResult) {
+  //             meas_result->has_rsrq = 1;
+  //             meas_result->rsrq = RSRQ_meas_mapping[*(meas_list.
+  //                   list.array[i]->measResult.rsrqResult)];
+  //             // log_i(agent,"RSRQ of Target %d", meas_result->rsrq);
+  //           }
+  //           eutra_meas[i]->meas_result = meas_result;
+  //         }
+  //         /* Check for CGI measurements. */
+  //         if (meas_list.list.array[i]->cgi_Info) {
+  //           /* Initialize CGI measurements. */
+  //           EUTRACgiMeasurements *cgi_meas;
+  //           cgi_meas = malloc(sizeof(EUTRACgiMeasurements));
+  //           eutra_cgi_measurements__init(cgi_meas);
+
+  //           /* EUTRA Cell Global Identity (CGI). */
+  //           CellGlobalIdEUTRA *cgi;
+  //           cgi = malloc(sizeof(CellGlobalIdEUTRA));
+  //           cell_global_id__eutra__init(cgi);
+
+  //           cgi->has_cell_id = 1;
+  //           CellIdentity_t cId = meas_list.list.array[i]->
+  //                     cgi_Info->cellGlobalId.cellIdentity;
+  //           cgi->cell_id = (cId.buf[0] << 20) + (cId.buf[1] << 12) +
+  //                   (cId.buf[2] << 4) + (cId.buf[3] >> 4);
+
+  //           /* Public land mobile network identifier of neighbor
+  //            * cell.
+  //            */
+  //           PlmnIdentity *plmn_id;
+  //           plmn_id = malloc(sizeof(PlmnIdentity));
+  //           plmn_identity__init(plmn_id);
+
+  //           MNC_t mnc = meas_list.list.array[i]->
+  //                 cgi_Info->cellGlobalId.plmn_Identity.mnc;
+
+  //           plmn_id->has_mnc = 1;
+  //           plmn_id->mnc = 0;
+  //           for (m = 0; m < mnc.list.count; m++) {
+  //             plmn_id->mnc += *mnc.list.array[m] *
+  //               ((uint32_t) pow(10, mnc.list.count - m - 1));
+  //           }
+
+  //           MCC_t *mcc = meas_list.list.array[i]->
+  //                 cgi_Info->cellGlobalId.plmn_Identity.mcc;
+
+  //           plmn_id->has_mcc = 1;
+  //           plmn_id->mcc = 0;
+  //           for (m = 0; m < mcc->list.count; m++) {
+  //             plmn_id->mcc += *mcc->list.array[m] *
+  //               ((uint32_t) pow(10, mcc->list.count - m - 1));
+  //           }
+
+  //           TrackingAreaCode_t tac = meas_list.list.array[i]->
+  //                         cgi_Info->trackingAreaCode;
+
+  //           cgi_meas->has_tracking_area_code = 1;
+  //           cgi_meas->tracking_area_code = (tac.buf[0] << 8) +
+  //                               (tac.buf[1]);
+
+  //           PLMN_IdentityList2_t *plmn_l = meas_list.list.array[i]->
+  //                         cgi_Info->plmn_IdentityList;
+
+  //           cgi_meas->n_plmn_id = plmn_l->list.count;
+  //           /* Set the PLMN ID list in CGI measurements. */
+  //           PlmnIdentity **plmn_id_l;
+  //           plmn_id_l = malloc(sizeof(PlmnIdentity *) *
+  //                           cgi_meas->n_plmn_id);
+
+  //           MNC_t mnc2;
+  //           MCC_t *mcc2;
+  //           for (m = 0; m < cgi_meas->n_plmn_id; m++) {
+  //             plmn_id_l[m] = malloc(sizeof(PlmnIdentity));
+  //             plmn_identity__init(plmn_id_l[m]);
+
+  //             mnc2 = plmn_l->list.array[m]->mnc;
+  //             plmn_id_l[m]->has_mnc = 1;
+  //             plmn_id_l[m]->mnc = 0;
+  //             for (k = 0; k < mnc2.list.count; k++) {
+  //               plmn_id_l[m]->mnc += *mnc2.list.array[k] *
+  //               ((uint32_t) pow(10, mnc2.list.count - k - 1));
+  //             }
+
+  //             mcc2 = plmn_l->list.array[m]->mcc;
+  //             plmn_id_l[m]->has_mcc = 1;
+  //             plmn_id_l[m]->mcc = 0;
+  //             for (k = 0; k < mcc2->list.count; k++) {
+  //               plmn_id_l[m]->mcc += *mcc2->list.array[k] *
+  //               ((uint32_t) pow(10, mcc2->list.count - k - 1));
+  //             }
+  //           }
+  //           cgi_meas->plmn_id = plmn_id_l;
+  //           eutra_meas[i]->cgi_meas = cgi_meas;
+  //         }
+  //       }
+  //       neigh_meas->eutra_meas = eutra_meas;
+  //     }
+  //   }
+  //   repl->neigh_meas = neigh_meas;
+  // }
+  /* Attach the RRC measurement reply message to RRC measurements message. */
+  // mrrc_meas->repl = repl;
+  /* Attach RRC measurement message to triggered event message. */
+  // te->mrrc_meas = mrrc_meas;
+  // te->has_action = 0;
+  /* Attach the triggered event message to main message. */
+  // reply->te = te;
+
+  /* Send the report to controller. */
+  // if (flexran_agent_msg_send(b_id, reply) < 0) {
+  //   goto error;
+  // }
+
+  /* Free the measurement report received from UE. */
+  // ASN_STRUCT_FREE(asn_DEF_MeasResults, p->meas);
+  /* Free the params. */
+  // free(p);
+
+
+  // stats_reply_msg->cell_report = cell_report;
+    
+  // stats_reply_msg->ue_report = ue_report;
+  
+  // msg = malloc(sizeof(Protocol__FlexranMessage));
+  // if(msg == NULL)
+  //   goto error;
+  // protocol__flexran_message__init(msg);
+  // msg->msg_case = PROTOCOL__FLEXRAN_MESSAGE__MSG_STATS_REPLY_MSG;
+  // msg->msg_dir = PROTOCOL__FLEXRAN_DIRECTION__SUCCESSFUL_OUTCOME;
+  // msg->stats_reply_msg = stats_reply_msg;
+  
+  // data = flexran_agent_pack_message(msg, &size);
+  
+  
+  // if (flexran_agent_msg_send(mod_id, FLEXRAN_AGENT_DEFAULT, data, size, priority)) {
+  
+  //   err_code = PROTOCOL__FLEXRAN_ERR__MSG_ENQUEUING;
+  //   goto error;
+  // }
+  
+  //  LOG_I(FLEXRAN_AGENT,"RRC Trigger is done  \n");
+
+  return;
+
+  // error:
+
+    // LOG_E(FLEXRAN_AGENT, "Could not send UE state message becasue of %d \n",err_code);
+    /* Free the measurement report received from UE. */
+    // ASN_STRUCT_FREE(asn_DEF_MeasResults, p->meas);
+    /* Free the params. */
+    // free(p);
+    // return -1;
+}
+
+
+int flexran_agent_rrc_stats_reply(mid_t mod_id,       
+          const report_config_t *report_config,
+           Protocol__FlexUeStatsReport **ue_report,
+           Protocol__FlexCellStatsReport **cell_report) {
+
+
+  // Protocol__FlexHeader *header;
+  int i,j;
+
+  /* Allocate memory for list of UE reports */
+  if (report_config->nr_ue > 0) {
+
+    for (i = 0; i < report_config->nr_ue; i++) {
+      
+      /* Check flag for creation of buffer status report */
+      if (report_config->ue_report_type[i].ue_report_flags & PROTOCOL__FLEX_UE_STATS_TYPE__FLUST_RRC_MEASUREMENTS) {
+      	
+        /*Source Cell*/
+        Protocol__FlexRrcMeasurements *rrc_measurements;
+      	rrc_measurements = malloc(sizeof(Protocol__FlexRrcMeasurements));
+      	if (rrc_measurements == NULL)
+      	  goto error;
+      	protocol__flex_rrc_measurements__init(rrc_measurements);
+      	
+      	rrc_measurements->measid = flexran_get_rrc_pcell_measid(mod_id,i);
+      	rrc_measurements->has_measid = 1;
+      	
+      	rrc_measurements->pcell_rsrp = flexran_get_rrc_pcell_rsrp(mod_id,i);
+      	rrc_measurements->has_pcell_rsrp = 1;
+      	
+      	rrc_measurements->pcell_rsrq = flexran_get_rrc_pcell_rsrq(mod_id,i);
+      	rrc_measurements->has_pcell_rsrq = 1 ;
+
+        
+        /* Target Cell, Neghibouring*/
+        Protocol__FlexNeighCellsMeasurements *neigh_meas;
+        neigh_meas = malloc(sizeof(Protocol__FlexNeighCellsMeasurements));
+        if (neigh_meas == NULL)
+          goto error;
+        protocol__flex_neigh_cells_measurements__init(neigh_meas);
+         
+        
+        neigh_meas->n_eutra_meas = flexran_get_rrc_num_ncell(mod_id, i);
+
+        Protocol__FlexEutraMeasurements **eutra_meas = NULL;
+
+        if (neigh_meas->n_eutra_meas > 0){
+          
+          eutra_meas = malloc(sizeof(Protocol__FlexEutraMeasurements) * neigh_meas->n_eutra_meas);
+          if (eutra_meas == NULL)
+            goto error;
+          
+          for (j = 0; j < neigh_meas->n_eutra_meas; j++ ){
+
+              eutra_meas[j] = malloc(sizeof(Protocol__FlexEutraMeasurements));
+              if (eutra_meas[j] == NULL)
+                goto error;
+
+              protocol__flex_eutra_measurements__init(eutra_meas[j]);
+
+              eutra_meas[j]->phys_cell_id = flexran_get_rrc_neigh_phy_cell_id(mod_id, i, j);
+              eutra_meas[j]->has_phys_cell_id = 1;
+
+
+              /*TODO: Extend for CGI and PLMNID*/
+
+              Protocol__FlexEutraRefSignalMeas *meas_result;
+              meas_result = malloc(sizeof(Protocol__FlexEutraRefSignalMeas));
+
+              protocol__flex_eutra_ref_signal_meas__init(meas_result);     
+
+              meas_result->rsrp = flexran_get_rrc_neigh_rsrp(mod_id, i, eutra_meas[j]->phys_cell_id);
+              meas_result->has_rsrp = 1;
+
+              meas_result->rsrq = flexran_get_rrc_neigh_rsrq(mod_id, i, eutra_meas[j]->phys_cell_id);
+              meas_result->has_rsrq = 1;
+
+              eutra_meas[j]->meas_result = meas_result;
+             
+          }    
+
+           neigh_meas->eutra_meas = eutra_meas;   
+
+           rrc_measurements->neigh_meas = neigh_meas;
+       
+        }
+
+      	 ue_report[i]->rrc_measurements = rrc_measurements;
+      	
+      }
+
+    } 
+
+  }
+
+  /* To be considered for RRC signaling of cell*/ 
+  // if (report_config->nr_cc > 0) { 
+    
+            
+  //           // Fill in the Cell reports
+  //           for (i = 0; i < report_config->nr_cc; i++) {
+
+
+  //                     /* Check flag for creation of noise and interference report */
+  //                     if(report_config->cc_report_type[i].cc_report_flags & PROTOCOL__FLEX_CELL_STATS_TYPE__FLCST_NOISE_INTERFERENCE) {
+  //                           // TODO: Fill in the actual noise and interference report for this cell
+  //                           Protocol__FlexNoiseInterferenceReport *ni_report;
+  //                           ni_report = malloc(sizeof(Protocol__FlexNoiseInterferenceReport));
+  //                           if(ni_report == NULL)
+  //                             goto error;
+  //                           protocol__flex_noise_interference_report__init(ni_report);
+  //                           // Current frame and subframe number
+  //                           ni_report->sfn_sf = flexran_get_sfn_sf(enb_id);
+  //                           ni_report->has_sfn_sf = 1;
+  //                           //TODO:Received interference power in dbm
+  //                           ni_report->rip = 0;
+  //                           ni_report->has_rip = 1;
+  //                           //TODO:Thermal noise power in dbm
+  //                           ni_report->tnp = 0;
+  //                           ni_report->has_tnp = 1;
+
+  //                           ni_report->p0_nominal_pucch = flexran_get_p0_nominal_pucch(enb_id, 0);
+  //                           ni_report->has_p0_nominal_pucch = 1;
+  //                           cell_report[i]->noise_inter_report = ni_report;
+  //                     }
+  //           }
+            
+
+      
+            
+  // }
+
+  return 0;
+
+ error:
+
+  for (i = 0; i < report_config->nr_ue; i++){
+
+      if (ue_report[i]->rrc_measurements->neigh_meas != NULL){
+          for (j = 0; j < flexran_get_rrc_num_ncell(mod_id, i); j++){
+
+             free(ue_report[i]->rrc_measurements->neigh_meas->eutra_meas[j]);
+        }
+        free(ue_report[i]->rrc_measurements->neigh_meas);
+      }
+  }
+
+  if (cell_report != NULL)
+        free(cell_report);
+  if (ue_report != NULL)
+        free(ue_report);
+
+  return -1;
+}
+
+
+int flexran_agent_register_rrc_xface(mid_t mod_id, AGENT_RRC_xface *xface) {
+  if (rrc_agent_registered[mod_id]) {
+    LOG_E(RRC, "RRC agent for eNB %d is already registered\n", mod_id);
+    return -1;
+  }
+
+//  xface->flexran_agent_send_update_rrc_stats = flexran_agent_send_update_rrc_stats;
+  
+  xface->flexran_agent_notify_ue_state_change = flexran_agent_ue_state_change;
+  xface->flexran_trigger_rrc_measurements = flexran_trigger_rrc_measurements;
+
+  rrc_agent_registered[mod_id] = 1;
+  agent_rrc_xface[mod_id] = xface;
+
+  return 0;
+}
+
+int flexran_agent_unregister_rrc_xface(mid_t mod_id, AGENT_RRC_xface *xface) {
+
+  //xface->agent_ctxt = NULL;
+//  xface->flexran_agent_send_update_rrc_stats = NULL;
+
+  xface->flexran_agent_notify_ue_state_change = NULL;
+  xface->flexran_trigger_rrc_measurements = NULL;
+  rrc_agent_registered[mod_id] = 0;
+  agent_rrc_xface[mod_id] = NULL;
+
+  return 0;
+}
diff --git a/openair2/ENB_APP/CONTROL_MODULES/RRC/flexran_agent_rrc.h b/openair2/ENB_APP/CONTROL_MODULES/RRC/flexran_agent_rrc.h
new file mode 100644
index 0000000000000000000000000000000000000000..ae26b4162116268f8de7227a8c532539a0ca7081
--- /dev/null
+++ b/openair2/ENB_APP/CONTROL_MODULES/RRC/flexran_agent_rrc.h
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The OpenAirInterface Software Alliance licenses this file to You under
+ * the OAI Public License, Version 1.0  (the "License"); you may not use this file
+ * except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.openairinterface.org/?page_id=698
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *-------------------------------------------------------------------------------
+ * For more information about the OpenAirInterface (OAI) Software Alliance:
+ *      contact@openairinterface.org
+ */ 
+
+/*! \file flexran_agent_rrc.h
+ * \brief FlexRAN agent Control Module RRC header
+ * \author shahab SHARIAT BAGHERI 
+ * \date 2017
+ * \version 0.1
+ */
+
+#ifndef FLEXRAN_AGENT_RRC_H_
+#define FLEXRAN_AGENT_RRC_H_
+
+#include "header.pb-c.h"
+#include "flexran.pb-c.h"
+#include "stats_messages.pb-c.h"
+#include "stats_common.pb-c.h"
+
+
+#include "flexran_agent_common.h"
+#include "flexran_agent_rrc_defs.h"
+
+
+/* Initialization function for the agent structures etc */
+void flexran_agent_init_rrc_agent(mid_t mod_id);
+
+/* UE state change message constructor and destructor */
+void flexran_agent_ue_state_change(mid_t mod_id, uint32_t rnti, uint8_t state_change);
+int flexran_agent_destroy_ue_state_change(Protocol__FlexranMessage *msg);
+
+
+/**********************************
+ * FlexRAN agent - technology RRC API
+ **********************************/
+
+/* Send to the controller all the rrc stat updates that occured during this subframe*/
+// void flexran_agent_send_update_rrc_stats(mid_t mod_id);
+
+/* this is called by RRC as a part of rrc xface  . The controller previously requested  this*/ 
+void flexran_trigger_rrc_measurements (mid_t mod_id, MeasResults_t *);
+
+/* Statistics reply protocol message constructor and destructor */
+int flexran_agent_rrc_stats_reply(mid_t mod_id, const report_config_t *report_config, Protocol__FlexUeStatsReport **ue_report, Protocol__FlexCellStatsReport **cell_report);
+int flexran_agent_rrc_destroy_stats_reply(Protocol__FlexranMessage *msg);
+
+/*Register technology specific interface callbacks*/
+int flexran_agent_register_rrc_xface(mid_t mod_id, AGENT_RRC_xface *xface);
+
+/*Unregister technology specific callbacks*/
+int flexran_agent_unregister_rrc_xface(mid_t mod_id, AGENT_RRC_xface*xface);
+
+#endif
diff --git a/openair2/ENB_APP/CONTROL_MODULES/RRC/flexran_agent_rrc_defs.h b/openair2/ENB_APP/CONTROL_MODULES/RRC/flexran_agent_rrc_defs.h
new file mode 100644
index 0000000000000000000000000000000000000000..a101bab242cb22bf44de260391ddcbb3aaed537b
--- /dev/null
+++ b/openair2/ENB_APP/CONTROL_MODULES/RRC/flexran_agent_rrc_defs.h
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The OpenAirInterface Software Alliance licenses this file to You under
+ * the OAI Public License, Version 1.0  (the "License"); you may not use this file
+ * except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.openairinterface.org/?page_id=698
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *-------------------------------------------------------------------------------
+ * For more information about the OpenAirInterface (OAI) Software Alliance:
+ *      contact@openairinterface.org
+ */ 
+
+
+/*! \file flexran_agent_rrc_defs.h
+ * \brief FlexRAN agent - RRC interface primitives
+ * \author shahab SHARIAT BAGHERI
+ * \date 2017
+ * \version 0.1
+ * \mail 
+ */
+
+#ifndef __FLEXRAN_AGENT_RRC_PRIMITIVES_H__
+#define __FLEXRAN_AGENT_RRC_PRIMITIVES_H__
+
+#include "PHY/extern.h"
+#include "flexran_agent_defs.h"
+#include "flexran.pb-c.h"
+#include "header.pb-c.h"
+#include "MeasResults.h"
+
+#define RINGBUFFER_SIZE 100
+
+
+typedef struct 
+{
+   int32_t rnti; 
+   int32_t meas_id;
+   int32_t rsrp;
+   int32_t rsrq;
+
+   /*To Be Extended*/
+}rrc_meas_stats;
+
+/* RRC CMI statistics */
+rrc_meas_stats * meas_stats;
+
+
+/* FLEXRAN AGENT-RRC Interface */
+typedef struct {
+  
+  
+   /// Notify the controller for a state change of a particular UE, by sending the proper
+  /// UE state change message (ACTIVATION, DEACTIVATION, HANDOVER)
+  void (*flexran_agent_notify_ue_state_change)(mid_t mod_id, uint32_t rnti,
+                 uint8_t state_change);
+
+  void (*flexran_trigger_rrc_measurements)(mid_t mod_id, MeasResults_t*  measResults);
+  
+} AGENT_RRC_xface;
+
+#endif
diff --git a/openair2/ENB_APP/MESSAGES/V2/config_messages.proto b/openair2/ENB_APP/MESSAGES/V2/config_messages.proto
index ac939b828cc13399511a808a92159919285b7d39..995865f1ab533e79d70aa71b8774ea303fed0c55 100644
--- a/openair2/ENB_APP/MESSAGES/V2/config_messages.proto
+++ b/openair2/ENB_APP/MESSAGES/V2/config_messages.proto
@@ -38,6 +38,11 @@ message flex_cell_config {
 	optional uint32 srs_mac_up_pts = 32;		// Boolean value. See TS 36.211, section 5.5.3.2. TDD only
 	optional uint32 enable_64QAM = 33;		// One of the FLEQ_* enum values
 	optional uint32 carrier_index = 34;		// Carrier component index
+	optional uint32 dl_freq = 35;        // operating downlink frequency
+	optional uint32 ul_freq = 36;       // operating uplink frequency 
+	optional uint32 eutra_band= 37;       // operating band 
+	optional int32 dl_pdsch_power = 38;       // operating downlink power 
+	optional int32 ul_pusch_power = 39;       // operating uplink power
 }
 
 message flex_ue_config {
diff --git a/openair2/ENB_APP/MESSAGES/V2/control_delegation.proto b/openair2/ENB_APP/MESSAGES/V2/control_delegation.proto
index 0f7e34de156599a448265e2846b9b69c83aea5c6..ef0eea3bd2eb9ed7062ec11195e6856d246a806c 100644
--- a/openair2/ENB_APP/MESSAGES/V2/control_delegation.proto
+++ b/openair2/ENB_APP/MESSAGES/V2/control_delegation.proto
@@ -3,4 +3,4 @@ package protocol;
 
 enum flex_control_delegation_type {
      FLCDT_MAC_DL_UE_SCHEDULER = 1;		// DL UE scheduler delegation
-}
\ No newline at end of file
+}
diff --git a/openair2/ENB_APP/MESSAGES/V2/controller_commands.proto b/openair2/ENB_APP/MESSAGES/V2/controller_commands.proto
index c92f171b0ee9e21d163633b86c021e74aa47b641..29e072383550fce0fc6dbabc2265fd79e1e62ed5 100644
--- a/openair2/ENB_APP/MESSAGES/V2/controller_commands.proto
+++ b/openair2/ENB_APP/MESSAGES/V2/controller_commands.proto
@@ -16,6 +16,12 @@ message flex_dl_data {
 	optional uint32 act_deact_ce = 6; //Hex content of MAC CE for Activation/Deactivation in CA
 }
 
+
+message flex_ul_data {
+        optional uint32 rnti = 1;
+        optional flex_ul_dci ul_dci = 2;
+}
+
 //
 // Body of the RAR scheduler configuration
 //
@@ -56,4 +62,4 @@ message flex_pdcch_ofdm_sym_count {
 enum flex_broadcast_type {
      FLBT_BCCH = 0;
      FLBT_PCCH = 1;
-}
\ No newline at end of file
+}
diff --git a/openair2/ENB_APP/MESSAGES/V2/flexran.proto b/openair2/ENB_APP/MESSAGES/V2/flexran.proto
index 8c0c300efea152c1b5a3943807504d5d1295bfaf..b54fc171c6acb831466726e40ec33ed3e941bb17 100644
--- a/openair2/ENB_APP/MESSAGES/V2/flexran.proto
+++ b/openair2/ENB_APP/MESSAGES/V2/flexran.proto
@@ -8,6 +8,7 @@ import "config_messages.proto";
 import "controller_commands.proto";
 import "control_delegation.proto";
 
+
 message flexran_message {
        optional flexran_direction msg_dir = 100;
 	oneof msg {
@@ -28,6 +29,8 @@ message flexran_message {
 	      flex_ue_state_change ue_state_change_msg = 15;
 	      flex_control_delegation control_delegation_msg = 16;
 	      flex_agent_reconfiguration agent_reconfiguration_msg = 17;
+	      flex_rrc_triggering rrc_triggering = 18;
+	      flex_ul_mac_config ul_mac_config_msg = 19;
 	}
 }
 
@@ -130,6 +133,7 @@ message flex_enb_config_reply {
 	optional flex_header header = 1;
 	optional uint32 eNB_id = 2;		// Unique id to distinguish the eNB
 	repeated flex_cell_config cell_config = 3;
+        optional uint32 device_spec = 4;
 }
 
 message flex_ue_config_request {
@@ -163,6 +167,18 @@ message flex_dl_mac_config {
 	repeated flex_pdcch_ofdm_sym_count ofdm_sym = 6; // OFDM symbol count for each CC
 }
 
+message flex_ul_mac_config {
+	optional flex_header header = 1;
+ 	optional uint32 sfn_sf = 2;
+	repeated flex_ul_data ul_ue_data = 3;
+}
+
+message flex_rrc_triggering {
+
+	optional flex_header header = 1;
+	optional string rrc_trigger = 2;	
+}
+
 //
 // UE state change message
 //
@@ -190,7 +206,7 @@ message flex_control_delegation {
 
 message flex_agent_reconfiguration {
 	optional flex_header header = 1;
-	optional string policy = 2;		// The policy changes using YAML syntax in string format
+	optional string policy = 2;		// The policy changes using YAML syntax in string format    
 }
 
 // Extensions of the echo request and reply
diff --git a/openair2/ENB_APP/MESSAGES/V2/header.proto b/openair2/ENB_APP/MESSAGES/V2/header.proto
index 939429f51fe134c644d14dce5097154bea17e280..8900b934920eca605cce1746c2aa014ef8564bce 100644
--- a/openair2/ENB_APP/MESSAGES/V2/header.proto
+++ b/openair2/ENB_APP/MESSAGES/V2/header.proto
@@ -40,5 +40,7 @@ enum flex_type {
      // Control delegation messages
      FLPT_DELEGATE_CONTROL = 15;
      FLPT_RECONFIGURE_AGENT = 16;
+     FLPT_RRC_TRIGGERING = 17;
+     FLPT_UL_MAC_CONFIG = 18;
 }
 
diff --git a/openair2/ENB_APP/MESSAGES/V2/mac_primitives.proto b/openair2/ENB_APP/MESSAGES/V2/mac_primitives.proto
index 89b8f0e380605a12077aae640728b7fbf25fcc47..bd2b9cbe509a887b83f29fbfca13c2e29bf1bf2a 100644
--- a/openair2/ENB_APP/MESSAGES/V2/mac_primitives.proto
+++ b/openair2/ENB_APP/MESSAGES/V2/mac_primitives.proto
@@ -36,6 +36,39 @@ message flex_dl_dci {
 	optional uint32 cif = 27;     		// CIF for cross-carrier scheduling
 }
 
+message flex_ul_dci {
+        optional uint32 rnti = 1;
+        optional uint32 rb_start = 2;           // The start RB allocated to the UE 
+        optional uint32 rb_len = 3;             // The number of RBs allocated to the UE
+        optional uint32 mcs = 4;                // Modulation and coding scheme
+        optional uint32 cyclic_shift2 = 5;      //  match DCI format 0/4 PDU 
+        optional uint32 freq_hop_flag = 6;      // 0 no hopping, 1 hoppping
+        optional uint32 freq_hop_map = 7;       // Frequency hopping bits (0..4) 
+        optional uint32 ndi = 8;                // New data indicator
+        optional uint32 rv = 9;                 // Redundancy version
+        optional uint32 harq_pid = 10;          //  The harq process id
+        optional uint32 ultx_mode = 11;         //  A FLULM_* value
+        optional uint32 tbs_size = 12;          // The size of each TBS
+        optional uint32 n_srs = 13;             // Overlap indication with srs
+        optional uint32 res_alloc = 14;         // Type of resource allocation
+        optional uint32 size = 15;    // Size of the ULSCH PDU in bytes for UL Grant.
+
+        optional uint32 dai = 16;               // TDD only
+
+//      optional uint32 tb_swap = 17;           // Boolean. TB to codeword swap flag
+
+//      optional uint32 pdcch_order = 19;
+//      optional uint32 preamble_index = 20;    // Only valid if pdcch_order = 1
+//      optional uint32 prach_mask_index = 21;  // Only valid if pdcch_order = 1
+
+//      optional uint32 tbs_idx = 23;           // The TBS index for Format 1A
+
+
+
+
+}
+
+
 //
 // Messages related to the creation of RLC PDUs
 //
@@ -74,4 +107,4 @@ enum flex_vrb_format {
 enum flex_ngap_val {
      FLNGV_1 = 0;
      FLNGV_2 = 1;
-}
\ No newline at end of file
+}
diff --git a/openair2/ENB_APP/MESSAGES/V2/stats_common.proto b/openair2/ENB_APP/MESSAGES/V2/stats_common.proto
index fa985bf9cc4af4cdfa8318d640239364aac58af2..f651195ab14c51359788acf770a9bc9df42890c6 100644
--- a/openair2/ENB_APP/MESSAGES/V2/stats_common.proto
+++ b/openair2/ENB_APP/MESSAGES/V2/stats_common.proto
@@ -182,3 +182,90 @@ message flex_noise_interference_report {
 	optional int32 p0_nominal_pucch = 4;
 }
 
+//
+// RRC Measurements Primitives
+//
+
+
+message flex_rrc_measurements {
+	// Measurement identifier.
+	optional int32 measid = 1;
+	// Primary Cell Reference Signal Received Power (RSRP).
+	optional int32 pcell_rsrp = 2;
+	// Primary Cell Reference Signal Received Quality (RSRQ).
+	optional int32 pcell_rsrq = 3;
+	// Neighboring cells measurements performed by UE.
+	optional flex_neigh_cells_measurements neigh_meas = 4;
+}
+
+message flex_neigh_cells_measurements {
+	// Neighboring EUTRA cells measurements.
+	repeated flex_eutra_measurements eutra_meas = 1;
+}
+
+message flex_eutra_measurements {
+	// Physical Cell identifier.
+	optional int32 phys_cell_id = 1;
+	// EUTRA Cell Global Identity (CGI) measurement.
+	optional flex_eutra_cgi_measurements cgi_meas = 2;
+	// EUTRA nearby cell reference signal measurement.
+	optional flex_eutra_ref_signal_meas meas_result = 3;
+}
+
+message flex_eutra_cgi_measurements {
+	// EUTRA Cell Global Identity (CGI).
+	optional flex_cell_global_eutra_id cgi = 1;
+	// Tracking area code of the neighbor cell.
+	optional uint32 tracking_area_code = 2;
+	// Public land mobile network identifiers of neighbor cell.
+	repeated flex_plmn_identity plmn_id = 3;
+}
+
+message flex_cell_global_eutra_id {
+	// Public land mobile network identifier of neighbor cell.
+	optional flex_plmn_identity plmn_id = 1;
+	// Cell identifier of neighbor cell.
+	optional uint32 cell_id = 2;
+}
+
+message flex_plmn_identity {
+	// Mobile Network Code (MNC).
+	repeated uint32 mnc = 1;
+	// Mobile Country Code (MCC).
+	repeated uint32 mcc = 2;
+	// tracking area code 
+	repeated uint32 tac = 3;
+}
+
+message flex_eutra_ref_signal_meas {
+	// Neighboring Cell RSRP
+	optional int32 rsrp = 1;
+	// Neighboring Cell RSRQ	
+	optional int32 rsrq = 2;
+}
+
+//
+// PDCP Statistics
+//
+
+message flex_pdcp_stats {
+
+	optional uint32 pkt_tx = 1;
+	optional uint32 pkt_tx_bytes = 2;
+	optional uint32 pkt_tx_sn = 3;
+	optional uint32 pkt_tx_w = 4;
+	optional uint32 pkt_tx_bytes_w = 5;
+	optional uint32 pkt_tx_aiat = 7;
+	optional uint32 pkt_tx_aiat_w = 8;
+	
+	optional uint32 pkt_rx = 9;
+	optional uint32 pkt_rx_bytes = 10;
+	optional uint32 pkt_rx_sn = 11;
+	optional uint32 pkt_rx_w = 12;
+	optional uint32 pkt_rx_bytes_w = 13;
+	optional uint32 pkt_rx_aiat = 14;
+	optional uint32 pkt_rx_aiat_w = 15;
+	optional uint32 pkt_rx_oo = 16;
+
+	optional uint64 sfn=17;
+}
diff --git a/openair2/ENB_APP/MESSAGES/V2/stats_messages.proto b/openair2/ENB_APP/MESSAGES/V2/stats_messages.proto
index d8c0651fa16962a0f26e9c2c922cf0e9dbbd02c9..b8126c55f221a1d8733436a86d42b742391074fd 100644
--- a/openair2/ENB_APP/MESSAGES/V2/stats_messages.proto
+++ b/openair2/ENB_APP/MESSAGES/V2/stats_messages.proto
@@ -47,6 +47,8 @@ message flex_ue_stats_report {
 	optional flex_dl_cqi_report dl_cqi_report = 7;
 	optional flex_paging_buffer_report pbr = 8;
 	optional flex_ul_cqi_report ul_cqi_report = 9;
+	optional flex_rrc_measurements rrc_measurements = 10;
+    optional flex_pdcp_stats pdcp_stats = 11;
 }
 
 //
@@ -77,11 +79,15 @@ enum flex_cell_stats_type {
 // Flags for UE-related statistics
 enum flex_ue_stats_type {
      FLUST_BSR = 1;
-     FLUST_PRH = 2;
+     FLUST_PHR = 2;
      FLUST_RLC_BS = 4;
      FLUST_MAC_CE_BS = 8;
      FLUST_DL_CQI = 16;
      FLUST_PBS = 32;
      FLUST_UL_CQI = 64;
+
+     FLUST_PDCP_STATS = 1024;     
+     FLUST_RRC_MEASUREMENTS = 65536;
      // To be extended with more types of stats
-}
\ No newline at end of file
+    
+}
diff --git a/openair2/ENB_APP/MESSAGES/V2/time_common.proto b/openair2/ENB_APP/MESSAGES/V2/time_common.proto
index 8bd2497443daaed136dc55b39740c66776d95795..6c0affbe51e676a8b725de582098af960ad2ca87 100644
--- a/openair2/ENB_APP/MESSAGES/V2/time_common.proto
+++ b/openair2/ENB_APP/MESSAGES/V2/time_common.proto
@@ -25,6 +25,7 @@ message flex_ul_info {
 	repeated uint32 ul_reception = 2;
 	optional uint32 reception_status = 3;
 	optional uint32 tpc = 4;
-	optional uint32 serv_cell_index = 5; 
+	optional uint32 serv_cell_index = 5;
+	optional uint32 rssi = 6;
 }
 
diff --git a/openair2/ENB_APP/enb_app.c b/openair2/ENB_APP/enb_app.c
index a163b031c95f4c7a55dcf84b1c8b5d3f1cf42315..bd9be082c2b2d12a1a2c827fb5cfb6bc3897ff13 100644
--- a/openair2/ENB_APP/enb_app.c
+++ b/openair2/ENB_APP/enb_app.c
@@ -51,7 +51,7 @@
 # endif
 
 #if defined(FLEXRAN_AGENT_SB_IF)
-#   include "flexran_agent.h"
+#   include "targets/RT/USER/lte-softmodem.h"
 #endif
 
 extern unsigned char NB_eNB_INST;
@@ -206,6 +206,15 @@ static void configure_rrc(uint32_t enb_id)
   else AssertFatal(0,"RRC context for eNB %d not allocated\n",enb_id);
 }
 
+void enb_app_start_phy_rrc(uint32_t enb_id_start, uint32_t enb_id_end)
+{
+  Enb_properties_array_t *enb_properties_p = enb_config_get();
+  for (uint32_t enb_id = enb_id_start; (enb_id < enb_id_end) ; enb_id++) {
+    configure_phy(enb_id, enb_properties_p);
+    configure_rrc(enb_id, enb_properties_p);
+  }
+}
+
 /*------------------------------------------------------------------------------*/
 # if defined(ENABLE_USE_MME)
 static uint32_t eNB_app_register(uint32_t enb_id_start, uint32_t enb_id_end)//, const Enb_properties_array_t *enb_properties)
@@ -288,15 +297,15 @@ void *eNB_app_task(void *args_p)
 #if defined(ENABLE_ITTI)
   uint32_t                        enb_nb = RC.nb_inst; 
   uint32_t                        enb_id_start = 0;
+  uint32_t                        enb_i;
   uint32_t                        enb_id_end = enb_id_start + enb_nb;
 # if defined(ENABLE_USE_MME)
   uint32_t                        register_enb_pending;
   uint32_t                        registered_enb;
   long                            enb_register_retry_timer_id;
 # endif
-  uint32_t                        enb_id;
-  MessageDef                      *msg_p           = NULL;
-  const char                      *msg_name        = NULL;
+  MessageDef                     *msg_p           = NULL;
+  const char                     *msg_name        = NULL;
   instance_t                      instance;
   int                             result;
   /* for no gcc warnings */
@@ -331,21 +340,13 @@ void *eNB_app_task(void *args_p)
 
   RC.rrc = (eNB_RRC_INST **)malloc(RC.nb_inst*sizeof(eNB_RRC_INST *));
 
-  for (enb_id = enb_id_start; (enb_id < enb_id_end) ; enb_id++) {
-    RC.rrc[enb_id] = (eNB_RRC_INST*)malloc(sizeof(eNB_RRC_INST));
-    memset((void *)RC.rrc[enb_id],0,sizeof(eNB_RRC_INST));
-    configure_rrc(enb_id);
-  }
-  
-#if defined (FLEXRAN_AGENT_SB_IF)
-  
-  for (enb_id = enb_id_start; (enb_id < enb_id_end) ; enb_id++) {
-    printf("\n start enb agent %d\n", enb_id);
-    flexran_agent_start(enb_id, enb_properties_p);
+  enb_app_start_phy_rrc(enb_id_start, enb_id_end);
+
+#ifdef FLEXRAN_AGENT_SB_IF 
+  for (enb_i = 0; enb_i <1; enb_i ++){ // To be handled for all of current eNB
+    flexran_set_enb_vars(enb_i, RAN_LTE_OAI);
   }
 #endif 
-  
-
 
 # if defined(ENABLE_USE_MME)
   /* Try to register each eNB */
@@ -366,6 +367,7 @@ void *eNB_app_task(void *args_p)
 
     switch (ITTI_MSG_ID(msg_p)) {
     case TERMINATE_MESSAGE:
+      LOG_W(TASK_ENB_APP, " *** Exiting ENB_APP thread\n");
       itti_exit_task ();
       break;
 
diff --git a/openair2/ENB_APP/enb_app.h b/openair2/ENB_APP/enb_app.h
index 52f63806e8e9a27fd042b759ff12ace41f23c892..4dfea72eefbbbf6bc951f562b17f91b869e3ed4a 100644
--- a/openair2/ENB_APP/enb_app.h
+++ b/openair2/ENB_APP/enb_app.h
@@ -30,8 +30,12 @@
 #ifndef ENB_APP_H_
 #define ENB_APP_H_
 
+#include <stdint.h>
 
 
 void *eNB_app_task(void *args_p);
 
+/* needed for flexran: start PHY and RRC when restarting */
+void enb_app_start_phy_rrc(uint32_t enb_id_start, uint32_t enb_id_end);
+
 #endif /* ENB_APP_H_ */
diff --git a/openair2/ENB_APP/flexran_agent.c b/openair2/ENB_APP/flexran_agent.c
index 4faa1f36243353aa7faf6e070e2aa8319a79e8f9..530cb81042f5314261833e538007ccb9e6f63ad2 100644
--- a/openair2/ENB_APP/flexran_agent.c
+++ b/openair2/ENB_APP/flexran_agent.c
@@ -21,27 +21,16 @@
 
 /*! \file flexran_agent.h
  * \brief top level flexran agent receive thread and itti task
- * \author Xenofon Foukas and Navid Nikaein
- * \date 2016
+ * \author Xenofon Foukas and Navid Nikaein and shahab SHARIAT BAGHERI
+ * \date 2017
  * \version 0.1
  */
 
-#include "flexran_agent_common.h"
-#include "log.h"
 #include "flexran_agent.h"
-#include "flexran_agent_mac_defs.h"
-#include "flexran_agent_mac.h"
-#include "flexran_agent_mac_internal.h"
-
-#include "flexran_agent_extern.h"
-
-#include "assertions.h"
-
-#include "flexran_agent_net_comm.h"
-#include "flexran_agent_async.h"
 
 #include <arpa/inet.h>
 
+
 //#define TEST_TIMER
 
 flexran_agent_instance_t flexran_agent[NUM_MAX_ENB];
@@ -85,6 +74,7 @@ void *flexran_agent_task(void *args){
 
     switch (ITTI_MSG_ID(msg_p)) {
     case TERMINATE_MESSAGE:
+      LOG_W(FLEXRAN_AGENT, " *** Exiting FLEXRAN thread\n");
       itti_exit_task ();
       break;
 
@@ -196,14 +186,9 @@ pthread_t new_thread(void *(*f)(void *), void *b) {
   return t;
 }
 
-int channel_container_init = 0;
-int flexran_agent_start(mid_t mod_id, const Enb_properties_array_t* enb_properties){
-  
-  int channel_id;
-  
-  flexran_set_enb_vars(mod_id, RAN_LTE_OAI);
-  flexran_agent[mod_id].enb_id = mod_id;
-  
+void flexran_agent_reconfigure(mid_t mod_id){
+  Enb_properties_array_t *enb_properties = enb_config_get();
+
   /* 
    * check the configuration
    */ 
@@ -213,7 +198,7 @@ int flexran_agent_start(mid_t mod_id, const Enb_properties_array_t* enb_properti
   } else {
     strcpy(local_cache, DEFAULT_FLEXRAN_AGENT_CACHE);
   }
-  
+
   if (enb_properties->properties[mod_id]->flexran_agent_ipv4_address != 0) {
     inet_ntop(AF_INET, &(enb_properties->properties[mod_id]->flexran_agent_ipv4_address), in_ip, INET_ADDRSTRLEN);
   } else {
@@ -229,6 +214,18 @@ int flexran_agent_start(mid_t mod_id, const Enb_properties_array_t* enb_properti
 	flexran_agent[mod_id].enb_id,
 	in_ip,
 	in_port);
+  
+}
+
+int channel_container_init = 0;
+int flexran_agent_start(mid_t mod_id)
+{
+  int channel_id;
+  
+  flexran_set_enb_vars(mod_id, RAN_LTE_OAI);
+  flexran_agent[mod_id].enb_id = mod_id;
+  
+  flexran_agent_reconfigure(mod_id);
 
   /*
    * Initialize the channel container
@@ -264,8 +261,8 @@ int flexran_agent_start(mid_t mod_id, const Enb_properties_array_t* enb_properti
    *flexran_agent_register_channel(mod_id, channel, FLEXRAN_AGENT_MAC);
    */
 
-  /*Initialize the continuous MAC stats update mechanism*/
-  flexran_agent_init_cont_mac_stats_update(mod_id);
+  /*Initialize the continuous stats update mechanism*/
+  flexran_agent_init_cont_stats_update(mod_id);
   
   new_thread(receive_thread, &flexran_agent[mod_id]);
 
@@ -275,6 +272,12 @@ int flexran_agent_start(mid_t mod_id, const Enb_properties_array_t* enb_properti
   AGENT_MAC_xface *mac_agent_xface = (AGENT_MAC_xface *) malloc(sizeof(AGENT_MAC_xface));
   flexran_agent_register_mac_xface(mod_id, mac_agent_xface);
   
+  AGENT_RRC_xface *rrc_agent_xface = (AGENT_RRC_xface *) malloc(sizeof(AGENT_RRC_xface));
+  flexran_agent_register_rrc_xface(mod_id, rrc_agent_xface);
+
+   AGENT_PDCP_xface *pdcp_agent_xface = (AGENT_PDCP_xface *) malloc(sizeof(AGENT_PDCP_xface));
+   flexran_agent_register_pdcp_xface(mod_id, pdcp_agent_xface);
+
   /* 
    * initilize a timer 
    */ 
diff --git a/openair2/ENB_APP/flexran_agent.h b/openair2/ENB_APP/flexran_agent.h
index 579bf3be2357b4a0ad7d942194fc5690d3eec978..f3f71c0631bca494372fb90a16f904c8d44d5933 100644
--- a/openair2/ENB_APP/flexran_agent.h
+++ b/openair2/ENB_APP/flexran_agent.h
@@ -22,20 +22,33 @@
 /*! \file flexran_agent.h
  * \brief top level flexran agent  
  * \author Navid Nikaein and Xenofon Foukas
- * \date 2016
+ * \date 2017
  * \version 0.1
  */
 
 #ifndef FLEXRAN_AGENT_H_
 #define FLEXRAN_AGENT_H_
 
-#include "enb_config.h" // for enb properties
 #include "flexran_agent_common.h"
+#include "flexran_agent_async.h"
+#include "flexran_agent_extern.h"
+#include "flexran_agent_timer.h"
+#include "flexran_agent_defs.h"
+#include "flexran_agent_net_comm.h"
+#include "flexran_agent_ran_api.h"
+#include "flexran_agent_mac.h"
+#include "flexran_agent_rrc.h"
+#include "flexran_agent_pdcp.h"
+#include "log.h"
+#include "assertions.h"
+
+#include "enb_config.h" // for enb properties
 
 
 /* Initiation and termination of the eNodeB agent */
-int flexran_agent_start(mid_t mod_id, const Enb_properties_array_t* enb_properties);
+int flexran_agent_start(mid_t mod_id);
 int flexran_agent_stop(mid_t mod_id);
+void flexran_agent_reconfigure(mid_t mod_id);
 
 /* 
  * enb agent task mainly wakes up the tx thread for periodic and oneshot messages to the controller 
diff --git a/openair2/ENB_APP/flexran_agent_async.c b/openair2/ENB_APP/flexran_agent_async.c
index f1edc291c9cfab179ab46e5f932578e08ad85357..9e099fc21c31dd1b2ecaf39fc389f46e5770c90f 100644
--- a/openair2/ENB_APP/flexran_agent_async.c
+++ b/openair2/ENB_APP/flexran_agent_async.c
@@ -68,12 +68,12 @@ flexran_agent_async_channel_t * flexran_agent_async_channel_info(mid_t mod_id, c
 
  error:
   LOG_I(FLEXRAN_AGENT,"there was an error\n");
-  return 1;
+  return NULL;
 }
 
 int flexran_agent_async_msg_send(void *data, int size, int priority, void *channel_info) {
   flexran_agent_async_channel_t *channel;
-  channel = (flexran_agent_channel_t *)channel_info;
+  channel = (flexran_agent_async_channel_t *)channel_info;
 
   return message_put(channel->send_queue, data, size, priority);
 }
diff --git a/openair2/ENB_APP/flexran_agent_common.c b/openair2/ENB_APP/flexran_agent_common.c
index 69c786edb333e33f0d12679bd5f711e6dbaa0799..b69ddf35cddd62713a96bdc6c39d7a5d49709a39 100644
--- a/openair2/ENB_APP/flexran_agent_common.c
+++ b/openair2/ENB_APP/flexran_agent_common.c
@@ -21,18 +21,20 @@
 
 /*! \file flexran_agent_common.c
  * \brief common primitives for all agents 
- * \author Xenofon Foukas, Mohamed Kassem and Navid Nikaein
- * \date 2016
+ * \author Xenofon Foukas, Mohamed Kassem and Navid Nikaein, shahab SHARIAT BAGHERI
+ * \date 2017
  * \version 0.1
  */
 
-#include<stdio.h>
+#include <stdio.h>
 #include <time.h>
+#include <sys/stat.h>
 
 #include "flexran_agent_common.h"
 #include "flexran_agent_common_internal.h"
 #include "flexran_agent_extern.h"
 #include "flexran_agent_net_comm.h"
+#include "flexran_agent_ran_api.h"
 #include "PHY/extern.h"
 #include "log.h"
 
@@ -41,10 +43,6 @@
 #include "RRC/L2_INTERFACE/openair_rrc_L2_interface.h"
 #include "rrc_eNB_UE_context.h"
 
-void * enb[NUM_MAX_ENB];
-void * enb_ue[NUM_MAX_ENB];
-void * enb_rrc[NUM_MAX_ENB];
-
 /*
  * message primitives
  */
@@ -344,19 +342,6 @@ int flexran_agent_destroy_lc_config_reply(Protocol__FlexranMessage *msg) {
   return -1;
 }
 
-int flexran_agent_destroy_ue_state_change(Protocol__FlexranMessage *msg) {
-  if(msg->msg_case != PROTOCOL__FLEXRAN_MESSAGE__MSG_UE_STATE_CHANGE_MSG)
-    goto error;
-  free(msg->ue_state_change_msg->header);
-  //TODO: Free the contents of the UE config structure
-  free(msg->ue_state_change_msg);
-  free(msg);
-  return 0;
-
- error:
-  //LOG_E(MAC, "%s: an error occured\n", __FUNCTION__);
-  return -1;
-}
 
 int flexran_agent_destroy_enb_config_request(Protocol__FlexranMessage *msg) {
   if(msg->msg_case != PROTOCOL__FLEXRAN_MESSAGE__MSG_ENB_CONFIG_REQUEST_MSG)
@@ -402,14 +387,13 @@ int flexran_agent_control_delegation(mid_t mod_id, const void *params, Protocol_
   Protocol__FlexControlDelegation *control_delegation_msg = input->control_delegation_msg;
 
   //  struct timespec vartime = timer_start();
-  
   //Write the payload lib into a file in the cache and load the lib
   char lib_name[120];
   char target[512];
   snprintf(lib_name, sizeof(lib_name), "/%s.so", control_delegation_msg->name);
   strcpy(target, local_cache);
   strcat(target, lib_name);
-
+  
   FILE *f;
   f = fopen(target, "wb");
   fwrite(control_delegation_msg->payload.data, control_delegation_msg->payload.len, 1, f);
@@ -442,1085 +426,6 @@ int flexran_agent_destroy_agent_reconfiguration(Protocol__FlexranMessage *msg) {
 }
 
 
-/*
- * get generic info from RAN
- */
-
-void flexran_set_enb_vars(mid_t mod_id, ran_name_t ran){
-
-  switch (ran){
-  case RAN_LTE_OAI :
-    enb[mod_id] =  (void *)&eNB_mac_inst[mod_id];
-    enb_ue[mod_id] = (void *)&eNB_mac_inst[mod_id].UE_list;
-    enb_rrc[mod_id] = (void *)&eNB_rrc_inst[mod_id];
-    break;
-  default :
-    goto error;
-  }
-
-  return; 
-
- error:
-  LOG_E(FLEXRAN_AGENT, "unknown RAN name %d\n", ran);
-}
-
-int flexran_get_current_time_ms (mid_t mod_id, int subframe_flag){
-
-  if (subframe_flag == 1){
-    return ((eNB_MAC_INST *)enb[mod_id])->frame*10 + ((eNB_MAC_INST *)enb[mod_id])->subframe;
-  }else {
-    return ((eNB_MAC_INST *)enb[mod_id])->frame*10;
-  }
-   
-}
-
-unsigned int flexran_get_current_frame (mid_t mod_id) {
-
-  //  #warning "SFN will not be in [0-1023] when oaisim is used"
-  return ((eNB_MAC_INST *)enb[mod_id])->frame;
-  
-}
-
-unsigned int flexran_get_current_system_frame_num(mid_t mod_id) {
-  return (flexran_get_current_frame(mod_id) %1024);
-}
-
-unsigned int flexran_get_current_subframe (mid_t mod_id) {
-
-  return ((eNB_MAC_INST *)enb[mod_id])->subframe;
-  
-}
-
-uint16_t flexran_get_sfn_sf (mid_t mod_id) {
-  
-  frame_t frame;
-  sub_frame_t subframe;
-  uint16_t sfn_sf, frame_mask, sf_mask;
-  
-  frame = (frame_t) flexran_get_current_system_frame_num(mod_id);
-  subframe = (sub_frame_t) flexran_get_current_subframe(mod_id);
-  frame_mask = ((1<<12) - 1);
-  sf_mask = ((1<<4) - 1);
-  sfn_sf = (subframe & sf_mask) | ((frame & frame_mask) << 4);
-  
-  return sfn_sf;
-}
-
-uint16_t flexran_get_future_sfn_sf (mid_t mod_id, int ahead_of_time) {
-  
-  frame_t frame;
-  sub_frame_t subframe;
-  uint16_t sfn_sf, frame_mask, sf_mask;
-  
-  frame = (frame_t) flexran_get_current_system_frame_num(mod_id);
-  subframe = (sub_frame_t) flexran_get_current_subframe(mod_id);
-
-  subframe = ((subframe + ahead_of_time) % 10);
-  
-  if (subframe < flexran_get_current_subframe(mod_id)) {
-    frame = (frame + 1) % 1024;
-  }
-  
-  int additional_frames = ahead_of_time / 10;
-  frame = (frame + additional_frames) % 1024;
-  
-  frame_mask = ((1<<12) - 1);
-  sf_mask = ((1<<4) - 1);
-  sfn_sf = (subframe & sf_mask) | ((frame & frame_mask) << 4);
-  
-  return sfn_sf;
-}
-
-int flexran_get_num_ues (mid_t mod_id){
-
-  return  ((UE_list_t *)enb_ue[mod_id])->num_UEs;
-}
-
-int flexran_get_ue_crnti (mid_t mod_id, mid_t ue_id) {
-
-  return  UE_RNTI(mod_id, ue_id);
-}
-
-int flexran_get_ue_bsr (mid_t mod_id, mid_t ue_id, lcid_t lcid) {
-
-  return ((UE_list_t *)enb_ue[mod_id])->UE_template[UE_PCCID(mod_id,ue_id)][ue_id].bsr_info[lcid];
-}
-
-int flexran_get_ue_phr (mid_t mod_id, mid_t ue_id) {
-
-  return ((UE_list_t *)enb_ue[mod_id])->UE_template[UE_PCCID(mod_id,ue_id)][ue_id].phr_info;
-}
-
-int flexran_get_ue_wcqi (mid_t mod_id, mid_t ue_id) {
-  LTE_eNB_UE_stats     *eNB_UE_stats     = NULL;
-  eNB_UE_stats = mac_xface->get_eNB_UE_stats(mod_id, 0, UE_RNTI(mod_id, ue_id));
-  return eNB_UE_stats->DL_cqi[0];
-
-  //  return ((UE_list_t *)enb_ue[mod_id])->eNB_UE_stats[UE_PCCID(mod_id,ue_id)][ue_id].dl_cqi;
-}
-
-int flexran_get_tx_queue_size(mid_t mod_id, mid_t ue_id, logical_chan_id_t channel_id) {
-  rnti_t rnti = flexran_get_ue_crnti(mod_id,ue_id);
-  uint16_t frame = (uint16_t) flexran_get_current_frame(mod_id);
-  uint16_t subframe = (uint16_t) flexran_get_current_subframe(mod_id);
-  mac_rlc_status_resp_t rlc_status = mac_rlc_status_ind(mod_id,rnti, mod_id,frame,subframe,ENB_FLAG_YES,MBMS_FLAG_NO, channel_id, 0);
-  return rlc_status.bytes_in_buffer;
-}
-
-int flexran_get_hol_delay(mid_t mod_id, mid_t ue_id, logical_chan_id_t channel_id) {
-  rnti_t rnti = flexran_get_ue_crnti(mod_id,ue_id);
-  uint16_t frame = (uint16_t) flexran_get_current_frame(mod_id);
-  uint16_t subframe = (uint16_t) flexran_get_current_subframe(mod_id);
-  mac_rlc_status_resp_t rlc_status = mac_rlc_status_ind(mod_id, rnti, mod_id, frame, subframe, ENB_FLAG_YES, MBMS_FLAG_NO, channel_id, 0);
-  return rlc_status.head_sdu_creation_time;
-}
-
-short flexran_get_TA(mid_t mod_id, mid_t ue_id, int CC_id) {
-  
-  UE_list_t *UE_list=&eNB_mac_inst[mod_id].UE_list;
-  int rnti;
-
-  rnti = flexran_get_ue_crnti(mod_id, ue_id);
-
-  LTE_eNB_UE_stats		*eNB_UE_stats = mac_xface->get_eNB_UE_stats(mod_id, CC_id, rnti);
-  //ue_sched_ctl->ta_timer		      = 20;	// wait 20 subframes before taking TA measurement from PHY                                         
-  switch (PHY_vars_eNB_g[mod_id][CC_id]->frame_parms.N_RB_DL) {
-  case 6:
-    return eNB_UE_stats->timing_advance_update;
-  case 15:
-    return eNB_UE_stats->timing_advance_update/2;
-  case 25:
-    return eNB_UE_stats->timing_advance_update/4;
-  case 50:
-    return eNB_UE_stats->timing_advance_update/8;
-  case 75:
-    return eNB_UE_stats->timing_advance_update/12;
-  case 100:
-    if (PHY_vars_eNB_g[mod_id][CC_id]->frame_parms.threequarter_fs == 0) {
-      return eNB_UE_stats->timing_advance_update/16;
-    } else {
-      return eNB_UE_stats->timing_advance_update/12;
-    }
-  default:
-    return 0;
-  }
-}
-
-void flexran_update_TA(mid_t mod_id, mid_t ue_id, int CC_id) {
-  
-  UE_list_t *UE_list=&eNB_mac_inst[mod_id].UE_list;
-  UE_sched_ctrl *ue_sched_ctl = &UE_list->UE_sched_ctrl[ue_id];
-
-  if (ue_sched_ctl->ta_timer == 0) {
-    
-    // WE SHOULD PROTECT the eNB_UE_stats with a mutex here ...                                                                         
-    //    LTE_eNB_UE_stats		*eNB_UE_stats = mac_xface->get_eNB_UE_stats(mod_id, CC_id, rnti);
-    //ue_sched_ctl->ta_timer		      = 20;	// wait 20 subframes before taking TA measurement from PHY                                         
-    ue_sched_ctl->ta_update = flexran_get_TA(mod_id, ue_id, CC_id);
-
-    // clear the update in case PHY does not have a new measurement after timer expiry                                               
-    //    eNB_UE_stats->timing_advance_update	      = 0;
-  } else {
-    ue_sched_ctl->ta_timer--;
-    ue_sched_ctl->ta_update		      = 0;	// don't trigger a timing advance command      
-  }
-}
-
-int flexran_get_MAC_CE_bitmap_TA(mid_t mod_id, mid_t ue_id,int CC_id) {
-  
-  UE_list_t			*UE_list      = &eNB_mac_inst[mod_id].UE_list;
-
-  rnti_t rnti = flexran_get_ue_crnti(mod_id,ue_id);
-  LTE_eNB_UE_stats *eNB_UE_stats = mac_xface->get_eNB_UE_stats(mod_id,CC_id,rnti);
-  
-  if (eNB_UE_stats == NULL) {
-    return 0;
-  }
-
-  if (flexran_get_TA(mod_id, ue_id, CC_id) != 0) {
-    return PROTOCOL__FLEX_CE_TYPE__FLPCET_TA;
-  } else {
-    return 0;
-  }
-
-}
-
-int flexran_get_active_CC(mid_t mod_id, mid_t ue_id) {
-	return ((UE_list_t *)enb_ue[mod_id])->numactiveCCs[ue_id];
-}
-
-int flexran_get_current_RI(mid_t mod_id, mid_t ue_id, int CC_id) {
-	LTE_eNB_UE_stats	*eNB_UE_stats = NULL;
-
-	rnti_t			 rnti	      = flexran_get_ue_crnti(mod_id,ue_id);
-
-	eNB_UE_stats			      = mac_xface->get_eNB_UE_stats(mod_id,CC_id,rnti);
-	
-	if (eNB_UE_stats == NULL) {
-	  return 0;
-	}
-
-	return eNB_UE_stats[CC_id].rank;
-}
-
-int flexran_get_tpc(mid_t mod_id, mid_t ue_id) {
-	LTE_eNB_UE_stats	*eNB_UE_stats = NULL;
-	int32_t			 normalized_rx_power, target_rx_power;
-	int			 tpc	      = 1;
-
-	int			 pCCid	      = UE_PCCID(mod_id,ue_id);
-	rnti_t			 rnti	      = flexran_get_ue_crnti(mod_id,ue_id);
-
-	eNB_UE_stats = mac_xface->get_eNB_UE_stats(mod_id, pCCid, rnti);
-
-	target_rx_power = mac_xface->get_target_pusch_rx_power(mod_id,pCCid);
-
-	if (eNB_UE_stats == NULL) {
-	  normalized_rx_power = target_rx_power;
-	} else if (eNB_UE_stats->UL_rssi != NULL) {
-	  normalized_rx_power = eNB_UE_stats->UL_rssi[0];
-	} else {
-	  normalized_rx_power = target_rx_power;
-	}
-
-	if (normalized_rx_power>(target_rx_power+1)) {
-		tpc = 0;	//-1
-	} else if (normalized_rx_power<(target_rx_power-1)) {
-		tpc = 2;	//+1
-	} else {
-		tpc = 1;	//0
-	}
-	return tpc;
-}
-
-int flexran_get_harq(const mid_t mod_id, 
-		     const uint8_t CC_id, 
-		     const mid_t ue_id, 
-		     const int frame, 
-		     const uint8_t subframe, 
-		     uint8_t *id, 
-		     uint8_t *round)	{ //flag_id_status = 0 then id, else status
-	/*TODO: Add int TB in function parameters to get the status of the second TB. This can be done to by editing in
-	 * get_ue_active_harq_pid function in line 272 file: phy_procedures_lte_eNB.c to add
-	 * DLSCH_ptr = PHY_vars_eNB_g[Mod_id][CC_id]->dlsch_eNB[(uint32_t)UE_id][1];*/
-
-  uint8_t harq_pid;
-  uint8_t harq_round;
-  
-
-  uint16_t rnti = flexran_get_ue_crnti(mod_id,ue_id);
-
-  mac_xface->get_ue_active_harq_pid(mod_id,CC_id,rnti,frame,subframe,&harq_pid,&harq_round,openair_harq_DL);
-
-  *id = harq_pid;
-  *round = harq_round;
-  /* if (round > 0) { */
-  /*   *status = 1; */
-  /* } else { */
-  /*   *status = 0; */
-  /* } */
-
-  /* return 0; */
-  return *round;
-}
-
-int flexran_get_p0_pucch_dbm(mid_t mod_id, mid_t ue_id, int CC_id) {
-  LTE_eNB_UE_stats *eNB_UE_stats = NULL;
-  uint32_t rnti = flexran_get_ue_crnti(mod_id,ue_id);
-  
-  eNB_UE_stats =  mac_xface->get_eNB_UE_stats(mod_id, CC_id, rnti);
-  
-  if (eNB_UE_stats == NULL) {
-    return -1;
-  }
-  
-  //	if(eNB_UE_stats->Po_PUCCH_update == 1) {
-  return eNB_UE_stats->Po_PUCCH_dBm;
-  //}
-  //else
-  //  return -1;
-}
-
-int flexran_get_p0_nominal_pucch(mid_t mod_id, int CC_id) {
-  int32_t pucch_rx_received = mac_xface->get_target_pucch_rx_power(mod_id, CC_id);
-  return pucch_rx_received;
-}
-
-int flexran_get_p0_pucch_status(mid_t mod_id, mid_t ue_id, int CC_id) {
-  LTE_eNB_UE_stats *eNB_UE_stats = NULL;
-  uint32_t rnti = flexran_get_ue_crnti(mod_id,ue_id);
-  
-  eNB_UE_stats =  mac_xface->get_eNB_UE_stats(mod_id, CC_id, rnti);
-  return eNB_UE_stats->Po_PUCCH_update;
-}
-
-int flexran_update_p0_pucch(mid_t mod_id, mid_t ue_id, int CC_id) {
-  LTE_eNB_UE_stats *eNB_UE_stats = NULL;
-  uint32_t rnti = flexran_get_ue_crnti(mod_id,ue_id);
-  
-  eNB_UE_stats =  mac_xface->get_eNB_UE_stats(mod_id, CC_id, rnti);
-  eNB_UE_stats->Po_PUCCH_update = 0;
-  
-  return 0;
-}
-
-
-/*
- * ************************************
- * Get Messages for eNB Configuration Reply
- * ************************************
- */
-
-int flexran_get_hopping_offset(mid_t mod_id, int CC_id) {
-	LTE_DL_FRAME_PARMS   *frame_parms;
-
-	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
-	return frame_parms->pusch_config_common.pusch_HoppingOffset;
-}
-
-int flexran_get_hopping_mode(mid_t mod_id, int CC_id) {
-	LTE_DL_FRAME_PARMS   *frame_parms;
-
-	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
-	return frame_parms->pusch_config_common.hoppingMode;
-}
-
-int flexran_get_n_SB(mid_t mod_id, int CC_id) {
-	LTE_DL_FRAME_PARMS   *frame_parms;
-
-	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
-	return frame_parms->pusch_config_common.n_SB;
-}
-
-int flexran_get_enable64QAM(mid_t mod_id, int CC_id) {
-	LTE_DL_FRAME_PARMS   *frame_parms;
-
-	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
-	return frame_parms->pusch_config_common.enable64QAM;
-}
-
-int flexran_get_phich_duration(mid_t mod_id, int CC_id) {
-	LTE_DL_FRAME_PARMS   *frame_parms;
-
-	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
-	return frame_parms->phich_config_common.phich_duration;
-}
-
-int flexran_get_phich_resource(mid_t mod_id, int CC_id) {
-	LTE_DL_FRAME_PARMS   *frame_parms;
-
-	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
-	if(frame_parms->phich_config_common.phich_resource == oneSixth)
-		return 0;
-	else if(frame_parms->phich_config_common.phich_resource == half)
-		return 1;
-	else if(frame_parms->phich_config_common.phich_resource == one)
-		return 2;
-	else if(frame_parms->phich_config_common.phich_resource == two)
-		return 3;
-
-	return -1;
-}
-
-int flexran_get_n1pucch_an(mid_t mod_id, int CC_id) {
-	LTE_DL_FRAME_PARMS   *frame_parms;
-
-	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
-	return frame_parms->pucch_config_common.n1PUCCH_AN;
-}
-
-int flexran_get_nRB_CQI(mid_t mod_id, int CC_id) {
-	LTE_DL_FRAME_PARMS   *frame_parms;
-
-	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
-	return frame_parms->pucch_config_common.nRB_CQI;
-}
-
-int flexran_get_deltaPUCCH_Shift(mid_t mod_id, int CC_id) {
-	LTE_DL_FRAME_PARMS   *frame_parms;
-
-	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
-	return frame_parms->pucch_config_common.deltaPUCCH_Shift;
-}
-
-int flexran_get_prach_ConfigIndex(mid_t mod_id, int CC_id) {
-	LTE_DL_FRAME_PARMS   *frame_parms;
-
-	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
-	return frame_parms->prach_config_common.prach_ConfigInfo.prach_ConfigIndex;
-}
-
-int flexran_get_prach_FreqOffset(mid_t mod_id, int CC_id) {
-	LTE_DL_FRAME_PARMS   *frame_parms;
-
-	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
-	return frame_parms->prach_config_common.prach_ConfigInfo.prach_FreqOffset;
-}
-
-int flexran_get_maxHARQ_Msg3Tx(mid_t mod_id, int CC_id) {
-	LTE_DL_FRAME_PARMS   *frame_parms;
-
-	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
-	return frame_parms->maxHARQ_Msg3Tx;
-}
-
-int flexran_get_ul_cyclic_prefix_length(mid_t mod_id, int CC_id) {
-	LTE_DL_FRAME_PARMS   *frame_parms;
-
-	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
-	return frame_parms->Ncp_UL;
-}
-
-int flexran_get_dl_cyclic_prefix_length(mid_t mod_id, int CC_id) {
-	LTE_DL_FRAME_PARMS   *frame_parms;
-
-	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
-	return frame_parms->Ncp;
-}
-
-int flexran_get_cell_id(mid_t mod_id, int CC_id) {
-	LTE_DL_FRAME_PARMS   *frame_parms;
-
-	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
-	return frame_parms->Nid_cell;
-}
-
-int flexran_get_srs_BandwidthConfig(mid_t mod_id, int CC_id) {
-	LTE_DL_FRAME_PARMS   *frame_parms;
-
-	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
-	return frame_parms->soundingrs_ul_config_common.srs_BandwidthConfig;
-}
-
-int flexran_get_srs_SubframeConfig(mid_t mod_id, int CC_id) {
-	LTE_DL_FRAME_PARMS   *frame_parms;
-
-	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
-	return frame_parms->soundingrs_ul_config_common.srs_SubframeConfig;
-}
-
-int flexran_get_srs_MaxUpPts(mid_t mod_id, int CC_id) {
-	LTE_DL_FRAME_PARMS   *frame_parms;
-
-	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
-	return frame_parms->soundingrs_ul_config_common.srs_MaxUpPts;
-}
-
-int flexran_get_N_RB_DL(mid_t mod_id, int CC_id) {
-	LTE_DL_FRAME_PARMS   *frame_parms;
-
-	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
-	return frame_parms->N_RB_DL;
-}
-
-int flexran_get_N_RB_UL(mid_t mod_id, int CC_id) {
-	LTE_DL_FRAME_PARMS   *frame_parms;
-
-	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
-	return frame_parms->N_RB_UL;
-}
-
-int flexran_get_N_RBG(mid_t mod_id, int CC_id) {
-  	LTE_DL_FRAME_PARMS   *frame_parms;
-
-	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
-	return frame_parms->N_RBG;
-}
-
-int flexran_get_subframe_assignment(mid_t mod_id, int CC_id) {
-	LTE_DL_FRAME_PARMS   *frame_parms;
-
-	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
-	return frame_parms->tdd_config;
-}
-
-int flexran_get_special_subframe_assignment(mid_t mod_id, int CC_id) {
-	LTE_DL_FRAME_PARMS   *frame_parms;
-
-	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
-	return frame_parms->tdd_config_S;
-}
-
-int flexran_get_ra_ResponseWindowSize(mid_t mod_id, int CC_id) {
-  return enb_config_get()->properties[mod_id]->rach_raResponseWindowSize[CC_id];
-}
-
-int flexran_get_mac_ContentionResolutionTimer(mid_t mod_id, int CC_id) {
-  return enb_config_get()->properties[mod_id]->rach_macContentionResolutionTimer[CC_id];
-}
-
-int flexran_get_duplex_mode(mid_t mod_id, int CC_id) {
-	LTE_DL_FRAME_PARMS   *frame_parms;
-
-	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
-	if(frame_parms->frame_type == TDD)
-		return PROTOCOL__FLEX_DUPLEX_MODE__FLDM_TDD;
-	else if (frame_parms->frame_type == FDD)
-		return PROTOCOL__FLEX_DUPLEX_MODE__FLDM_FDD;
-
-	return -1;
-}
-
-long flexran_get_si_window_length(mid_t mod_id, int CC_id) {
-	return  ((eNB_RRC_INST *)enb_rrc[mod_id])->carrier[CC_id].sib1->si_WindowLength;
-}
-
-int flexran_get_sib1_length(mid_t mod_id, int CC_id) {
-	return  ((eNB_RRC_INST *)enb_rrc[mod_id])->carrier[CC_id].sizeof_SIB1;
-}
-
-int flexran_get_num_pdcch_symb(mid_t mod_id, int CC_id) {
-  /* TODO: This should return the number of PDCCH symbols initially used by the cell CC_id */
-  return 0;
-  //(PHY_vars_UE_g[mod_id][CC_id]->lte_ue_pdcch_vars[mod_id]->num_pdcch_symbols);
-}
-
-
-
-/*
- * ************************************
- * Get Messages for UE Configuration Reply
- * ************************************
- */
-
-
-int flexran_get_time_alignment_timer(mid_t mod_id, mid_t ue_id) {
-  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
-  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
-  
-  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
-  if(ue_context_p != NULL) {
-    if(ue_context_p->ue_context.mac_MainConfig != NULL) {
-      return ue_context_p->ue_context.mac_MainConfig->timeAlignmentTimerDedicated;
-    } else {
-      return -1;
-    }
-  } else {
-    return -1;
-  }
-}
-
-int flexran_get_meas_gap_config(mid_t mod_id, mid_t ue_id) {
-  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
-  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
-
-  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
-  if(ue_context_p != NULL) {
-    if(ue_context_p->ue_context.measGapConfig != NULL) {
-      if(ue_context_p->ue_context.measGapConfig->present == MeasGapConfig_PR_setup) {
-	if (ue_context_p->ue_context.measGapConfig->choice.setup.gapOffset.present == MeasGapConfig__setup__gapOffset_PR_gp0) {
-	  return PROTOCOL__FLEX_MEAS_GAP_CONFIG_PATTERN__FLMGCP_GP1;
-	} else if (ue_context_p->ue_context.measGapConfig->choice.setup.gapOffset.present == MeasGapConfig__setup__gapOffset_PR_gp1) {
-	  return PROTOCOL__FLEX_MEAS_GAP_CONFIG_PATTERN__FLMGCP_GP2;
-	} else {
-	  return PROTOCOL__FLEX_MEAS_GAP_CONFIG_PATTERN__FLMGCP_OFF;
-	}
-      }
-    }
-  }
-  return -1;
-}
-
-
-int flexran_get_meas_gap_config_offset(mid_t mod_id, mid_t ue_id) {
-  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
-  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
-  
-  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
-  
-  if(ue_context_p != NULL) {
-    if(ue_context_p->ue_context.measGapConfig != NULL){
-      if(ue_context_p->ue_context.measGapConfig->present == MeasGapConfig_PR_setup) {
-	if (ue_context_p->ue_context.measGapConfig->choice.setup.gapOffset.present == MeasGapConfig__setup__gapOffset_PR_gp0) {
-	  return ue_context_p->ue_context.measGapConfig->choice.setup.gapOffset.choice.gp0;
-	} else if (ue_context_p->ue_context.measGapConfig->choice.setup.gapOffset.present == MeasGapConfig__setup__gapOffset_PR_gp1) {
-	  return ue_context_p->ue_context.measGapConfig->choice.setup.gapOffset.choice.gp0;
-	} 
-      }
-    }
-  }
-  return -1;
-}
-
-int flexran_get_ue_aggregated_max_bitrate_dl (mid_t mod_id, mid_t ue_id) {
-	return ((UE_list_t *)enb_ue[mod_id])->UE_sched_ctrl[ue_id].ue_AggregatedMaximumBitrateDL;
-}
-
-int flexran_get_ue_aggregated_max_bitrate_ul (mid_t mod_id, mid_t ue_id) {
-	return ((UE_list_t *)enb_ue[mod_id])->UE_sched_ctrl[ue_id].ue_AggregatedMaximumBitrateUL;
-}
-
-int flexran_get_half_duplex(mid_t ue_id) {
-  // TODO
-	//int halfduplex = 0;
-	//int bands_to_scan = ((UE_RRC_INST *)enb_ue_rrc[ue_id])->UECap->UE_EUTRA_Capability->rf_Parameters.supportedBandListEUTRA.list.count;
-	//for (int i =0; i < bands_to_scan; i++){
-		//if(((UE_RRC_INST *)enb_ue_rrc[ue_id])->UECap->UE_EUTRA_Capability->rf_Parameters.supportedBandListEUTRA.list.array[i]->halfDuplex > 0)
-		//	halfduplex = 1;
-	//}
-	//return halfduplex;
-  return 0;
-}
-
-int flexran_get_intra_sf_hopping(mid_t ue_id) {
-	//TODO:Get proper value
-	//temp = (((UE_RRC_INST *)enb_ue_rrc[ue_id])->UECap->UE_EUTRA_Capability->featureGroupIndicators->buf);
-	//return (0 & ( 1 << (31)));
-  return 0;
-}
-
-int flexran_get_type2_sb_1(mid_t ue_id) {
-	//TODO:Get proper value
-	//uint8_t temp = 0;
-	//temp = (((UE_RRC_INST *)enb_ue_rrc[ue_id])->UECap->UE_EUTRA_Capability->featureGroupIndicators->buf);
-	//return (temp & ( 1 << (11)));
-  return 0;
-}
-
-int flexran_get_ue_category(mid_t ue_id) {
-	//TODO:Get proper value
-	//return (((UE_RRC_INST *)enb_ue_rrc[ue_id])->UECap->UE_EUTRA_Capability->ue_Category);
-  return 0;
-}
-
-int flexran_get_res_alloc_type1(mid_t ue_id) {
-	//TODO:Get proper value
-	//uint8_t temp = 0;
-	//temp = (((UE_RRC_INST *)enb_ue_rrc[ue_id])->UECap->UE_EUTRA_Capability->featureGroupIndicators->buf);
-	//return (temp & ( 1 << (30)));
-  return 0;
-}
-
-int flexran_get_ue_transmission_mode(mid_t mod_id, mid_t ue_id) {
-  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
-  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
-  
-  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
-  
-  if(ue_context_p != NULL) {
-    if(ue_context_p->ue_context.physicalConfigDedicated != NULL){
-      return ue_context_p->ue_context.physicalConfigDedicated->antennaInfo->choice.explicitValue.transmissionMode;
-    } else {
-      return -1;
-    }
-  } else {
-    return -1;
-  }
-}
-
-int flexran_get_tti_bundling(mid_t mod_id, mid_t ue_id) {
-  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
-  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
-  
-  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
-  if(ue_context_p != NULL) {
-    if(ue_context_p->ue_context.mac_MainConfig != NULL){
-      return ue_context_p->ue_context.mac_MainConfig->ul_SCH_Config->ttiBundling;
-    } else {
-      return -1;
-    }
-  }
-  else {
-    return -1;
-  }
-}
-
-int flexran_get_maxHARQ_TX(mid_t mod_id, mid_t ue_id) {
-  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
-  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
-  
-  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
-  if(ue_context_p != NULL) {
-    if(ue_context_p->ue_context.mac_MainConfig != NULL){
-      return *ue_context_p->ue_context.mac_MainConfig->ul_SCH_Config->maxHARQ_Tx;
-    }
-  }
-  return -1;
-}
-
-int flexran_get_beta_offset_ack_index(mid_t mod_id, mid_t ue_id) {
-  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
-  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
-  
-  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
-  if(ue_context_p != NULL) {
-    if(ue_context_p->ue_context.physicalConfigDedicated != NULL){
-      return ue_context_p->ue_context.physicalConfigDedicated->pusch_ConfigDedicated->betaOffset_ACK_Index;
-    } else {
-      return -1;
-    } 
-  } else {
-    return -1;
-  }
-}
-
-int flexran_get_beta_offset_ri_index(mid_t mod_id, mid_t ue_id) {
-  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
-  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
-  
-  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
-  if(ue_context_p != NULL) {
-    if(ue_context_p->ue_context.physicalConfigDedicated != NULL){
-      return ue_context_p->ue_context.physicalConfigDedicated->pusch_ConfigDedicated->betaOffset_RI_Index;
-    } else {
-      return -1;
-    }
-  } else {
-    return -1;
-  }
-}
-
-int flexran_get_beta_offset_cqi_index(mid_t mod_id, mid_t ue_id) {
-  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
-  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
-  
-  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
-  if(ue_context_p != NULL) {
-    if(ue_context_p->ue_context.physicalConfigDedicated != NULL){
-      return ue_context_p->ue_context.physicalConfigDedicated->pusch_ConfigDedicated->betaOffset_CQI_Index;
-    } else {
-      return -1;
-    }
-  }
-  else {
-    return -1;
-  }
-}
-
-int flexran_get_simultaneous_ack_nack_cqi(mid_t mod_id, mid_t ue_id) {
-  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
-  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
-  
-  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
-  if(ue_context_p != NULL) {
-    if(ue_context_p->ue_context.physicalConfigDedicated != NULL){
-      if (ue_context_p->ue_context.physicalConfigDedicated->cqi_ReportConfig->cqi_ReportPeriodic != NULL) {
-	return ue_context_p->ue_context.physicalConfigDedicated->cqi_ReportConfig->cqi_ReportPeriodic->choice.setup.simultaneousAckNackAndCQI;
-      }
-    }
-  }
-  return -1;
-}
-
-int flexran_get_ack_nack_simultaneous_trans(mid_t mod_id,mid_t ue_id) {
-	return (&eNB_rrc_inst[mod_id])->carrier[0].sib2->radioResourceConfigCommon.soundingRS_UL_ConfigCommon.choice.setup.ackNackSRS_SimultaneousTransmission;
-}
-
-int flexran_get_aperiodic_cqi_rep_mode(mid_t mod_id,mid_t ue_id) {
-  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
-  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
-  
-  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
-  
-  if(ue_context_p != NULL) {
-    if(ue_context_p->ue_context.physicalConfigDedicated != NULL){
-      return *ue_context_p->ue_context.physicalConfigDedicated->cqi_ReportConfig->cqi_ReportModeAperiodic;
-    }
-  }
-  return -1;
-}
-
-int flexran_get_tdd_ack_nack_feedback(mid_t mod_id, mid_t ue_id) {
-  // TODO: This needs fixing
-  return -1;
-
-  /* struct rrc_eNB_ue_context_s* ue_context_p = NULL; */
-  /* uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id); */
-  
-  /* ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP); */
-  
-  /* if(ue_context_p != NULL) { */
-  /*   if(ue_context_p->ue_context.physicalConfigDedicated != NULL){ */
-  /*     return ue_context_p->ue_context.physicalConfigDedicated->pucch_ConfigDedicated->tdd_AckNackFeedbackMode; */
-  /*   } else { */
-  /*     return -1; */
-  /*   } */
-  /* } else { */
-  /*   return -1; */
-  /* } */
-}
-
-int flexran_get_ack_nack_repetition_factor(mid_t mod_id, mid_t ue_id) {
-  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
-  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
-  
-  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
-  if(ue_context_p != NULL) {
-    if(ue_context_p->ue_context.physicalConfigDedicated != NULL){
-      return ue_context_p->ue_context.physicalConfigDedicated->pucch_ConfigDedicated->ackNackRepetition.choice.setup.repetitionFactor;
-    } else {
-      return -1;
-    }
-  } else {
-    return -1;
-  }
-}
-
-int flexran_get_extended_bsr_size(mid_t mod_id, mid_t ue_id) {
-  //TODO: need to double check
-  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
-  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
-
-  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
-  if(ue_context_p != NULL) {
-    if(ue_context_p->ue_context.mac_MainConfig != NULL){
-      if(ue_context_p->ue_context.mac_MainConfig->ext2 != NULL){
-	long val = (*(ue_context_p->ue_context.mac_MainConfig->ext2->mac_MainConfig_v1020->extendedBSR_Sizes_r10));
-	if (val > 0) {
-	  return 1;
-	}
-      }
-    }
-  }
-  return -1;
-}
-
-int flexran_get_ue_transmission_antenna(mid_t mod_id, mid_t ue_id) {
-  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
-  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
-  
-  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
-  
-  if(ue_context_p != NULL) {
-    if(ue_context_p->ue_context.physicalConfigDedicated != NULL){
-      if(ue_context_p->ue_context.physicalConfigDedicated->antennaInfo->choice.explicitValue.ue_TransmitAntennaSelection.choice.setup == AntennaInfoDedicated__ue_TransmitAntennaSelection__setup_closedLoop) {
-	return 2;
-      } else if(ue_context_p->ue_context.physicalConfigDedicated->antennaInfo->choice.explicitValue.ue_TransmitAntennaSelection.choice.setup == AntennaInfoDedicated__ue_TransmitAntennaSelection__setup_openLoop) {
-	return 1;
-      } else {
-	return 0;
-      }
-    } else {
-      return -1;
-    }
-  } else {
-    return -1;
-  }
-}
-
-int flexran_get_lcg(mid_t ue_id, mid_t lc_id) {
-  if (UE_mac_inst == NULL) {
-    return -1;
-  }
-  if(UE_mac_inst[ue_id].logicalChannelConfig[lc_id] != NULL) {
-    return *UE_mac_inst[ue_id].logicalChannelConfig[lc_id]->ul_SpecificParameters->logicalChannelGroup;
-  } else {
-    return -1;
-  }
-}
-
-int flexran_get_direction(mid_t ue_id, mid_t lc_id) {
-	/*TODO: fill with the value for the rest of LCID*/
-  if(lc_id == DCCH || lc_id == DCCH1) {
-    return 2;
-  } else if(lc_id == DTCH) {
-    return 1;
-  } else {
-    return -1;
-  }
-}
-
-int flexran_agent_ue_state_change(mid_t mod_id, uint32_t rnti, uint8_t state_change) {
-  int size;
-  Protocol__FlexranMessage *msg;
-  Protocol__FlexHeader *header;
-  void *data;
-  int priority = 0;
-
-  int xid = 0;
-
-  if (flexran_create_header(xid, PROTOCOL__FLEX_TYPE__FLPT_UE_STATE_CHANGE, &header) != 0)
-    goto error;
-
-  Protocol__FlexUeStateChange *ue_state_change_msg;
-  ue_state_change_msg = malloc(sizeof(Protocol__FlexUeStateChange));
-  if(ue_state_change_msg == NULL) {
-    goto error;
-  }
-  protocol__flex_ue_state_change__init(ue_state_change_msg);
-  ue_state_change_msg->has_type = 1;
-  ue_state_change_msg->type = state_change;
-
-  Protocol__FlexUeConfig *config;
-  config = malloc(sizeof(Protocol__FlexUeConfig));
-  if (config == NULL) {
-    goto error;
-  }
-  protocol__flex_ue_config__init(config);
-  if (state_change == PROTOCOL__FLEX_UE_STATE_CHANGE_TYPE__FLUESC_DEACTIVATED) {
-    // Simply set the rnti of the UE
-    config->has_rnti = 1;
-    config->rnti = rnti;
-  } else if (state_change == PROTOCOL__FLEX_UE_STATE_CHANGE_TYPE__FLUESC_UPDATED
-	     || state_change == PROTOCOL__FLEX_UE_STATE_CHANGE_TYPE__FLUESC_ACTIVATED) {
-	  	  int i = find_UE_id(mod_id, rnti);
-		  config->has_rnti = 1;
-		  config->rnti = rnti;
-	  	  if(flexran_get_time_alignment_timer(mod_id,i) != -1) {
-	  		  config->time_alignment_timer = flexran_get_time_alignment_timer(mod_id,i);
-	  		  config->has_time_alignment_timer = 1;
-	  	  }
-	  	  if(flexran_get_meas_gap_config(mod_id,i) != -1){
-	  		  config->meas_gap_config_pattern = flexran_get_meas_gap_config(mod_id,i);
-	  	  	  config->has_meas_gap_config_pattern = 1;
-	  	  }
-	  	  if(config->has_meas_gap_config_pattern == 1 &&
-		     config->meas_gap_config_pattern != PROTOCOL__FLEX_MEAS_GAP_CONFIG_PATTERN__FLMGCP_OFF) {
-		    config->meas_gap_config_sf_offset = flexran_get_meas_gap_config_offset(mod_id,i);
-		    config->has_meas_gap_config_sf_offset = 1;
-	  	  }
-	  	  //TODO: Set the SPS configuration (Optional)
-	  	  //Not supported for now, so we do not set it
-
-	  	  //TODO: Set the SR configuration (Optional)
-	  	  //We do not set it for now
-
-	  	  //TODO: Set the CQI configuration (Optional)
-	  	  //We do not set it for now
-		  
-		  if(flexran_get_ue_transmission_mode(mod_id,i) != -1) {
-	  		  config->transmission_mode = flexran_get_ue_transmission_mode(mod_id,i);
-	  		  config->has_transmission_mode = 1;
-	  	  }
-
-		  config->ue_aggregated_max_bitrate_ul = flexran_get_ue_aggregated_max_bitrate_ul(mod_id,i);
-	  	  config->has_ue_aggregated_max_bitrate_ul = 1;
-
-		  config->ue_aggregated_max_bitrate_dl = flexran_get_ue_aggregated_max_bitrate_dl(mod_id,i);
-	  	  config->has_ue_aggregated_max_bitrate_dl = 1;
-
-	  	  //TODO: Set the UE capabilities
-	  	  Protocol__FlexUeCapabilities *c_capabilities;
-	  	  c_capabilities = malloc(sizeof(Protocol__FlexUeCapabilities));
-	  	  protocol__flex_ue_capabilities__init(c_capabilities);
-	  	  //TODO: Set half duplex (FDD operation)
-	  	  c_capabilities->has_half_duplex = 0;
-	  	  c_capabilities->half_duplex = 1;//flexran_get_half_duplex(i);
-	  	  //TODO: Set intra-frame hopping flag
-	  	  c_capabilities->has_intra_sf_hopping = 0;
-	  	  c_capabilities->intra_sf_hopping = 1;//flexran_get_intra_sf_hopping(i);
-	  	  //TODO: Set support for type 2 hopping with n_sb > 1
-	  	  c_capabilities->has_type2_sb_1 = 0;
-	  	  c_capabilities->type2_sb_1 = 1;//flexran_get_type2_sb_1(i);
-	  	  //TODO: Set ue category
-	  	  c_capabilities->has_ue_category = 0;
-	  	  c_capabilities->ue_category = 1;//flexran_get_ue_category(i);
-	  	  //TODO: Set UE support for resource allocation type 1
-	  	  c_capabilities->has_res_alloc_type1 = 0;
-	  	  c_capabilities->res_alloc_type1 = 1;//flexran_get_res_alloc_type1(i);
-	  	  //Set the capabilites to the message
-	  	  config->capabilities = c_capabilities;
-		  
-	  	  if(flexran_get_ue_transmission_antenna(mod_id,i) != -1) {
-		    config->has_ue_transmission_antenna = 1;
-		    config->ue_transmission_antenna = flexran_get_ue_transmission_antenna(mod_id,i);
-	  	  }
-
-	  	  if(flexran_get_tti_bundling(mod_id,i) != -1) {
-		    config->has_tti_bundling = 1;
-		    config->tti_bundling = flexran_get_tti_bundling(mod_id,i);
-	  	  }
-
-	  	  if(flexran_get_maxHARQ_TX(mod_id,i) != -1){
-		    config->has_max_harq_tx = 1;
-		    config->max_harq_tx = flexran_get_maxHARQ_TX(mod_id,i);
-	  	  }
-
-	  	  if(flexran_get_beta_offset_ack_index(mod_id,i) != -1) {
-		    config->has_beta_offset_ack_index = 1;
-		    config->beta_offset_ack_index = flexran_get_beta_offset_ack_index(mod_id,i);
-	  	  }
-
-	  	  if(flexran_get_beta_offset_ri_index(mod_id,i) != -1) {
-		    config->has_beta_offset_ri_index = 1;
-		    config->beta_offset_ri_index = flexran_get_beta_offset_ri_index(mod_id,i);
-	  	  }
-
-	  	  if(flexran_get_beta_offset_cqi_index(mod_id,i) != -1) {
-		    config->has_beta_offset_cqi_index = 1;
-		    config->beta_offset_cqi_index = flexran_get_beta_offset_cqi_index(mod_id,i);
-	  	  }
-
-	  	  if(flexran_get_ack_nack_simultaneous_trans(mod_id,i) != -1) {
-		    config->has_ack_nack_simultaneous_trans = 1;
-		    config->ack_nack_simultaneous_trans = flexran_get_ack_nack_simultaneous_trans(mod_id,i);
-	  	  }
-
-	  	  if(flexran_get_simultaneous_ack_nack_cqi(mod_id,i) != -1) {
-		    config->has_simultaneous_ack_nack_cqi = 1;
-		    config->simultaneous_ack_nack_cqi = flexran_get_simultaneous_ack_nack_cqi(mod_id,i);
-	  	  }
-
-	  	  if(flexran_get_aperiodic_cqi_rep_mode(mod_id,i) != -1) {
-		    config->has_aperiodic_cqi_rep_mode = 1;
-		    int mode = flexran_get_aperiodic_cqi_rep_mode(mod_id,i);
-		    if (mode > 4) {
-		      config->aperiodic_cqi_rep_mode = PROTOCOL__FLEX_APERIODIC_CQI_REPORT_MODE__FLACRM_NONE;
-		    } else {
-		      config->aperiodic_cqi_rep_mode = mode;
-		    }
-	  	  }
-
-	  	  if(flexran_get_tdd_ack_nack_feedback(mod_id, i) != -1) {
-		    config->has_tdd_ack_nack_feedback = 1;
-		    config->tdd_ack_nack_feedback = flexran_get_tdd_ack_nack_feedback(mod_id,i);
-	  	  }
-
-	  	  if(flexran_get_ack_nack_repetition_factor(mod_id, i) != -1) {
-		    config->has_ack_nack_repetition_factor = 1;
-		    config->ack_nack_repetition_factor = flexran_get_ack_nack_repetition_factor(mod_id,i);
-	  	  }
-
-	  	  if(flexran_get_extended_bsr_size(mod_id, i) != -1) {
-		    config->has_extended_bsr_size = 1;
-		    config->extended_bsr_size = flexran_get_extended_bsr_size(mod_id,i);
-	  	  }
-
-		  config->has_pcell_carrier_index = 1;
-		  config->pcell_carrier_index = UE_PCCID(mod_id, i);
-	  	  //TODO: Set carrier aggregation support (boolean)
-	  	  config->has_ca_support = 0;
-	  	  config->ca_support = 0;
-	  	  if(config->has_ca_support){
-		    //TODO: Set cross carrier scheduling support (boolean)
-		    config->has_cross_carrier_sched_support = 1;
-		    config->cross_carrier_sched_support = 0;
-		    //TODO: Set secondary cells configuration
-		    // We do not set it for now. No carrier aggregation support
-		    
-		    //TODO: Set deactivation timer for secondary cell
-		    config->has_scell_deactivation_timer = 0;
-		    config->scell_deactivation_timer = 0;
-	  	  }
-  } else if (state_change == PROTOCOL__FLEX_UE_STATE_CHANGE_TYPE__FLUESC_MOVED) {
-    // TODO: Not supported for now. Leave blank
-  }
-
-  ue_state_change_msg->config = config;
-  msg = malloc(sizeof(Protocol__FlexranMessage));
-  if (msg == NULL) {
-    goto error;
-  }
-  protocol__flexran_message__init(msg);
-  msg->msg_case = PROTOCOL__FLEXRAN_MESSAGE__MSG_UE_STATE_CHANGE_MSG;
-  msg->msg_dir = PROTOCOL__FLEXRAN_DIRECTION__INITIATING_MESSAGE;
-  msg->ue_state_change_msg = ue_state_change_msg;
-
-  data = flexran_agent_pack_message(msg, &size);
-  /*Send sr info using the MAC channel of the eNB*/
-  if (flexran_agent_msg_send(mod_id, FLEXRAN_AGENT_DEFAULT, data, size, priority)) {
-    goto error;
-  }
-
-  LOG_D(FLEXRAN_AGENT,"sent message with size %d\n", size);
-  return 0;
- error:
-  LOG_D(FLEXRAN_AGENT, "Could not send UE state message\n");
-  return -1;
-}
-
-
-
 int flexran_agent_lc_config_reply(mid_t mod_id, const void *params, Protocol__FlexranMessage **msg) {
 
   xid_t xid;
@@ -2105,6 +1010,22 @@ int flexran_agent_enb_config_reply(mid_t mod_id, const void *params, Protocol__F
       cell_conf[i]->srs_mac_up_pts = flexran_get_srs_MaxUpPts(enb_id,i);
       cell_conf[i]->has_srs_mac_up_pts = 1;
 
+      cell_conf[i]->dl_freq = flexran_agent_get_operating_dl_freq (enb_id,i);
+      cell_conf[i]->has_dl_freq = 1;
+
+      cell_conf[i]->ul_freq = flexran_agent_get_operating_ul_freq (enb_id, i);
+      cell_conf[i]->has_ul_freq = 1;
+
+      cell_conf[i]->eutra_band = flexran_agent_get_operating_eutra_band (enb_id,i);
+      cell_conf[i]->has_eutra_band = 1;
+
+      cell_conf[i]->dl_pdsch_power = flexran_agent_get_operating_pdsch_refpower(enb_id, i);
+      cell_conf[i]->has_dl_pdsch_power = 1;
+
+      cell_conf[i]->ul_pusch_power = flexran_agent_get_operating_pusch_p0 (enb_id,i);
+      cell_conf[i]->has_ul_pusch_power = 1;
+ 
+
       if (flexran_get_enable64QAM(enb_id,i) == 0) {
 	cell_conf[i]->enable_64qam = PROTOCOL__FLEX_QAM__FLEQ_MOD_16QAM;
       } else if(flexran_get_enable64QAM(enb_id,i) == 1) {
@@ -2140,191 +1061,39 @@ int flexran_agent_enb_config_reply(mid_t mod_id, const void *params, Protocol__F
 }
 
 
+int flexran_agent_rrc_measurement(mid_t mod_id, const void *params, Protocol__FlexranMessage **msg) {
 
-/*
- * timer primitives
- */
-
-//struct flexran_agent_map agent_map;
-flexran_agent_timer_instance_t timer_instance;
-int agent_timer_init = 0;
-err_code_t flexran_agent_init_timer(void){
-  
-  LOG_I(FLEXRAN_AGENT, "init RB tree\n");
-  if (!agent_timer_init) {
-    RB_INIT(&timer_instance.flexran_agent_head);
-    agent_timer_init = 1;
-  }
- 
- return PROTOCOL__FLEXRAN_ERR__NO_ERR;
-}
+  protocol_ctxt_t  ctxt;
 
-RB_GENERATE(flexran_agent_map, flexran_agent_timer_element_s, entry, flexran_agent_compare_timer);
+  Protocol__FlexranMessage *input = (Protocol__FlexranMessage *)params;
+  Protocol__FlexRrcTriggering *triggering = input->rrc_triggering;
 
-/* The timer_id might not be the best choice for the comparison */
-int flexran_agent_compare_timer(struct flexran_agent_timer_element_s *a, struct flexran_agent_timer_element_s *b){
+  agent_reconf_rrc *reconf_param = malloc(sizeof(agent_reconf_rrc));
+  
 
-  if (a->timer_id < b->timer_id) return -1;
-  if (a->timer_id > b->timer_id) return 1;
+  reconf_param->trigger_policy = triggering->rrc_trigger;
 
-  // equal timers
-  return 0;
-}
+  struct rrc_eNB_ue_context_s   *ue_context_p = NULL;
 
-err_code_t flexran_agent_create_timer(uint32_t interval_sec,
-				      uint32_t interval_usec,
-				      agent_id_t     agent_id,
-				      instance_t     instance,
-				      uint32_t timer_type,
-				      xid_t xid,
-				      flexran_agent_timer_callback_t cb,
-				      void*    timer_args,
-				      long *timer_id){
-  
-  struct flexran_agent_timer_element_s *e = calloc(1, sizeof(*e));
-  DevAssert(e != NULL);
-  
-//uint32_t timer_id;
-  int ret=-1;
-  
-  if ((interval_sec == 0) && (interval_usec == 0 ))
-    return TIMER_NULL;
-  
-  if (timer_type >= FLEXRAN_AGENT_TIMER_TYPE_MAX)
-    return TIMER_TYPE_INVALIDE;
-  
-  if (timer_type  ==   FLEXRAN_AGENT_TIMER_TYPE_ONESHOT){ 
-    ret = timer_setup(interval_sec, 
-		      interval_usec, 
-		      TASK_FLEXRAN_AGENT, 
-		      instance, 
-		      TIMER_ONE_SHOT,
-		      timer_args,
-		      timer_id);
-    
-    e->type = TIMER_ONE_SHOT;
-  }
-  else if (timer_type  ==   FLEXRAN_AGENT_TIMER_TYPE_PERIODIC ){
-    ret = timer_setup(interval_sec, 
-		      interval_usec, 
-		      TASK_FLEXRAN_AGENT, 
-		      instance, 
-		      TIMER_PERIODIC,
-		      timer_args,
-		      timer_id);
-    
-    e->type = TIMER_PERIODIC;
-  }
-  
-  if (ret < 0 ) {
-    return TIMER_SETUP_FAILED; 
-  }
+  RB_FOREACH(ue_context_p, rrc_ue_tree_s, &(eNB_rrc_inst[mod_id].rrc_ue_head)){
 
-  e->agent_id = agent_id;
-  e->instance = instance;
-  e->state = FLEXRAN_AGENT_TIMER_STATE_ACTIVE;
-  e->timer_id = *timer_id;
-  e->xid = xid;
-  e->timer_args = timer_args; 
-  e->cb = cb;
-  /*element should be a real pointer*/
-  RB_INSERT(flexran_agent_map, &timer_instance.flexran_agent_head, e); 
-  
-  LOG_I(FLEXRAN_AGENT,"Created a new timer with id 0x%lx for agent %d, instance %d \n",
-	e->timer_id, e->agent_id, e->instance);
-  
-  return 0; 
-}
 
-err_code_t flexran_agent_destroy_timer(long timer_id){
+  PROTOCOL_CTXT_SET_BY_MODULE_ID(&ctxt, mod_id, ENB_FLAG_YES, ue_context_p->ue_context.rnti, flexran_get_current_frame(mod_id), flexran_get_current_subframe (mod_id), mod_id);
   
-  struct flexran_agent_timer_element_s *e = get_timer_entry(timer_id);
+  flexran_rrc_eNB_generate_defaultRRCConnectionReconfiguration(&ctxt, ue_context_p, 0, reconf_param);  
 
-  if (e != NULL ) {
-    RB_REMOVE(flexran_agent_map, &timer_instance.flexran_agent_head, e);
-    flexran_agent_destroy_flexran_message(e->timer_args->msg);
-    free(e);
   }
   
-  if (timer_remove(timer_id) < 0 ) 
-    goto error;
   
+  *msg = NULL;
   return 0;
-
- error:
-  LOG_E(FLEXRAN_AGENT, "timer can't be removed\n");
-  return TIMER_REMOVED_FAILED ;
-}
-
-err_code_t flexran_agent_destroy_timer_by_task_id(xid_t xid) {
-  struct flexran_agent_timer_element_s *e = NULL;
-  long timer_id;
-  RB_FOREACH(e, flexran_agent_map, &timer_instance.flexran_agent_head) {
-    if (e->xid == xid) {
-      timer_id = e->timer_id;
-      RB_REMOVE(flexran_agent_map, &timer_instance.flexran_agent_head, e);
-      flexran_agent_destroy_flexran_message(e->timer_args->msg);
-      free(e);
-      if (timer_remove(timer_id) < 0 ) { 
-	goto error;
-      }
-    }
-  }
-  return 0;
-
- error:
-  LOG_E(FLEXRAN_AGENT, "timer can't be removed\n");
-  return TIMER_REMOVED_FAILED ;
 }
 
-err_code_t flexran_agent_destroy_timers(void){
-  
-  struct flexran_agent_timer_element_s *e = NULL;
-  
-  RB_FOREACH(e, flexran_agent_map, &timer_instance.flexran_agent_head) {
-    RB_REMOVE(flexran_agent_map, &timer_instance.flexran_agent_head, e);
-    timer_remove(e->timer_id);
-    flexran_agent_destroy_flexran_message(e->timer_args->msg);
-    free(e);
-  }  
 
+int flexran_agent_destroy_rrc_measurement(Protocol__FlexranMessage *msg){
+  // TODO
   return 0;
-
 }
 
-void flexran_agent_sleep_until(struct timespec *ts, int delay) {
-  ts->tv_nsec += delay;
-  if(ts->tv_nsec >= 1000*1000*1000){
-    ts->tv_nsec -= 1000*1000*1000;
-    ts->tv_sec++;
-  }
-  clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ts,  NULL);
-}
-
-
-err_code_t flexran_agent_stop_timer(long timer_id){
-  
-  struct flexran_agent_timer_element_s *e=NULL;
-  struct flexran_agent_timer_element_s search;
-  memset(&search, 0, sizeof(struct flexran_agent_timer_element_s));
-  search.timer_id = timer_id;
 
-  e = RB_FIND(flexran_agent_map, &timer_instance.flexran_agent_head, &search);
 
-  if (e != NULL ) {
-    e->state =  FLEXRAN_AGENT_TIMER_STATE_STOPPED;
-  }
-  
-  timer_remove(timer_id);
-  
-  return 0;
-}
-
-struct flexran_agent_timer_element_s * get_timer_entry(long timer_id) {
-  
-  struct flexran_agent_timer_element_s search;
-  memset(&search, 0, sizeof(struct flexran_agent_timer_element_s));
-  search.timer_id = timer_id;
-
-  return  RB_FIND(flexran_agent_map, &timer_instance.flexran_agent_head, &search); 
-}
diff --git a/openair2/ENB_APP/flexran_agent_common.h b/openair2/ENB_APP/flexran_agent_common.h
index 7ab89acb4b1e4690b6ea6b1d3249427a9ecd853e..242cb55ca86364db4254f250a6a97657ad73e71d 100644
--- a/openair2/ENB_APP/flexran_agent_common.h
+++ b/openair2/ENB_APP/flexran_agent_common.h
@@ -21,8 +21,8 @@
 
 /*! \file flexran_agent_common.h
  * \brief common message primitves and utilities 
- * \author Xenofon Foukas, Mohamed Kassem and Navid Nikaein
- * \date 2016
+ * \author Xenofon Foukas, Mohamed Kassem and Navid Nikaein and shahab SHARIAT BAGHERI
+ * \date 2017
  * \version 0.1
  */
 
@@ -37,7 +37,8 @@
 #include "flexran.pb-c.h"
 #include "stats_messages.pb-c.h"
 #include "stats_common.pb-c.h"
-
+#include "flexran_agent_ran_api.h"
+#include "flexran_agent_net_comm.h"
 #include "flexran_agent_defs.h"
 #include "enb_config.h"
 
@@ -60,6 +61,19 @@ typedef int (*flexran_agent_message_destruction_callback)(
 	Protocol__FlexranMessage *msg
 );
 
+typedef struct {
+ 
+  uint8_t is_initialized;
+  volatile uint8_t cont_update;
+  xid_t xid;
+  Protocol__FlexranMessage *stats_req;
+  Protocol__FlexranMessage *prev_stats_reply;
+
+  pthread_mutex_t *mutex;
+} stats_updates_context_t;
+
+stats_updates_context_t stats_context[NUM_MAX_ENB];
+
 /**********************************
  * FlexRAN protocol messages helper 
  * functions and generic handlers
@@ -116,10 +130,6 @@ int flexran_agent_destroy_ue_config_request(Protocol__FlexranMessage *msg);
 /* TODO: Need to define and implement destructor */
 int flexran_agent_destroy_lc_config_request(Protocol__FlexranMessage *msg);
 
-/* UE state change message constructor and destructor */
-int flexran_agent_ue_state_change(mid_t mod_id, uint32_t rnti, uint8_t state_change);
-int flexran_agent_destroy_ue_state_change(Protocol__FlexranMessage *msg);
-
 /* Control delegation message constructor and destructor */
 int flexran_agent_control_delegation(mid_t mod_id, const void *params, Protocol__FlexranMessage **msg);
 int flexran_agent_destroy_control_delegation(Protocol__FlexranMessage *msg);
@@ -128,6 +138,11 @@ int flexran_agent_destroy_control_delegation(Protocol__FlexranMessage *msg);
 int flexran_agent_reconfiguration(mid_t mod_id, const void *params, Protocol__FlexranMessage **msg);
 int flexran_agent_destroy_agent_reconfiguration(Protocol__FlexranMessage *msg);
 
+/* rrc triggering measurement message constructor and destructor */
+int flexran_agent_rrc_measurement(mid_t mod_id, const void *params, Protocol__FlexranMessage **msg);
+int flexran_agent_destroy_rrc_measurement(Protocol__FlexranMessage *msg);
+
+
 /* FlexRAN protocol message dispatcher function */
 Protocol__FlexranMessage* flexran_agent_handle_message (mid_t mod_id, 
 						    uint8_t *data, 
@@ -136,367 +151,21 @@ Protocol__FlexranMessage* flexran_agent_handle_message (mid_t mod_id,
 /* Function to be used to send a message to a dispatcher once the appropriate event is triggered. */
 Protocol__FlexranMessage *flexran_agent_handle_timed_task(void *args);
 
+/*Top level Statistics hanlder*/
+int flexran_agent_handle_stats(mid_t mod_id, const void *params, Protocol__FlexranMessage **msg);
 
+/* Function to be used to handle reply message . */
+int flexran_agent_stats_reply(mid_t enb_id, xid_t xid, const report_config_t *report_config, Protocol__FlexranMessage **msg);
 
+/* Top level Statistics request protocol message constructor and destructor */
+int flexran_agent_stats_request(mid_t mod_id, xid_t xid, const stats_request_config_t *report_config, Protocol__FlexranMessage **msg);
+int flexran_agent_destroy_stats_request(Protocol__FlexranMessage *msg);
 
-/****************************
- * get generic info from RAN
- ****************************/
-
-void flexran_set_enb_vars(mid_t mod_id, ran_name_t ran);
-
-int flexran_get_current_time_ms (mid_t mod_id, int subframe_flag);
-
-/*Return the current frame number
- *Could be using implementation specific numbering of frames
- */
-unsigned int flexran_get_current_frame(mid_t mod_id);
-
-/*Return the current SFN (0-1023)*/ 
-unsigned int flexran_get_current_system_frame_num(mid_t mod_id);
-
-unsigned int flexran_get_current_subframe(mid_t mod_id);
-
-/*Return the frame and subframe number in compact 16-bit format.
-  Bits 0-3 subframe, rest for frame. Required by FlexRAN protocol*/
-uint16_t flexran_get_sfn_sf (mid_t mod_id);
-
-/* Return a future frame and subframe number that is ahead_of_time
-   subframes later in compact 16-bit format. Bits 0-3 subframe,
-   rest for frame */
-uint16_t flexran_get_future_sfn_sf(mid_t mod_id, int ahead_of_time);
-
-/* Return the number of attached UEs */
-int flexran_get_num_ues(mid_t mod_id);
-
-/* Get the rnti of a UE with id ue_id */
-int flexran_get_ue_crnti (mid_t mod_id, mid_t ue_id);
-
-/* Get the RLC buffer status report of a ue for a designated
-   logical channel id */
-int flexran_get_ue_bsr (mid_t mod_id, mid_t ue_id, lcid_t lcid);
-
-/* Get power headroom of UE with id ue_id */
-int flexran_get_ue_phr (mid_t mod_id, mid_t ue_id);
-
-/* Get the UE wideband CQI */
-int flexran_get_ue_wcqi (mid_t mod_id, mid_t ue_id);
-
-/* Get the transmission queue size for a UE with a channel_id logical channel id */
-int flexran_get_tx_queue_size(mid_t mod_id, mid_t ue_id, logical_chan_id_t channel_id);
-
-/* Get the head of line delay for a UE with a channel_id logical channel id */
-int flexran_get_hol_delay(mid_t mod_id, mid_t ue_id, logical_chan_id_t channel_id);
-
-/* Check the status of the timing advance for a UE */
-short flexran_get_TA(mid_t mod_id, mid_t ue_id, int CC_id);
-
-/* Update the timing advance status (find out whether a timing advance command is required) */
-void flexran_update_TA(mid_t mod_id, mid_t ue_id, int CC_id);
-
-/* Return timing advance MAC control element for a designated cell and UE */
-int flexran_get_MAC_CE_bitmap_TA(mid_t mod_id, mid_t ue_id, int CC_id);
-
-/* Get the number of active component carriers for a specific UE */
-int flexran_get_active_CC(mid_t mod_id, mid_t ue_id);
-
-/* Get the rank indicator for a designated cell and UE */
-int flexran_get_current_RI(mid_t mod_id, mid_t ue_id, int CC_id);
-
-/* See TS 36.213, section 10.1 */
-int flexran_get_n1pucch_an(mid_t mod_id, int CC_id);
-
-/* See TS 36.211, section 5.4 */
-int flexran_get_nRB_CQI(mid_t mod_id, int CC_id);
-
-/* See TS 36.211, section 5.4 */
-int flexran_get_deltaPUCCH_Shift(mid_t mod_id, int CC_id);
-
-/* See TS 36.211, section 5.7.1 */
-int flexran_get_prach_ConfigIndex(mid_t mod_id, int CC_id);
-
-/* See TS 36.211, section 5.7.1 */
-int flexran_get_prach_FreqOffset(mid_t mod_id, int CC_id);
-
-/* See TS 36.321 */
-int flexran_get_maxHARQ_Msg3Tx(mid_t mod_id, int CC_id);
-
-/* Get the length of the UL cyclic prefix */
-int flexran_get_ul_cyclic_prefix_length(mid_t mod_id, int CC_id);
-
-/* Get the length of the DL cyclic prefix */
-int flexran_get_dl_cyclic_prefix_length(mid_t mod_id, int CC_id);
-
-/* Get the physical cell id of a cell */
-int flexran_get_cell_id(mid_t mod_id, int CC_id);
-
-/* See TS 36.211, section 5.5.3.2 */
-int flexran_get_srs_BandwidthConfig(mid_t mod_id, int CC_id);
-
-/* See TS 36.211, table 5.5.3.3-1 and 2 */
-int flexran_get_srs_SubframeConfig(mid_t mod_id, int CC_id);
-
-/* Boolean value. See TS 36.211,
-   section 5.5.3.2. TDD only */
-int flexran_get_srs_MaxUpPts(mid_t mod_id, int CC_id);
-
-/* Get number of DL resource blocks */
-int flexran_get_N_RB_DL(mid_t mod_id, int CC_id);
-
-/* Get number of UL resource blocks */
-int flexran_get_N_RB_UL(mid_t mod_id, int CC_id);
-
-/* Get number of resource block groups */
-int flexran_get_N_RBG(mid_t mod_id, int CC_id);
-
-/* Get DL/UL subframe assignment. TDD only */
-int flexran_get_subframe_assignment(mid_t mod_id, int CC_id);
-
-/* TDD only. See TS 36.211, table 4.2.1 */
-int flexran_get_special_subframe_assignment(mid_t mod_id, int CC_id);
-
-/* Get the duration of the random access response window in subframes */
-int flexran_get_ra_ResponseWindowSize(mid_t mod_id, int CC_id);
-
-/* Get timer used for random access */
-int flexran_get_mac_ContentionResolutionTimer(mid_t mod_id, int CC_id);
-
-/* Get type of duplex mode (FDD/TDD) */
-int flexran_get_duplex_mode(mid_t mod_id, int CC_id);
-
-/* Get the SI window length */
-long flexran_get_si_window_length(mid_t mod_id, int CC_id);
-
-/* Get the number of PDCCH symbols configured for the cell */
-int flexran_get_num_pdcch_symb(mid_t mod_id, int CC_id);
-
-/* See TS 36.213, sec 5.1.1.1 */
-int flexran_get_tpc(mid_t mod_id, mid_t ue_id);
-
-/* Get the first available HARQ process for a specific cell and UE during 
-   a designated frame and subframe. Returns 0 for success. The id and the 
-   status of the HARQ process are stored in id and status respectively */
-int flexran_get_harq(const mid_t mod_id, const uint8_t CC_id, const mid_t ue_id,
-		     const int frame, const uint8_t subframe, unsigned char *id, unsigned char *round);
-
-/* Uplink power control management*/
-int flexran_get_p0_pucch_dbm(mid_t mod_id, mid_t ue_id, int CC_id);
-
-int flexran_get_p0_nominal_pucch(mid_t mod_id, int CC_id);
-
-int flexran_get_p0_pucch_status(mid_t mod_id, mid_t ue_id, int CC_id);
-
-int flexran_update_p0_pucch(mid_t mod_id, mid_t ue_id, int CC_id);
-
-
-/*
- * ************************************
- * Get Messages for UE Configuration Reply
- * ************************************
- */
-
-/* Get timer in subframes. Controls the synchronization
-   status of the UE, not the actual timing 
-   advance procedure. See TS 36.321 */
-int flexran_get_time_alignment_timer(mid_t mod_id, mid_t ue_id);
-
-/* Get measurement gap configuration. See TS 36.133 */
-int flexran_get_meas_gap_config(mid_t mod_id, mid_t ue_id);
-
-/* Get measurement gap configuration offset if applicable */
-int flexran_get_meas_gap_config_offset(mid_t mod_id, mid_t ue_id);
-
-/* DL aggregated bit-rate of non-gbr bearer
-   per UE. See TS 36.413 */
-int flexran_get_ue_aggregated_max_bitrate_dl (mid_t mod_id, mid_t ue_id);
-
-/* UL aggregated bit-rate of non-gbr bearer
-   per UE. See TS 36.413 */
-int flexran_get_ue_aggregated_max_bitrate_ul (mid_t mod_id, mid_t ue_id);
-
-/* Only half-duplex support. FDD
-   operation. Boolean value */
-int flexran_get_half_duplex(mid_t ue_id);
-
-/* Support of intra-subframe hopping.
-   Boolean value */
-int flexran_get_intra_sf_hopping(mid_t ue_id);
-
-/* UE support for type 2 hopping with
-   n_sb>1 */
-int flexran_get_type2_sb_1(mid_t ue_id);
-
-/* Get the UE category */
-int flexran_get_ue_category(mid_t ue_id);
-
-/* UE support for resource allocation
-   type 1 */
-int flexran_get_res_alloc_type1(mid_t ue_id);
-
-/* Get UE transmission mode */
-int flexran_get_ue_transmission_mode(mid_t mod_id, mid_t ue_id);
-
-/* Boolean value. See TS 36.321 */
-int flexran_get_tti_bundling(mid_t mod_id, mid_t ue_id);
-
-/* The max HARQ retransmission for UL.
-   See TS 36.321 */
-int flexran_get_maxHARQ_TX(mid_t mod_id, mid_t ue_id);
-
-/* See TS 36.213 */
-int flexran_get_beta_offset_ack_index(mid_t mod_id, mid_t ue_id);
-
-/* See TS 36.213 */
-int flexran_get_beta_offset_ri_index(mid_t mod_id, mid_t ue_id);
-
-/* See TS 36.213 */
-int flexran_get_beta_offset_cqi_index(mid_t mod_id, mid_t ue_id);
-
-/* Boolean. See TS36.213, Section 10.1 */
-int flexran_get_simultaneous_ack_nack_cqi(mid_t mod_id, mid_t ue_id);
-
-/* Boolean. See TS 36.213, Section 8.2 */
-int flexran_get_ack_nack_simultaneous_trans(mid_t mod_id,mid_t ue_id);
-
-/* Get aperiodic CQI report mode */
-int flexran_get_aperiodic_cqi_rep_mode(mid_t mod_id,mid_t ue_id);
-
-/* Get ACK/NACK feedback mode. TDD only */
-int flexran_get_tdd_ack_nack_feedback(mid_t mod_id, mid_t ue_id);
-
-/* See TS36.213, section 10.1 */
-int flexran_get_ack_nack_repetition_factor(mid_t mod_id, mid_t ue_id);
-
-/* Boolean. Extended buffer status report size */
-int flexran_get_extended_bsr_size(mid_t mod_id, mid_t ue_id);
-
-/* Get number of UE transmission antennas */
-int flexran_get_ue_transmission_antenna(mid_t mod_id, mid_t ue_id);
-
-/* Get logical channel group of a channel with id lc_id */
-int flexran_get_lcg(mid_t ue_id, mid_t lc_id);
-
-/* Get direction of logical channel with id lc_id */
-int flexran_get_direction(mid_t ue_id, mid_t lc_id);
-
-/*******************
- * timer primitves
- *******************/
-
-#define TIMER_NULL                 -1 
-#define TIMER_TYPE_INVALIDE        -2
-#define	TIMER_SETUP_FAILED         -3
-#define	TIMER_REMOVED_FAILED       -4
-#define	TIMER_ELEMENT_NOT_FOUND    -5
-
-
-/* Type of the callback executed when the timer expired */
-typedef Protocol__FlexranMessage *(*flexran_agent_timer_callback_t)(void*);
-
-typedef enum {
-  /* oneshot timer:  */
-  FLEXRAN_AGENT_TIMER_TYPE_ONESHOT = 0x0,
-
-  /* periodic timer  */
-  FLEXRAN_AGENT_TIMER_TYPE_PERIODIC = 0x1,
-
-  /* Inactive state: initial state for any timer. */
-  FLEXRAN_AGENT_TIMER_TYPE_EVENT_DRIVEN = 0x2,
-  
-  /* Max number of states available */
-  FLEXRAN_AGENT_TIMER_TYPE_MAX,
-} flexran_agent_timer_type_t;
-
-typedef enum {
-  /* Inactive state: initial state for any timer. */
-  FLEXRAN_AGENT_TIMER_STATE_INACTIVE = 0x0,
-
-  /* Inactive state: initial state for any timer. */
-  FLEXRAN_AGENT_TIMER_STATE_ACTIVE = 0x1,
-
-  /* Inactive state: initial state for any timer. */
-  FLEXRAN_AGENT_TIMER_STATE_STOPPED = 0x2,
-  
-  /* Max number of states available */
-  FLEXRAN_AGENT_TIMER_STATE_MAX,
-} flexran_agent_timer_state_t;
-
-typedef struct flexran_agent_timer_args_s{
-  mid_t            mod_id;
-  Protocol__FlexranMessage *msg;
-} flexran_agent_timer_args_t;
-
-
-
-typedef struct flexran_agent_timer_element_s{
-  RB_ENTRY(flexran_agent_timer_element_s) entry;
-
-  agent_id_t             agent_id;
-  instance_t       instance;
-  
-  flexran_agent_timer_type_t  type;
-  flexran_agent_timer_state_t state;
-
-  uint32_t interval_sec;
-  uint32_t interval_usec;
-
-  long timer_id;  /* Timer id returned by the timer API*/
-  xid_t xid; /*The id of the task as received by the controller
-	       message*/
-  
-  flexran_agent_timer_callback_t cb;
-  flexran_agent_timer_args_t *timer_args;
-  
-} flexran_agent_timer_element_t;
-
-typedef struct flexran_agent_timer_instance_s{
-  RB_HEAD(flexran_agent_map, flexran_agent_timer_element_s) flexran_agent_head;
-}flexran_agent_timer_instance_t;
-
-
-err_code_t flexran_agent_init_timer(void);
-
-/* Create a timer for some agent related event with id xid. Will store the id 
-   of the generated timer in timer_id */
-err_code_t flexran_agent_create_timer(uint32_t interval_sec,
-				  uint32_t interval_usec,
-				  agent_id_t     agent_id,
-				  instance_t     instance,
-				  uint32_t timer_type,
-				  xid_t xid,
-				  flexran_agent_timer_callback_t cb,
-				  void*    timer_args,
-				  long *timer_id);
-
-/* Destroy all existing timers */
-err_code_t flexran_agent_destroy_timers(void);
-
-/* Destroy the timer with the given timer_id */
-err_code_t flexran_agent_destroy_timer(long timer_id);
-
-/* Destroy the timer for task with id xid */
-err_code_t flexran_agent_destroy_timer_by_task_id(xid_t xid);
-
-/* Stop a timer */
-err_code_t flexran_agent_stop_timer(long timer_id);
-
-/* Restart the given timer */
-err_code_t flexran_agent_restart_timer(long *timer_id);
-
-/* Find the timer with the given timer_id */
-struct flexran_agent_timer_element_s * get_timer_entry(long timer_id);
-
-/* Obtain the protocol message stored in the given expired timer */
-Protocol__FlexranMessage * flexran_agent_process_timeout(long timer_id, void* timer_args);
-
-/* Comparator function comparing two timers. Decides the ordering of the timers */
-int flexran_agent_compare_timer(struct flexran_agent_timer_element_s *a, struct flexran_agent_timer_element_s *b);
-
-/*Specify a delay in nanoseconds to timespec and sleep until then*/
-void flexran_agent_sleep_until(struct timespec *ts, int delay);
+err_code_t flexran_agent_init_cont_stats_update(mid_t mod_id);
 
-/* RB_PROTOTYPE is for .h files */
-RB_PROTOTYPE(flexran_agent_map, flexran_agent_timer_element_s, entry, flexran_agent_compare_timer);
+void flexran_agent_send_update_stats(mid_t mod_id);
 
+err_code_t flexran_agent_enable_cont_stats_update(mid_t mod_id, xid_t xid, stats_request_config_t *stats_req) ;
+err_code_t flexran_agent_disable_cont_stats_update(mid_t mod_id);
 
 #endif
diff --git a/openair2/ENB_APP/flexran_agent_common_internal.c b/openair2/ENB_APP/flexran_agent_common_internal.c
index 240856b948254f45d558848a0050b1720595b2f2..de937db0c6b332ddbb84faa9ddd8a367d8716bf8 100644
--- a/openair2/ENB_APP/flexran_agent_common_internal.c
+++ b/openair2/ENB_APP/flexran_agent_common_internal.c
@@ -21,8 +21,8 @@
 
 /*! \file flexran_agent_common_internal.c
  * \brief internal functions for common message primitves and utilities 
- * \author Xenofon Foukas
- * \date 2016
+ * \author Xenofon Foukas and N. Nikaein
+ * \date 2017
  * \version 0.1
  */
 
@@ -32,6 +32,44 @@
 #include "flexran_agent_common_internal.h"
 #include "flexran_agent_mac_internal.h"
 
+/* the following is needed to soft-restart the lte-softmodem */
+#include "targets/RT/USER/lte-softmodem.h"
+#include "assertions.h"
+#include "enb_app.h"
+
+void handle_reconfiguration(mid_t mod_id)
+{
+  /* NOTE: this function might be extended by using stop_modem()
+   * to halt the modem so that it can later be resumed */
+  int do_restart = 0;
+
+  pthread_mutex_lock(&mutex_node_ctrl);
+  if (ENB_NORMAL_OPERATION != node_control_state) {
+    node_control_state = ENB_NORMAL_OPERATION;
+    pthread_cond_broadcast(&cond_node_ctrl);
+  } else {
+    do_restart = 1;
+  }
+  pthread_mutex_unlock(&mutex_node_ctrl);
+
+  if (do_restart) {
+    clock_t start_ms = 1000 * clock();
+    /* operator || enforces sequence points */
+    if (stop_L1L2(mod_id) < 0 || restart_L1L2(mod_id) < 0) {
+      LOG_E(ENB_APP, "could not restart, killing lte-softmodem\n");
+      /* shutdown the whole lte-softmodem */
+      itti_terminate_tasks(TASK_PHY_ENB);
+      return;
+    }
+    enb_app_start_phy_rrc(mod_id, mod_id+1);
+    MessageDef *msg_p = itti_alloc_new_message(TASK_ENB_APP, INITIALIZE_MESSAGE);
+    itti_send_msg_to_task(TASK_L2L1, INSTANCE_DEFAULT, msg_p);
+
+    int diff_ms = (1000 * clock() - start_ms) / CLOCKS_PER_SEC;
+    LOG_I(ENB_APP, "lte-softmodem restart succeeded in %d ms\n", diff_ms);
+  }
+}
+
 int apply_reconfiguration_policy(mid_t mod_id, const char *policy, size_t policy_length) {
 
   yaml_parser_t parser;
@@ -64,7 +102,16 @@ int apply_reconfiguration_policy(mid_t mod_id, const char *policy, size_t policy
       break;
     case YAML_SCALAR_EVENT:
       // Check the system name and call the proper handler
-      if (strcmp((char *) event.data.scalar.value, "mac") == 0) {
+      // Check the system name and call the proper handler
+      if (strcmp((char *) event.data.scalar.value, "enb") == 0) {
+	LOG_I(ENB_APP, "This is intended for the enb system\n");
+	// Call the enb handler
+	if (parse_enb_id(mod_id, &parser) == -1) {
+	  goto error;
+	} else { // succeful parse and setting 
+          handle_reconfiguration(mod_id);
+	}
+      } else if (strcmp((char *) event.data.scalar.value, "mac") == 0) {
 	LOG_D(ENB_APP, "This is intended for the mac system\n");
 	// Call the mac handler
 	if (parse_mac_config(mod_id, &parser) == -1) {
@@ -90,8 +137,8 @@ int apply_reconfiguration_policy(mid_t mod_id, const char *policy, size_t policy
 	// TODO : Just skip it for now
 	if (skip_system_section(&parser) == -1) {
 	  goto error;
-	}
-      } else {
+	} 
+      } else { 
 	goto error;
       }
       break;
@@ -115,6 +162,147 @@ int apply_reconfiguration_policy(mid_t mod_id, const char *policy, size_t policy
 
 }
 
+int parse_enb_id(mid_t mod_id, yaml_parser_t *parser) {
+  yaml_event_t event;
+  
+  char *endptr;
+  // int is_array;
+  
+  int done = 0;
+  int mapping_started = 0;
+
+  while (!done) {
+    
+    if (!yaml_parser_parse(parser, &event))
+      goto error;
+
+    switch (event.type) {
+      // We are expecting a mapping of parameters
+    case YAML_SEQUENCE_START_EVENT:
+      // is_array = 1;
+      break;
+    case YAML_MAPPING_START_EVENT:
+      LOG_D(ENB_APP, "The mapping of the parameters started\n");
+      mapping_started = 1;
+      break;
+    case YAML_MAPPING_END_EVENT:
+      LOG_D(ENB_APP, "The mapping of the parameters ended\n");
+      mapping_started = 0;
+      break;
+    case YAML_SCALAR_EVENT:
+      if (!mapping_started) {
+	goto error;
+      }
+      // Check what key needs to be set
+      // use eNB egistered
+      if (mac_agent_registered[mod_id]) {
+	LOG_I(ENB_APP, "Setting parameter for eNB %s\n", event.data.scalar.value);
+	if (strcmp((char *) event.data.scalar.tag, YAML_INT_TAG) == 0) { // if int 
+	  if ((strtol((char *) event.data.scalar.value, &endptr, 10))== mod_id ) { // enb_id == mod_id: right enb instance to be configured
+	    if (parse_enb_config_parameters(mod_id, parser) == -1) {
+	      goto error;
+	    } 
+	  }
+	  else{
+	    goto error; // not the expected type
+	  }
+	}
+      }
+      break;
+    default:
+      goto error;
+    }
+
+    done = (event.type == YAML_MAPPING_END_EVENT);
+    yaml_event_delete(&event);
+  }
+
+  return 0;
+  
+ error:
+  yaml_event_delete(&event);
+  return -1;
+}
+
+int parse_enb_config_parameters(mid_t mod_id, yaml_parser_t *parser) {
+  yaml_event_t event;
+  
+  char *endptr;
+  
+  int done = 0;
+  int mapping_started = 0;
+
+  while (!done) {
+    
+    if (!yaml_parser_parse(parser, &event))
+      goto error;
+
+    switch (event.type) {
+      // We are expecting a mapping of parameters
+    case YAML_MAPPING_START_EVENT:
+      LOG_D(ENB_APP, "The mapping of the parameters started\n");
+      mapping_started = 1;
+      break;
+    case YAML_MAPPING_END_EVENT:
+      LOG_D(ENB_APP, "The mapping of the parameters ended\n");
+      mapping_started = 0;
+      break;
+    case YAML_SCALAR_EVENT:
+      if (!mapping_started) {
+	goto error;
+      }
+      // Check what key needs to be set
+      if (strcmp((char *) event.data.scalar.value, "dl_freq") == 0) {
+        if (!yaml_parser_parse(parser, &event))
+          goto error;
+	flexran_agent_set_operating_dl_freq(mod_id,
+					    0,
+					    strtol((char *) event.data.scalar.value, &endptr, 10));
+        LOG_I(ENB_APP, "Setting dl_freq to %s\n", event.data.scalar.value);
+      } else if (strcmp((char *) event.data.scalar.value, "ul_freq_offset") == 0) {
+        if (!yaml_parser_parse(parser, &event))
+          goto error;
+	flexran_agent_set_operating_ul_freq(mod_id,
+					    0,
+					    strtol((char *) event.data.scalar.value, &endptr, 10));
+        LOG_I(ENB_APP, "Setting ul_freq_offset to %s\n", event.data.scalar.value);
+      } else if (strcmp((char *) event.data.scalar.value, "bandwidth") == 0) {
+        if (!yaml_parser_parse(parser, &event))
+          goto error;
+	flexran_agent_set_operating_bandwidth(mod_id,
+					    0,
+					    strtol((char *) event.data.scalar.value, &endptr, 10));
+        LOG_I(ENB_APP, "Setting bandwidth to %s\n", event.data.scalar.value);
+      } else if (strcmp((char *) event.data.scalar.value, "frame_type") == 0) {
+        if (!yaml_parser_parse(parser, &event))
+          goto error;
+	flexran_agent_set_operating_frame_type (mod_id,
+					    0,
+					    strtol((char *) event.data.scalar.value, &endptr, 10));
+        LOG_I(ENB_APP, "Setting frame_type to %s\n", event.data.scalar.value);
+      }else { // not supported tag  
+	goto error;
+      }
+      
+      break;
+    default:
+      goto error;
+    }
+
+    done = (event.type == YAML_MAPPING_END_EVENT);
+    yaml_event_delete(&event);
+  }
+
+  /* reflect in RAN API */
+  flexran_set_enb_vars(mod_id, RAN_LTE_OAI);
+
+  return 0;
+  
+ error:
+  yaml_event_delete(&event);
+  return -1;
+}
+
 int skip_system_section(yaml_parser_t *parser) {
   yaml_event_t event;
   
diff --git a/openair2/ENB_APP/flexran_agent_common_internal.h b/openair2/ENB_APP/flexran_agent_common_internal.h
index d91c2dc7f6578db33ece11dfeb642ea701c35ae9..bf908ac13232b8743c72411481a8be649d884519 100644
--- a/openair2/ENB_APP/flexran_agent_common_internal.h
+++ b/openair2/ENB_APP/flexran_agent_common_internal.h
@@ -21,8 +21,8 @@
 
 /*! \file flexran_agent_common_internal.h
  * \brief internal agent functions for common message primitves and utilities
- * \author Xenofon Foukas
- * \date 2016
+ * \author Xenofon Foukas and N. Nikaein
+ * \date 2017
  * \version 0.1
  */
 
@@ -37,6 +37,10 @@ int apply_reconfiguration_policy(mid_t mod_id, const char *policy, size_t policy
 
 int apply_parameter_modification(void *parameter, yaml_parser_t *parser);
 
+int parse_enb_id(mid_t mod_id, yaml_parser_t *parser);
+int parse_enb_config_parameters(mid_t mod_id, yaml_parser_t *parser) ;
+
+
 // This can be used when parsing for a specific system that is not yet implmeneted
 // in order to skip its configuration, without affecting the rest
 int skip_system_section(yaml_parser_t *parser);
diff --git a/openair2/ENB_APP/flexran_agent_defs.h b/openair2/ENB_APP/flexran_agent_defs.h
index 12e3c56dffa16ffeb71a8141bf0499e8db585bba..2de19e59aaeb835e346d0184c694c7f33be9055b 100644
--- a/openair2/ENB_APP/flexran_agent_defs.h
+++ b/openair2/ENB_APP/flexran_agent_defs.h
@@ -21,8 +21,8 @@
 
 /*! \file flexran_agent_defs.h
  * \brief FlexRAN agent common definitions 
- * \author Navid Nikaein and Xenofon Foukas
- * \date 2016
+ * \author Navid Nikaein and Xenofon Foukas and shahab SHARIAT BAGHERI
+ * \date 2017
  * \version 0.1
  */
 #ifndef FLEXRAN_AGENT_DEFS_H_
@@ -32,11 +32,16 @@
 #include <stdlib.h>
 #include <pthread.h>
 #include <string.h>
+#include <stdbool.h>
+#include <time.h>
 
 #include "link_manager.h"
 
 #define NUM_MAX_ENB 2
+#define NUM_MAX_DRB 8
+#define NUM_MAX_SRB 3
 #define NUM_MAX_UE 2048
+#define DEFAULT_DRB 3
 #define DEFAULT_FLEXRAN_AGENT_IPv4_ADDRESS "127.0.0.1"
 #define DEFAULT_FLEXRAN_AGENT_PORT          2210
 #define DEFAULT_FLEXRAN_AGENT_CACHE        "/mnt/oai_agent_cache"
@@ -102,6 +107,38 @@ typedef uint8_t lcid_t;
 typedef int32_t  err_code_t; 
 
 
+/*---------Timer Enums --------- */
+
+typedef enum {
+  /* oneshot timer:  */
+  FLEXRAN_AGENT_TIMER_TYPE_ONESHOT = 0,
+
+  /* periodic timer  */
+  FLEXRAN_AGENT_TIMER_TYPE_PERIODIC = 1,
+
+  /* Inactive state: initial state for any timer. */
+  FLEXRAN_AGENT_TIMER_TYPE_EVENT_DRIVEN = 2,
+  
+  /* Max number of states available */
+  FLEXRAN_AGENT_TIMER_TYPE_MAX,
+} flexran_agent_timer_type_t;
+
+
+typedef enum {
+  /* Inactive state: initial state for any timer. */
+  FLEXRAN_AGENT_TIMER_STATE_INACTIVE = 0x0,
+
+  /* Inactive state: initial state for any timer. */
+  FLEXRAN_AGENT_TIMER_STATE_ACTIVE = 0x1,
+
+  /* Inactive state: initial state for any timer. */
+  FLEXRAN_AGENT_TIMER_STATE_STOPPED = 0x2,
+  
+  /* Max number of states available */
+  FLEXRAN_AGENT_TIMER_STATE_MAX,
+} flexran_agent_timer_state_t;
+
+
 
 typedef struct {
   /* general info */ 
@@ -116,6 +153,53 @@ typedef struct {
 
 } flexran_agent_info_t;
 
+
+/*
+rrc triggering
+ */
+
+
+typedef struct {
+   char   * trigger_policy;
+   uint32_t report_interval;
+   uint32_t report_amount;
+
+} agent_reconf_rrc;
+
+
+/* These structs will be used to give
+   instructions for the type of stats reports
+   we need to create */
+
+
+typedef struct {
+  uint16_t ue_rnti;
+  uint32_t ue_report_flags; /* Indicates the report elements
+             required for this UE id. See
+             FlexRAN specification 1.2.4.2 */
+} ue_report_type_t;
+
+typedef struct {
+  uint16_t cc_id;
+  uint32_t cc_report_flags; /* Indicates the report elements
+            required for this CC index. See
+            FlexRAN specification 1.2.4.3 */
+} cc_report_type_t;
+
+typedef struct {
+  int nr_ue;
+  ue_report_type_t *ue_report_type;
+  int nr_cc;
+  cc_report_type_t *cc_report_type;
+} report_config_t;
+
+typedef struct stats_request_config_s{
+  uint8_t report_type;
+  uint8_t report_frequency;
+  uint16_t period; /*In number of subframes*/
+  report_config_t *config;
+} stats_request_config_t;
+
 typedef struct {
   mid_t enb_id;
   flexran_agent_info_t agent_info;
diff --git a/openair2/ENB_APP/flexran_agent_extern.h b/openair2/ENB_APP/flexran_agent_extern.h
index 6237f78367cad368d6115e42f7b6e02cdae88f75..8e9fef383dd40ef702d8c000f49005786e925205 100644
--- a/openair2/ENB_APP/flexran_agent_extern.h
+++ b/openair2/ENB_APP/flexran_agent_extern.h
@@ -20,9 +20,9 @@
  */ 
 
 /*! \file ENB_APP/extern.h
- * \brief FlexRAN agent - mac interface primitives
- * \author Xenofon Foukas
- * \date 2016
+ * \brief FlexRAN agent - Extern VSF xfaces
+ * \author Xenofon Foukas and shahab SHARIAT BAGHERI
+ * \date 2017
  * \version 0.1
  * \mail x.foukas@sms.ed.ac.uk
  */
@@ -30,9 +30,10 @@
 #ifndef __FLEXRAN_AGENT_EXTERN_H__
 #define __FLEXRAN_AGENT_EXTERN_H__
 
-#include "flexran_agent_defs.h"
+// #include "flexran_agent_defs.h"
 #include "flexran_agent_mac_defs.h"
-
+#include "flexran_agent_rrc_defs.h"
+#include "flexran_agent_pdcp_defs.h"
 
 //extern msg_context_t shared_ctxt[NUM_MAX_ENB][FLEXRAN_AGENT_MAX];
 
@@ -45,6 +46,18 @@ extern AGENT_MAC_xface *agent_mac_xface[NUM_MAX_ENB];
 /* Flag indicating whether the VSFs for the MAC control module have been registered */
 extern unsigned int mac_agent_registered[NUM_MAX_ENB];
 
+/* Control module interface for the communication of the RRC Control Module with the agent */
+extern AGENT_RRC_xface *agent_rrc_xface[NUM_MAX_ENB];
+
+/* Flag indicating whether the VSFs for the RRC control module have been registered */
+extern unsigned int rrc_agent_registered[NUM_MAX_ENB];
+
+/* Control module interface for the communication of the RRC Control Module with the agent */
+extern AGENT_PDCP_xface *agent_pdcp_xface[NUM_MAX_ENB];
+
+/* Flag indicating whether the VSFs for the RRC control module have been registered */
+extern unsigned int pdcp_agent_registered[NUM_MAX_ENB];
+
 /* Requried to know which UEs had a harq updated over some subframe */
 extern int harq_pid_updated[NUMBER_OF_UE_MAX][8];
 extern int harq_pid_round[NUMBER_OF_UE_MAX][8];
diff --git a/openair2/ENB_APP/flexran_agent_handler.c b/openair2/ENB_APP/flexran_agent_handler.c
index 51188bea86216a8ce6640e396d31bdae1046ea45..3597463ae369c2aee14d36e07a81b24dacd1ce92 100644
--- a/openair2/ENB_APP/flexran_agent_handler.c
+++ b/openair2/ENB_APP/flexran_agent_handler.c
@@ -21,14 +21,18 @@
 
 /*! \file flexran_agent_handler.c
  * \brief FlexRAN agent tx and rx message handler 
- * \author Xenofon Foukas and Navid Nikaein
- * \date 2016
+ * \author Xenofon Foukas and Navid Nikaein and shahab SHARIAT BAGHERI
+ * \date 2017
  * \version 0.1
  */
 
-
+#include "flexran_agent_defs.h"
 #include "flexran_agent_common.h"
 #include "flexran_agent_mac.h"
+#include "flexran_agent_rrc.h"
+#include "flexran_agent_pdcp.h"
+#include "flexran_agent_timer.h"
+#include "flexran_agent_ran_api.h"
 #include "log.h"
 
 #include "assertions.h"
@@ -37,7 +41,7 @@ flexran_agent_message_decoded_callback agent_messages_callback[][3] = {
   {flexran_agent_hello, 0, 0}, /*PROTOCOL__FLEXRAN_MESSAGE__MSG_HELLO_MSG*/
   {flexran_agent_echo_reply, 0, 0}, /*PROTOCOL__FLEXRAN_MESSAGE__MSG_ECHO_REQUEST_MSG*/
   {0, 0, 0}, /*PROTOCOL__FLEXRAN_MESSAGE__MSG_ECHO_REPLY_MSG*/ //Must add handler when receiving echo reply
-  {flexran_agent_mac_handle_stats, 0, 0}, /*PROTOCOL__FLEXRAN_MESSAGE__MSG_STATS_REQUEST_MSG*/
+  {flexran_agent_handle_stats, 0, 0}, /*PROTOCOL__FLEXRAN_MESSAGE__MSG_STATS_REQUEST_MSG*/
   {0, 0, 0}, /*PROTOCOL__FLEXRAN_MESSAGE__MSG_STATS_REPLY_MSG*/
   {0, 0, 0}, /*PROTOCOK__FLEXRAN_MESSAGE__MSG_SF_TRIGGER_MSG*/
   {0, 0, 0}, /*PROTOCOL__FLEXRAN_MESSAGE__MSG_UL_SR_INFO_MSG*/
@@ -51,13 +55,14 @@ flexran_agent_message_decoded_callback agent_messages_callback[][3] = {
   {0, 0, 0}, /*PROTOCOL__FLEXRAN_MESSAGE__MSG_UE_STATE_CHANGE_MSG*/
   {flexran_agent_control_delegation, 0, 0}, /*PROTOCOL__FLEXRAN_MESSAGE__MSG_CONTROL_DELEGATION_MSG*/
   {flexran_agent_reconfiguration, 0, 0}, /*PROTOCOL__FLEXRAN_MESSAGE__MSG_AGENT_RECONFIGURATION_MSG*/
+  {flexran_agent_rrc_measurement, 0, 0}, /*PROTOCOL__FLEXRAN_MESSAGE__MSG_RRC_TRIGGERING_MSG*/
 };
 
 flexran_agent_message_destruction_callback message_destruction_callback[] = {
   flexran_agent_destroy_hello,
   flexran_agent_destroy_echo_request,
   flexran_agent_destroy_echo_reply,
-  flexran_agent_mac_destroy_stats_request,
+  flexran_agent_destroy_stats_request,
   flexran_agent_mac_destroy_stats_reply,
   flexran_agent_mac_destroy_sf_trigger,
   flexran_agent_mac_destroy_sr_info,
@@ -93,7 +98,6 @@ Protocol__FlexranMessage* flexran_agent_handle_message (mid_t mod_id,
     err_code= PROTOCOL__FLEXRAN_ERR__MSG_DECODING;
     goto error; 
   }
-  
   if ((decoded_message->msg_case > sizeof(agent_messages_callback) / (3 * sizeof(flexran_agent_message_decoded_callback))) || 
       (decoded_message->msg_dir > PROTOCOL__FLEXRAN_DIRECTION__UNSUCCESSFUL_OUTCOME)){
     err_code= PROTOCOL__FLEXRAN_ERR__MSG_NOT_HANDLED;
@@ -139,7 +143,7 @@ void * flexran_agent_pack_message(Protocol__FlexranMessage *msg,
   
   DevAssert(buffer !=NULL);
   
-  LOG_D(FLEXRAN_AGENT,"Serilized the enb mac stats reply (size %d)\n", *size);
+  LOG_D(FLEXRAN_AGENT,"Serilized the eNB-UE stats reply (size %d)\n", *size);
   
   return buffer;
   
@@ -187,3 +191,587 @@ Protocol__FlexranMessage* flexran_agent_process_timeout(long timer_id, void* tim
 err_code_t flexran_agent_destroy_flexran_message(Protocol__FlexranMessage *msg) {
   return ((*message_destruction_callback[msg->msg_case-1])(msg));
 }
+
+
+/* 
+  Top Level Statistics Report
+
+ */
+
+
+
+int flexran_agent_handle_stats(mid_t mod_id, const void *params, Protocol__FlexranMessage **msg){
+
+  // TODO: Must deal with sanitization of input
+  // TODO: Must check if RNTIs and cell ids of the request actually exist
+  // TODO: Must resolve conflicts among stats requests
+
+  int i;
+  err_code_t err_code;
+  xid_t xid;
+  uint32_t usec_interval, sec_interval;
+
+  //TODO: We do not deal with multiple CCs at the moment and eNB id is 0
+  int enb_id = mod_id;
+
+  //eNB_MAC_INST *eNB = &eNB_mac_inst[enb_id];
+  //UE_list_t *eNB_UE_list=  &eNB->UE_list;
+
+  report_config_t report_config;
+
+  uint32_t ue_flags = 0;
+  uint32_t c_flags = 0;
+
+  Protocol__FlexranMessage *input = (Protocol__FlexranMessage *)params;
+
+  Protocol__FlexStatsRequest *stats_req = input->stats_request_msg;
+  xid = (stats_req->header)->xid;
+
+  // Check the type of request that is made
+  switch(stats_req->body_case) {
+  case PROTOCOL__FLEX_STATS_REQUEST__BODY_COMPLETE_STATS_REQUEST: ;
+    Protocol__FlexCompleteStatsRequest *comp_req = stats_req->complete_stats_request;
+    if (comp_req->report_frequency == PROTOCOL__FLEX_STATS_REPORT_FREQ__FLSRF_OFF) {
+      /*Disable both periodic and continuous updates*/
+      // flexran_agent_disable_cont_stats_update(mod_id);
+      flexran_agent_destroy_timer_by_task_id(xid);
+      *msg = NULL;
+      return 0;
+    } else { //One-off, periodical or continuous reporting
+      //Set the proper flags
+      ue_flags = comp_req->ue_report_flags;
+      c_flags = comp_req->cell_report_flags;
+      //Create a list of all eNB RNTIs and cells
+
+      //Set the number of UEs and create list with their RNTIs stats configs
+      report_config.nr_ue = flexran_get_num_ues(mod_id); //eNB_UE_list->num_UEs
+      report_config.ue_report_type = (ue_report_type_t *) malloc(sizeof(ue_report_type_t) * report_config.nr_ue);
+      if (report_config.ue_report_type == NULL) {
+  // TODO: Add appropriate error code
+  err_code = -100;
+  goto error;
+      }
+      for (i = 0; i < report_config.nr_ue; i++) {
+  report_config.ue_report_type[i].ue_rnti = flexran_get_ue_crnti(enb_id, i); //eNB_UE_list->eNB_UE_stats[UE_PCCID(enb_id,i)][i].crnti;
+  report_config.ue_report_type[i].ue_report_flags = ue_flags;
+      }
+      //Set the number of CCs and create a list with the cell stats configs
+      report_config.nr_cc = MAX_NUM_CCs;
+      report_config.cc_report_type = (cc_report_type_t *) malloc(sizeof(cc_report_type_t) * report_config.nr_cc);
+      if (report_config.cc_report_type == NULL) {
+  // TODO: Add appropriate error code
+  err_code = -100;
+  goto error;
+      }
+      for (i = 0; i < report_config.nr_cc; i++) {
+  //TODO: Must fill in the proper cell ids
+  report_config.cc_report_type[i].cc_id = i;
+  report_config.cc_report_type[i].cc_report_flags = c_flags;
+      }
+      /* Check if request was periodical */
+      if (comp_req->report_frequency == PROTOCOL__FLEX_STATS_REPORT_FREQ__FLSRF_PERIODICAL) {
+  /* Create a one off flexran message as an argument for the periodical task */
+  Protocol__FlexranMessage *timer_msg;
+  stats_request_config_t request_config;
+  request_config.report_type = PROTOCOL__FLEX_STATS_TYPE__FLST_COMPLETE_STATS;
+  request_config.report_frequency = PROTOCOL__FLEX_STATS_REPORT_FREQ__FLSRF_ONCE;
+  request_config.period = 0;
+  /* Need to make sure that the ue flags are saved (Bug) */
+  if (report_config.nr_ue == 0) {
+    report_config.nr_ue = 1;
+    report_config.ue_report_type = (ue_report_type_t *) malloc(sizeof(ue_report_type_t));
+     if (report_config.ue_report_type == NULL) {
+       // TODO: Add appropriate error code
+       err_code = -100;
+       goto error;
+     }
+     report_config.ue_report_type[0].ue_rnti = 0; // Dummy value
+     report_config.ue_report_type[0].ue_report_flags = ue_flags;
+  }
+  request_config.config = &report_config;
+  flexran_agent_stats_request(enb_id, xid, &request_config, &timer_msg);
+  /* Create a timer */
+  long timer_id = 0;
+  flexran_agent_timer_args_t *timer_args;
+  timer_args = malloc(sizeof(flexran_agent_timer_args_t));
+  memset (timer_args, 0, sizeof(flexran_agent_timer_args_t));
+  timer_args->mod_id = enb_id;
+  timer_args->msg = timer_msg;
+  /*Convert subframes to usec time*/
+  usec_interval = 1000*comp_req->sf;
+  sec_interval = 0;
+  /*add seconds if required*/
+  if (usec_interval >= 1000*1000) {
+    sec_interval = usec_interval/(1000*1000);
+    usec_interval = usec_interval%(1000*1000);
+  }
+  flexran_agent_create_timer(sec_interval, usec_interval, FLEXRAN_AGENT_DEFAULT, enb_id, FLEXRAN_AGENT_TIMER_TYPE_PERIODIC, xid, flexran_agent_handle_timed_task,(void*) timer_args, &timer_id);
+      } else if (comp_req->report_frequency == PROTOCOL__FLEX_STATS_REPORT_FREQ__FLSRF_CONTINUOUS) {
+  /*If request was for continuous updates, disable the previous configuration and
+    set up a new one*/
+  flexran_agent_disable_cont_stats_update(mod_id);
+  stats_request_config_t request_config;
+  request_config.report_type = PROTOCOL__FLEX_STATS_TYPE__FLST_COMPLETE_STATS;
+  request_config.report_frequency = PROTOCOL__FLEX_STATS_REPORT_FREQ__FLSRF_ONCE;
+  request_config.period = 0;
+  /* Need to make sure that the ue flags are saved (Bug) */
+  if (report_config.nr_ue == 0) {
+    report_config.nr_ue = 1;
+    report_config.ue_report_type = (ue_report_type_t *) malloc(sizeof(ue_report_type_t));
+    if (report_config.ue_report_type == NULL) {
+      // TODO: Add appropriate error code
+      err_code = -100;
+      goto error;
+    }
+    report_config.ue_report_type[0].ue_rnti = 0; // Dummy value
+    report_config.ue_report_type[0].ue_report_flags = ue_flags;
+  }
+  request_config.config = &report_config;
+  flexran_agent_enable_cont_stats_update(enb_id, xid, &request_config);
+      }
+    }
+    break;
+  case PROTOCOL__FLEX_STATS_REQUEST__BODY_CELL_STATS_REQUEST:;
+    Protocol__FlexCellStatsRequest *cell_req = stats_req->cell_stats_request;
+    // UE report config will be blank
+    report_config.nr_ue = 0;
+    report_config.ue_report_type = NULL;
+    report_config.nr_cc = cell_req->n_cell;
+    report_config.cc_report_type = (cc_report_type_t *) malloc(sizeof(cc_report_type_t) * report_config.nr_cc);
+    if (report_config.cc_report_type == NULL) {
+      // TODO: Add appropriate error code
+      err_code = -100;
+      goto error;
+    }
+    for (i = 0; i < report_config.nr_cc; i++) {
+  //TODO: Must fill in the proper cell ids
+      report_config.cc_report_type[i].cc_id = cell_req->cell[i];
+      report_config.cc_report_type[i].cc_report_flags = cell_req->flags;
+    }
+    break;
+  case PROTOCOL__FLEX_STATS_REQUEST__BODY_UE_STATS_REQUEST:;
+    Protocol__FlexUeStatsRequest *ue_req = stats_req->ue_stats_request;
+    // Cell report config will be blank
+    report_config.nr_cc = 0;
+    report_config.cc_report_type = NULL;
+    report_config.nr_ue = ue_req->n_rnti;
+    report_config.ue_report_type = (ue_report_type_t *) malloc(sizeof(ue_report_type_t) * report_config.nr_ue);
+    if (report_config.ue_report_type == NULL) {
+      // TODO: Add appropriate error code
+      err_code = -100;
+      goto error;
+    }
+    for (i = 0; i < report_config.nr_ue; i++) {
+      report_config.ue_report_type[i].ue_rnti = ue_req->rnti[i];
+      report_config.ue_report_type[i].ue_report_flags = ue_req->flags;
+    }
+    break;
+  default:
+    //TODO: Add appropriate error code
+    err_code = -100;
+    goto error;
+  }
+
+   if (flexran_agent_stats_reply(enb_id, xid, &report_config, msg )){  
+      err_code = PROTOCOL__FLEXRAN_ERR__MSG_BUILD;
+      goto error;
+    }
+
+  free(report_config.ue_report_type);
+  free(report_config.cc_report_type);
+
+  return 0;
+
+ error :
+  LOG_E(FLEXRAN_AGENT, "errno %d occured\n", err_code);
+  return err_code;
+}
+
+/*
+  Top level reply 
+ */
+
+int flexran_agent_stats_reply(mid_t enb_id, xid_t xid, const report_config_t *report_config, Protocol__FlexranMessage **msg){
+
+  Protocol__FlexHeader *header;
+  err_code_t err_code;
+  int i;
+
+  if (flexran_create_header(xid, PROTOCOL__FLEX_TYPE__FLPT_STATS_REPLY, &header) != 0)
+    goto error;
+
+  
+  Protocol__FlexStatsReply *stats_reply_msg;
+
+  stats_reply_msg = malloc(sizeof(Protocol__FlexStatsReply));
+
+  if (stats_reply_msg == NULL)
+    goto error;
+
+  protocol__flex_stats_reply__init(stats_reply_msg);
+  stats_reply_msg->header = header;
+
+  stats_reply_msg->n_ue_report = report_config->nr_ue;
+  stats_reply_msg->n_cell_report = report_config->nr_cc;
+
+  // UE report
+
+  Protocol__FlexUeStatsReport **ue_report;
+  
+
+  ue_report = malloc(sizeof(Protocol__FlexUeStatsReport *) * report_config->nr_ue);
+          if (ue_report == NULL)
+            goto error;
+  
+  for (i = 0; i < report_config->nr_ue; i++) {
+
+      ue_report[i] = malloc(sizeof(Protocol__FlexUeStatsReport));
+      protocol__flex_ue_stats_report__init(ue_report[i]);
+      ue_report[i]->rnti = report_config->ue_report_type[i].ue_rnti;
+      ue_report[i]->has_rnti = 1;
+      ue_report[i]->flags = report_config->ue_report_type[i].ue_report_flags;
+      ue_report[i]->has_flags = 1;
+  
+  }
+
+  // cell rpoert 
+
+  Protocol__FlexCellStatsReport **cell_report;
+
+  
+  cell_report = malloc(sizeof(Protocol__FlexCellStatsReport *) * report_config->nr_cc);
+  if (cell_report == NULL)
+    goto error;
+  
+  for (i = 0; i < report_config->nr_cc; i++) {
+
+      cell_report[i] = malloc(sizeof(Protocol__FlexCellStatsReport));
+      if(cell_report[i] == NULL)
+          goto error;
+
+      protocol__flex_cell_stats_report__init(cell_report[i]);
+      cell_report[i]->carrier_index = report_config->cc_report_type[i].cc_id;
+      cell_report[i]->has_carrier_index = 1;
+      cell_report[i]->flags = report_config->cc_report_type[i].cc_report_flags;
+      cell_report[i]->has_flags = 1;
+
+  }
+
+      /*
+      MAC reply split
+     */
+
+
+    if (flexran_agent_mac_stats_reply(enb_id, report_config,  ue_report, cell_report) < 0 ) {
+        err_code = PROTOCOL__FLEXRAN_ERR__MSG_BUILD;
+        goto error;
+    }
+
+    /*
+      RRC reply split
+     */
+
+    if (flexran_agent_rrc_stats_reply(enb_id, report_config,  ue_report, cell_report) < 0 ) {
+        err_code = PROTOCOL__FLEXRAN_ERR__MSG_BUILD;
+        goto error;
+    }
+   
+
+    /*
+      PDCP reply split
+    */
+    
+    if (flexran_agent_pdcp_stats_reply(enb_id, report_config,  ue_report, cell_report) < 0 ) {
+      err_code = PROTOCOL__FLEXRAN_ERR__MSG_BUILD;
+      goto error;
+    }
+
+       
+  stats_reply_msg->cell_report = cell_report;
+  stats_reply_msg->ue_report = ue_report;
+
+ *msg = malloc(sizeof(Protocol__FlexranMessage));
+  if(*msg == NULL)
+    goto error;
+  protocol__flexran_message__init(*msg);
+  (*msg)->msg_case = PROTOCOL__FLEXRAN_MESSAGE__MSG_STATS_REPLY_MSG;
+  (*msg)->msg_dir =  PROTOCOL__FLEXRAN_DIRECTION__SUCCESSFUL_OUTCOME;
+  (*msg)->stats_reply_msg = stats_reply_msg;
+
+  return 0;
+
+error :
+  LOG_E(FLEXRAN_AGENT, "errno %d occured\n", err_code);
+  return err_code;
+
+}
+
+/*
+  Top Level Request 
+ */
+
+int flexran_agent_stats_request(mid_t mod_id,
+            xid_t xid,
+            const stats_request_config_t *report_config,
+            Protocol__FlexranMessage **msg) {
+  Protocol__FlexHeader *header;
+  int i;
+
+  Protocol__FlexStatsRequest *stats_request_msg;
+  stats_request_msg = malloc(sizeof(Protocol__FlexStatsRequest));
+  if(stats_request_msg == NULL)
+    goto error;
+  protocol__flex_stats_request__init(stats_request_msg);
+
+  if (flexran_create_header(xid, PROTOCOL__FLEX_TYPE__FLPT_STATS_REQUEST, &header) != 0)
+    goto error;
+
+  stats_request_msg->header = header;
+
+  stats_request_msg->type = report_config->report_type;
+  stats_request_msg->has_type = 1;
+
+  switch (report_config->report_type) {
+  case PROTOCOL__FLEX_STATS_TYPE__FLST_COMPLETE_STATS:
+    stats_request_msg->body_case =  PROTOCOL__FLEX_STATS_REQUEST__BODY_COMPLETE_STATS_REQUEST;
+    Protocol__FlexCompleteStatsRequest *complete_stats;
+    complete_stats = malloc(sizeof(Protocol__FlexCompleteStatsRequest));
+    if(complete_stats == NULL)
+      goto error;
+    protocol__flex_complete_stats_request__init(complete_stats);
+    complete_stats->report_frequency = report_config->report_frequency;
+    complete_stats->has_report_frequency = 1;
+    complete_stats->sf = report_config->period;
+    complete_stats->has_sf = 1;
+    complete_stats->has_cell_report_flags = 1;
+    complete_stats->has_ue_report_flags = 1;
+    if (report_config->config->nr_cc > 0) {
+      complete_stats->cell_report_flags = report_config->config->cc_report_type[0].cc_report_flags;
+    }
+    if (report_config->config->nr_ue > 0) {
+      complete_stats->ue_report_flags = report_config->config->ue_report_type[0].ue_report_flags;
+    }
+    stats_request_msg->complete_stats_request = complete_stats;
+    break;
+  case  PROTOCOL__FLEX_STATS_TYPE__FLST_CELL_STATS:
+    stats_request_msg->body_case = PROTOCOL__FLEX_STATS_REQUEST__BODY_CELL_STATS_REQUEST;
+     Protocol__FlexCellStatsRequest *cell_stats;
+     cell_stats = malloc(sizeof(Protocol__FlexCellStatsRequest));
+    if(cell_stats == NULL)
+      goto error;
+    protocol__flex_cell_stats_request__init(cell_stats);
+    cell_stats->n_cell = report_config->config->nr_cc;
+    cell_stats->has_flags = 1;
+    if (cell_stats->n_cell > 0) {
+      uint32_t *cells;
+      cells = (uint32_t *) malloc(sizeof(uint32_t)*cell_stats->n_cell);
+      for (i = 0; i < cell_stats->n_cell; i++) {
+  cells[i] = report_config->config->cc_report_type[i].cc_id;
+      }
+      cell_stats->cell = cells;
+      cell_stats->flags = report_config->config->cc_report_type[i].cc_report_flags;
+    }
+    stats_request_msg->cell_stats_request = cell_stats;
+    break;
+  case PROTOCOL__FLEX_STATS_TYPE__FLST_UE_STATS:
+    stats_request_msg->body_case = PROTOCOL__FLEX_STATS_REQUEST__BODY_UE_STATS_REQUEST;
+     Protocol__FlexUeStatsRequest *ue_stats;
+     ue_stats = malloc(sizeof(Protocol__FlexUeStatsRequest));
+    if(ue_stats == NULL)
+      goto error;
+    protocol__flex_ue_stats_request__init(ue_stats);
+    ue_stats->n_rnti = report_config->config->nr_ue;
+    ue_stats->has_flags = 1;
+    if (ue_stats->n_rnti > 0) {
+      uint32_t *ues;
+      ues = (uint32_t *) malloc(sizeof(uint32_t)*ue_stats->n_rnti);
+      for (i = 0; i < ue_stats->n_rnti; i++) {
+  ues[i] = report_config->config->ue_report_type[i].ue_rnti;
+      }
+      ue_stats->rnti = ues;
+      ue_stats->flags = report_config->config->ue_report_type[i].ue_report_flags;
+    }
+    stats_request_msg->ue_stats_request = ue_stats;
+    break;
+  default:
+    goto error;
+  }
+  *msg = malloc(sizeof(Protocol__FlexranMessage));
+  if(*msg == NULL)
+    goto error;
+  protocol__flexran_message__init(*msg);
+  (*msg)->msg_case = PROTOCOL__FLEXRAN_MESSAGE__MSG_STATS_REQUEST_MSG;
+  (*msg)->msg_dir = PROTOCOL__FLEXRAN_DIRECTION__INITIATING_MESSAGE;
+  (*msg)->stats_request_msg = stats_request_msg;
+  return 0;
+
+ error:
+  // TODO: Need to make proper error handling
+  if (header != NULL)
+    free(header);
+  if (stats_request_msg != NULL)
+    free(stats_request_msg);
+  if(*msg != NULL)
+    free(*msg);
+  //LOG_E(MAC, "%s: an error occured\n", __FUNCTION__);
+  return -1;
+}
+
+int flexran_agent_destroy_stats_request(Protocol__FlexranMessage *msg) {
+   if(msg->msg_case != PROTOCOL__FLEXRAN_MESSAGE__MSG_STATS_REQUEST_MSG)
+    goto error;
+  free(msg->stats_request_msg->header);
+  if (msg->stats_request_msg->body_case == PROTOCOL__FLEX_STATS_REQUEST__BODY_CELL_STATS_REQUEST) {
+    free(msg->stats_request_msg->cell_stats_request->cell);
+  }
+  if (msg->stats_request_msg->body_case == PROTOCOL__FLEX_STATS_REQUEST__BODY_UE_STATS_REQUEST) {
+    free(msg->stats_request_msg->ue_stats_request->rnti);
+  }
+  free(msg->stats_request_msg);
+  free(msg);
+  return 0;
+
+ error:
+  //LOG_E(MAC, "%s: an error occured\n", __FUNCTION__);
+  return -1;
+}
+
+/*
+  Top Level Update 
+ */
+
+void flexran_agent_send_update_stats(mid_t mod_id) {
+
+  Protocol__FlexranMessage *current_report = NULL;
+  void *data;
+  int size;
+  err_code_t err_code;
+  int priority = 0;
+  
+  if (pthread_mutex_lock(stats_context[mod_id].mutex)) {
+    goto error;
+  }
+
+  if (stats_context[mod_id].cont_update == 1) {
+  
+    /*Create a fresh report with the required flags*/
+    err_code = flexran_agent_handle_stats(mod_id, (void *) stats_context[mod_id].stats_req, &current_report);
+    if (err_code < 0) {
+      goto error;
+    }
+  }
+  /* /\*TODO:Check if a previous reports exists and if yes, generate a report */
+  /*  *that is the diff between the old and the new report, */
+  /*  *respecting the thresholds. Otherwise send the new report*\/ */
+  /* if (stats_context[mod_id].prev_stats_reply != NULL) { */
+
+  /*   msg = flexran_agent_generate_diff_mac_stats_report(current_report, stats_context[mod_id].prev_stats_reply); */
+
+  /*   /\*Destroy the old stats*\/ */
+  /*    flexran_agent_destroy_flexran_message(stats_context[mod_id].prev_stats_reply); */
+  /* } */
+  /* /\*Use the current report for future comparissons*\/ */
+  /* stats_context[mod_id].prev_stats_reply = current_report; */
+
+
+  if (pthread_mutex_unlock(stats_context[mod_id].mutex)) {
+    goto error;
+  }
+
+  if (current_report != NULL){
+    data=flexran_agent_pack_message(current_report, &size);
+    /*Send any stats updates using the MAC channel of the eNB*/
+    if (flexran_agent_msg_send(mod_id, FLEXRAN_AGENT_MAC, data, size, priority)) {
+      err_code = PROTOCOL__FLEXRAN_ERR__MSG_ENQUEUING;
+      goto error;
+    }
+
+    LOG_D(FLEXRAN_AGENT,"sent message with size %d\n", size);
+    return;
+  }
+ error:
+  LOG_D(FLEXRAN_AGENT, "Could not send sf trigger message\n");
+}
+
+err_code_t flexran_agent_disable_cont_stats_update(mid_t mod_id) {
+  /*Disable the continuous updates for the MAC*/
+  if (pthread_mutex_lock(stats_context[mod_id].mutex)) {
+    goto error;
+  }
+  stats_context[mod_id].cont_update = 0;
+  stats_context[mod_id].xid = 0;
+  if (stats_context[mod_id].stats_req != NULL) {
+    flexran_agent_destroy_flexran_message(stats_context[mod_id].stats_req);
+  }
+  if (stats_context[mod_id].prev_stats_reply != NULL) {
+    flexran_agent_destroy_flexran_message(stats_context[mod_id].prev_stats_reply);
+  }
+  if (pthread_mutex_unlock(stats_context[mod_id].mutex)) {
+    goto error;
+  }
+  return 0;
+
+ error:
+  LOG_E(FLEXRAN_AGENT, "stats_context for eNB %d is not initialized\n", mod_id);
+  return -1;
+
+}
+
+err_code_t flexran_agent_enable_cont_stats_update(mid_t mod_id,
+                  xid_t xid, stats_request_config_t *stats_req) {
+  
+  if (pthread_mutex_lock(stats_context[mod_id].mutex)) {
+    goto error;
+  }
+
+  Protocol__FlexranMessage *req_msg;
+
+  flexran_agent_stats_request(mod_id, xid, stats_req, &req_msg);
+  stats_context[mod_id].stats_req = req_msg;
+  stats_context[mod_id].prev_stats_reply = NULL;
+
+  stats_context[mod_id].cont_update = 1;
+  stats_context[mod_id].xid = xid;
+
+  if (pthread_mutex_unlock(stats_context[mod_id].mutex)) {
+    goto error;
+  }
+  return 0;
+
+ error:
+  LOG_E(FLEXRAN_AGENT, "stats_context for eNB %d is not initialized\n", mod_id);
+  return -1;
+}
+
+
+err_code_t flexran_agent_init_cont_stats_update(mid_t mod_id) {
+
+  
+  /*Initially the continuous update is set to false*/
+  stats_context[mod_id].cont_update = 0;
+  stats_context[mod_id].is_initialized = 1;
+  stats_context[mod_id].stats_req = NULL;
+  stats_context[mod_id].prev_stats_reply = NULL;
+  stats_context[mod_id].mutex = calloc(1, sizeof(pthread_mutex_t));
+  if (stats_context[mod_id].mutex == NULL)
+    goto error;
+  if (pthread_mutex_init(stats_context[mod_id].mutex, NULL))
+    goto error;
+
+  return 0;
+
+ error:
+  return -1;
+}
+
+err_code_t flexran_agent_destroy_cont_stats_update(mid_t mod_id) {
+  
+  stats_context[mod_id].cont_update = 0;
+  stats_context[mod_id].is_initialized = 0;
+  flexran_agent_destroy_flexran_message(stats_context[mod_id].stats_req);
+  flexran_agent_destroy_flexran_message(stats_context[mod_id].prev_stats_reply);
+  free(stats_context[mod_id].mutex);
+
+  // mac_agent_registered[mod_id] = 0;
+  return 1;
+}
diff --git a/openair2/ENB_APP/flexran_agent_net_comm.c b/openair2/ENB_APP/flexran_agent_net_comm.c
index e6442512095963885e6361f7a3c7595d7dd0b9b9..6971c2975048fae72be383fa2a9ab38d00fe7579 100644
--- a/openair2/ENB_APP/flexran_agent_net_comm.c
+++ b/openair2/ENB_APP/flexran_agent_net_comm.c
@@ -118,7 +118,7 @@ int flexran_agent_create_channel(void *channel_info,
   /*element should be a real pointer*/
   RB_INSERT(flexran_agent_channel_map, &channel_instance.flexran_agent_head, channel); 
   
-  LOG_I(FLEXRAN_AGENT,"Created a new channel with id 0x%lx\n", channel->channel_id);
+  LOG_I(FLEXRAN_AGENT,"Created a new channel with id %d \n", channel->channel_id);
  
   return channel_id; 
 }
@@ -141,9 +141,9 @@ int flexran_agent_destroy_channel(int channel_id) {
   for (i = 0; i < NUM_MAX_ENB; i++) {
     for (j = 0; j < FLEXRAN_AGENT_MAX; j++) {
       if (agent_channel[i][j] != NULL) {
-	if (agent_channel[i][j]->channel_id == e->channel_id) {
-	  agent_channel[i][j] == NULL;
-	}
+        if (agent_channel[i][j]->channel_id == e->channel_id) {
+            free(agent_channel[i][j]);
+        }
       }
     }
   }
@@ -164,7 +164,9 @@ err_code_t flexran_agent_init_channel_container(void) {
   
   for (i = 0; i < NUM_MAX_ENB; i++) {
     for (j = 0; j < FLEXRAN_AGENT_MAX; j++) {
-    agent_channel[i][j] == NULL;
+      agent_channel[i][j] = malloc(sizeof(flexran_agent_channel_t));
+      if (!agent_channel[i][j])
+        return -1;
     }
   }
 
diff --git a/openair2/ENB_APP/flexran_agent_ran_api.c b/openair2/ENB_APP/flexran_agent_ran_api.c
new file mode 100644
index 0000000000000000000000000000000000000000..16462b4d404a92d022d9066535904efab586257b
--- /dev/null
+++ b/openair2/ENB_APP/flexran_agent_ran_api.c
@@ -0,0 +1,1425 @@
+/*
+ * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The OpenAirInterface Software Alliance licenses this file to You under
+ * the OAI Public License, Version 1.0  (the "License"); you may not use this file
+ * except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.openairinterface.org/?page_id=698
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *-------------------------------------------------------------------------------
+ * For more information about the OpenAirInterface (OAI) Software Alliance:
+ *      contact@openairinterface.org
+ */ 
+
+/*! \file flexran_agent_ran_api.c
+ * \brief FlexRAN RAN API abstraction 
+ * \author N. Nikaein, X. Foukas and S. SHARIAT BAGHERI
+ * \date 2017
+ * \version 0.1
+ */
+
+#include "flexran_agent_ran_api.h"
+
+
+/*
+ *  generic info from RAN
+ */
+
+
+
+void * enb[NUM_MAX_ENB];
+void * enb_ue[NUM_MAX_ENB];
+void * enb_rrc[NUM_MAX_ENB];
+Enb_properties_array_t* enb_properties;
+
+void flexran_set_enb_vars(mid_t mod_id, ran_name_t ran){
+
+  switch (ran){
+  case RAN_LTE_OAI :
+    enb_properties = enb_config_get();
+    if(eNB_mac_inst == NULL){
+      enb[mod_id] = NULL;
+      enb_ue[mod_id] = NULL;
+      enb_rrc[mod_id] = NULL;
+    }else{
+      enb[mod_id] =  (void *)&eNB_mac_inst[mod_id];
+      enb_ue[mod_id] = (void *)&eNB_mac_inst[mod_id].UE_list;
+      enb_rrc[mod_id] = (void *)&eNB_rrc_inst[mod_id];
+    }
+    break;
+  default :
+    goto error;
+  }
+
+  return; 
+
+ error:
+  LOG_E(FLEXRAN_AGENT, "unknown RAN name %d\n", ran);
+}
+
+static int mac_xface_not_ready(void)
+{
+  if (mac_xface == NULL) {
+    return 1;
+  }
+  else {
+    //printf("max_xface %p %d \n", mac_xface, mac_xface->active);
+    return 0;// !mac_xface->active;
+  }
+}
+
+static int eNB_rrc_inst_not_ready(void)
+{
+  if (NULL == eNB_rrc_inst) {
+    return 1;
+  }
+  else {
+    return 0;
+  }
+}
+
+int flexran_get_current_time_ms (mid_t mod_id, int subframe_flag){
+  if (enb[mod_id] == NULL) return 0;
+  if (subframe_flag == 1){
+    return ((eNB_MAC_INST *)enb[mod_id])->frame*10 + ((eNB_MAC_INST *)enb[mod_id])->subframe;
+  }else {
+    return ((eNB_MAC_INST *)enb[mod_id])->frame*10;
+  }
+   
+}
+
+unsigned int flexran_get_current_frame (mid_t mod_id) {
+  if (enb[mod_id] == NULL) return 0;
+  //  #warning "SFN will not be in [0-1023] when oaisim is used"
+  return ((eNB_MAC_INST *)enb[mod_id])->frame;
+  
+}
+
+unsigned int flexran_get_current_system_frame_num(mid_t mod_id) {
+  return (flexran_get_current_frame(mod_id) %1024);
+}
+
+unsigned int flexran_get_current_subframe (mid_t mod_id) {
+  if (enb[mod_id] == NULL) return 0;
+  return ((eNB_MAC_INST *)enb[mod_id])->subframe;
+  
+}
+
+uint16_t flexran_get_sfn_sf (mid_t mod_id) {
+  
+  frame_t frame;
+  sub_frame_t subframe;
+  uint16_t sfn_sf, frame_mask, sf_mask;
+  
+  frame = (frame_t) flexran_get_current_system_frame_num(mod_id);
+  subframe = (sub_frame_t) flexran_get_current_subframe(mod_id);
+  frame_mask = ((1<<12) - 1);
+  sf_mask = ((1<<4) - 1);
+  sfn_sf = (subframe & sf_mask) | ((frame & frame_mask) << 4);
+  
+  return sfn_sf;
+}
+
+uint16_t flexran_get_future_sfn_sf (mid_t mod_id, int ahead_of_time) {
+  
+  frame_t frame;
+  sub_frame_t subframe;
+  uint16_t sfn_sf, frame_mask, sf_mask;
+  
+  frame = (frame_t) flexran_get_current_system_frame_num(mod_id);
+  subframe = (sub_frame_t) flexran_get_current_subframe(mod_id);
+
+  subframe = ((subframe + ahead_of_time) % 10);
+  
+  if (subframe < flexran_get_current_subframe(mod_id)) {
+    frame = (frame + 1) % 1024;
+  }
+  
+  int additional_frames = ahead_of_time / 10;
+  frame = (frame + additional_frames) % 1024;
+  
+  frame_mask = ((1<<12) - 1);
+  sf_mask = ((1<<4) - 1);
+  sfn_sf = (subframe & sf_mask) | ((frame & frame_mask) << 4);
+  
+  return sfn_sf;
+}
+
+int flexran_get_num_ues (mid_t mod_id){
+  if (enb_ue[mod_id] == NULL) return 0;
+  return  ((UE_list_t *)enb_ue[mod_id])->num_UEs;
+}
+
+int flexran_get_ue_crnti (mid_t mod_id, mid_t ue_id) {
+
+  return  UE_RNTI(mod_id, ue_id);
+}
+
+int flexran_get_ue_bsr (mid_t mod_id, mid_t ue_id, lcid_t lcid) {
+  if (enb_ue[mod_id] == NULL) return 0;
+  return ((UE_list_t *)enb_ue[mod_id])->UE_template[UE_PCCID(mod_id,ue_id)][ue_id].bsr_info[lcid];
+}
+
+int flexran_get_ue_phr (mid_t mod_id, mid_t ue_id) {
+  if (enb_ue[mod_id] == NULL) return 0;
+  return ((UE_list_t *)enb_ue[mod_id])->UE_template[UE_PCCID(mod_id,ue_id)][ue_id].phr_info;
+}
+
+int flexran_get_ue_wcqi (mid_t mod_id, mid_t ue_id) {
+  LTE_eNB_UE_stats     *eNB_UE_stats     = NULL;
+  if (mac_xface_not_ready()) return 0 ;
+
+  eNB_UE_stats = mac_xface->get_eNB_UE_stats(mod_id, 0, UE_RNTI(mod_id, ue_id));
+  return eNB_UE_stats->DL_cqi[0];
+
+  //  return ((UE_list_t *)enb_ue[mod_id])->eNB_UE_stats[UE_PCCID(mod_id,ue_id)][ue_id].dl_cqi;
+}
+
+int flexran_get_tx_queue_size(mid_t mod_id, mid_t ue_id, logical_chan_id_t channel_id) {
+  rnti_t rnti = flexran_get_ue_crnti(mod_id,ue_id);
+  uint16_t frame = (uint16_t) flexran_get_current_frame(mod_id);
+  uint16_t subframe = (uint16_t) flexran_get_current_subframe(mod_id);
+  mac_rlc_status_resp_t rlc_status = mac_rlc_status_ind(mod_id,rnti, mod_id, frame, subframe, ENB_FLAG_YES,MBMS_FLAG_NO, channel_id, 0);
+  return rlc_status.bytes_in_buffer;
+}
+
+
+int flexran_get_num_pdus_buffer(mid_t mod_id, mid_t ue_id, logical_chan_id_t channel_id) {
+  rnti_t rnti = flexran_get_ue_crnti(mod_id,ue_id);
+  uint16_t frame = (uint16_t) flexran_get_current_frame(mod_id);
+  uint16_t subframe = (uint16_t) flexran_get_current_subframe(mod_id);
+  mac_rlc_status_resp_t rlc_status = mac_rlc_status_ind(mod_id,rnti, mod_id, frame, subframe, ENB_FLAG_YES,MBMS_FLAG_NO, channel_id, 0);
+  return rlc_status.pdus_in_buffer;
+}
+
+
+
+int flexran_get_hol_delay(mid_t mod_id, mid_t ue_id, logical_chan_id_t channel_id) {
+  rnti_t rnti = flexran_get_ue_crnti(mod_id,ue_id);
+  uint16_t frame = (uint16_t) flexran_get_current_frame(mod_id);
+  uint16_t subframe = (uint16_t) flexran_get_current_subframe(mod_id);
+  mac_rlc_status_resp_t rlc_status = mac_rlc_status_ind(mod_id, rnti, mod_id, frame, subframe, ENB_FLAG_YES, MBMS_FLAG_NO, channel_id, 0);
+  return rlc_status.head_sdu_creation_time;
+}
+
+short flexran_get_TA(mid_t mod_id, mid_t ue_id, int CC_id) {
+  
+  // UE_list_t *UE_list=&eNB_mac_inst[mod_id].UE_list;
+  int rnti;
+
+  rnti = flexran_get_ue_crnti(mod_id, ue_id);
+  if (mac_xface_not_ready()) return 0 ;
+
+  LTE_eNB_UE_stats		*eNB_UE_stats = mac_xface->get_eNB_UE_stats(mod_id, CC_id, rnti);
+  //ue_sched_ctl->ta_timer		      = 20;	// wait 20 subframes before taking TA measurement from PHY                                         
+  switch (flexran_get_N_RB_DL(mod_id, CC_id)) {
+  case 6:
+    return eNB_UE_stats->timing_advance_update;
+  case 15:
+    return eNB_UE_stats->timing_advance_update/2;
+  case 25:
+    return eNB_UE_stats->timing_advance_update/4;
+  case 50:
+    return eNB_UE_stats->timing_advance_update/8;
+  case 75:
+    return eNB_UE_stats->timing_advance_update/12;
+  case 100:
+    if (flexran_get_threequarter_fs(mod_id, CC_id) == 0) {
+      return eNB_UE_stats->timing_advance_update/16;
+    } else {
+      return eNB_UE_stats->timing_advance_update/12;
+    }
+  default:
+    return 0;
+  }
+}
+
+int flexran_get_ue_pmi(mid_t mod_id){
+
+  /*Xenofon to check this*/
+
+  return 0;
+}
+
+
+void flexran_update_TA(mid_t mod_id, mid_t ue_id, int CC_id) {
+  
+  UE_list_t *UE_list=&eNB_mac_inst[mod_id].UE_list;
+  UE_sched_ctrl *ue_sched_ctl = &UE_list->UE_sched_ctrl[ue_id];
+
+  if (ue_sched_ctl->ta_timer == 0) {
+    
+    // WE SHOULD PROTECT the eNB_UE_stats with a mutex here ...                                                                         
+    //    LTE_eNB_UE_stats		*eNB_UE_stats = mac_xface->get_eNB_UE_stats(mod_id, CC_id, rnti);
+    //ue_sched_ctl->ta_timer		      = 20;	// wait 20 subframes before taking TA measurement from PHY                                         
+    ue_sched_ctl->ta_update = flexran_get_TA(mod_id, ue_id, CC_id);
+
+    // clear the update in case PHY does not have a new measurement after timer expiry                                               
+    //    eNB_UE_stats->timing_advance_update	      = 0;
+  } else {
+    ue_sched_ctl->ta_timer--;
+    ue_sched_ctl->ta_update		      = 0;	// don't trigger a timing advance command      
+  }
+}
+
+int flexran_get_MAC_CE_bitmap_TA(mid_t mod_id, mid_t ue_id,int CC_id) {
+  
+  // UE_list_t			*UE_list      = &eNB_mac_inst[mod_id].UE_list;
+
+  rnti_t rnti = flexran_get_ue_crnti(mod_id,ue_id);
+  if (mac_xface_not_ready()) return 0 ;
+
+  LTE_eNB_UE_stats *eNB_UE_stats = mac_xface->get_eNB_UE_stats(mod_id,CC_id,rnti);
+  
+  if (eNB_UE_stats == NULL) {
+    return 0;
+  }
+
+  if (flexran_get_TA(mod_id, ue_id, CC_id) != 0) {
+    return PROTOCOL__FLEX_CE_TYPE__FLPCET_TA;
+  } else {
+    return 0;
+  }
+
+}
+
+int flexran_get_active_CC(mid_t mod_id, mid_t ue_id) {
+  if (enb_ue[mod_id] == NULL) return 0;
+	return ((UE_list_t *)enb_ue[mod_id])->numactiveCCs[ue_id];
+}
+
+int flexran_get_current_RI(mid_t mod_id, mid_t ue_id, int CC_id) {
+	LTE_eNB_UE_stats	*eNB_UE_stats = NULL;
+	if (mac_xface_not_ready()) return 0 ;
+
+	rnti_t			 rnti	      = flexran_get_ue_crnti(mod_id,ue_id);
+
+	eNB_UE_stats			      = mac_xface->get_eNB_UE_stats(mod_id,CC_id,rnti);
+	
+	if (eNB_UE_stats == NULL) {
+	  return 0;
+	}
+
+	return eNB_UE_stats[CC_id].rank;
+}
+
+int flexran_get_tpc(mid_t mod_id, mid_t ue_id) {
+	LTE_eNB_UE_stats	*eNB_UE_stats = NULL;
+	int32_t			 normalized_rx_power, target_rx_power;
+	int			 tpc	      = 1;
+
+	int			 pCCid	      = UE_PCCID(mod_id,ue_id);
+	rnti_t			 rnti	      = flexran_get_ue_crnti(mod_id,ue_id);
+	if (mac_xface_not_ready()) return 0 ;
+
+	eNB_UE_stats = mac_xface->get_eNB_UE_stats(mod_id, pCCid, rnti);
+
+	target_rx_power = mac_xface->get_target_pusch_rx_power(mod_id,pCCid);
+
+	if (eNB_UE_stats == NULL) {
+	  normalized_rx_power = target_rx_power;
+	} else if (eNB_UE_stats->UL_rssi != NULL) {
+	  normalized_rx_power = eNB_UE_stats->UL_rssi[0];
+	} else {
+	  normalized_rx_power = target_rx_power;
+	}
+
+	if (normalized_rx_power>(target_rx_power+1)) {
+		tpc = 0;	//-1
+	} else if (normalized_rx_power<(target_rx_power-1)) {
+		tpc = 2;	//+1
+	} else {
+		tpc = 1;	//0
+	}
+	return tpc;
+}
+
+int flexran_get_harq(const mid_t mod_id, 
+		     const uint8_t CC_id, 
+		     const mid_t ue_id, 
+		     const int frame, 
+		     const uint8_t subframe, 
+		     uint8_t *pid, 
+		     uint8_t *round,
+         const uint8_t harq_flag)	{ //flag_id_status = 0 then id, else status
+	/*TODO: Add int TB in function parameters to get the status of the second TB. This can be done to by editing in
+	 * get_ue_active_harq_pid function in line 272 file: phy_procedures_lte_eNB.c to add
+	 * DLSCH_ptr = PHY_vars_eNB_g[Mod_id][CC_id]->dlsch_eNB[(uint32_t)UE_id][1];*/
+
+  uint8_t harq_pid;
+  uint8_t harq_round;
+  
+  if (mac_xface_not_ready()) return 0 ;
+
+  uint16_t rnti = flexran_get_ue_crnti(mod_id,ue_id);
+  if (harq_flag == openair_harq_DL){
+
+      mac_xface->get_ue_active_harq_pid(mod_id,CC_id,rnti,frame,subframe,&harq_pid,&harq_round,openair_harq_DL);
+
+   } else if (harq_flag == openair_harq_UL){
+
+     mac_xface->get_ue_active_harq_pid(mod_id,CC_id,rnti,frame,subframe,&harq_pid,round,openair_harq_UL);    
+   }
+   else {
+
+      LOG_W(FLEXRAN_AGENT,"harq_flag is not recongnized");
+   }
+
+
+  *pid = harq_pid;
+  *round = harq_round;
+  /* if (round > 0) { */
+  /*   *status = 1; */
+  /* } else { */
+  /*   *status = 0; */
+  /* } */
+
+  /* return 0; */
+  return *round;
+}
+
+int flexran_get_p0_pucch_dbm(mid_t mod_id, mid_t ue_id, int CC_id) {
+  LTE_eNB_UE_stats *eNB_UE_stats = NULL;
+  uint32_t rnti = flexran_get_ue_crnti(mod_id,ue_id);
+  if (mac_xface_not_ready()) return 0 ;
+
+  eNB_UE_stats =  mac_xface->get_eNB_UE_stats(mod_id, CC_id, rnti);
+  
+  if (eNB_UE_stats == NULL) {
+    return -1;
+  }
+  
+  //	if(eNB_UE_stats->Po_PUCCH_update == 1) {
+  return eNB_UE_stats->Po_PUCCH_dBm;
+  //}
+  //else
+  //  return -1;
+}
+
+int flexran_get_p0_nominal_pucch(mid_t mod_id, int CC_id) {
+  if (mac_xface_not_ready()) return 0 ;
+
+  int32_t pucch_rx_received = mac_xface->get_target_pucch_rx_power(mod_id, CC_id);
+  return pucch_rx_received;
+}
+
+int flexran_get_p0_pucch_status(mid_t mod_id, mid_t ue_id, int CC_id) {
+  if (mac_xface_not_ready()) return 0 ;
+
+  LTE_eNB_UE_stats *eNB_UE_stats = NULL;
+  uint32_t rnti = flexran_get_ue_crnti(mod_id,ue_id);
+  
+  eNB_UE_stats =  mac_xface->get_eNB_UE_stats(mod_id, CC_id, rnti);
+  return eNB_UE_stats->Po_PUCCH_update;
+}
+
+int flexran_update_p0_pucch(mid_t mod_id, mid_t ue_id, int CC_id) {
+  if (mac_xface_not_ready()) return 0 ;
+
+  LTE_eNB_UE_stats *eNB_UE_stats = NULL;
+  uint32_t rnti = flexran_get_ue_crnti(mod_id,ue_id);
+  
+  eNB_UE_stats =  mac_xface->get_eNB_UE_stats(mod_id, CC_id, rnti);
+  eNB_UE_stats->Po_PUCCH_update = 0;
+  
+  return 0;
+}
+
+
+/*
+ * ************************************
+ * Get Messages for eNB Configuration Reply
+ * ************************************
+ */
+int flexran_get_threequarter_fs(mid_t mod_id, int CC_id) {
+	LTE_DL_FRAME_PARMS   *frame_parms;
+	if (mac_xface_not_ready()) return 0 ;
+
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	return frame_parms->threequarter_fs;
+}
+
+
+int flexran_get_hopping_offset(mid_t mod_id, int CC_id) {
+	LTE_DL_FRAME_PARMS   *frame_parms;
+	if (mac_xface_not_ready()) return 0 ;
+
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	return frame_parms->pusch_config_common.pusch_HoppingOffset;
+}
+
+int flexran_get_hopping_mode(mid_t mod_id, int CC_id) {
+	LTE_DL_FRAME_PARMS   *frame_parms;
+	if (mac_xface_not_ready()) return 0 ;
+
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	return frame_parms->pusch_config_common.hoppingMode;
+}
+
+int flexran_get_n_SB(mid_t mod_id, int CC_id) {
+	LTE_DL_FRAME_PARMS   *frame_parms;
+	if (mac_xface_not_ready()) return 0 ;
+
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	return frame_parms->pusch_config_common.n_SB;
+}
+
+int flexran_get_enable64QAM(mid_t mod_id, int CC_id) {
+	LTE_DL_FRAME_PARMS   *frame_parms;
+	if (mac_xface_not_ready()) return 0 ;
+
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	return frame_parms->pusch_config_common.enable64QAM;
+}
+
+int flexran_get_phich_duration(mid_t mod_id, int CC_id) {
+	LTE_DL_FRAME_PARMS   *frame_parms;
+	if (mac_xface_not_ready()) return 0 ;
+
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	return frame_parms->phich_config_common.phich_duration;
+}
+
+int flexran_get_phich_resource(mid_t mod_id, int CC_id) {
+	LTE_DL_FRAME_PARMS   *frame_parms;
+	if (mac_xface_not_ready()) return 0 ;
+
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	if(frame_parms->phich_config_common.phich_resource == oneSixth)
+		return 0;
+	else if(frame_parms->phich_config_common.phich_resource == half)
+		return 1;
+	else if(frame_parms->phich_config_common.phich_resource == one)
+		return 2;
+	else if(frame_parms->phich_config_common.phich_resource == two)
+		return 3;
+
+	return -1;
+}
+
+int flexran_get_n1pucch_an(mid_t mod_id, int CC_id) {
+	LTE_DL_FRAME_PARMS   *frame_parms;
+	if (mac_xface_not_ready()) return 0 ;
+
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	return frame_parms->pucch_config_common.n1PUCCH_AN;
+}
+
+int flexran_get_nRB_CQI(mid_t mod_id, int CC_id) {
+	LTE_DL_FRAME_PARMS   *frame_parms;
+	if (mac_xface_not_ready()) return 0 ;
+
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	return frame_parms->pucch_config_common.nRB_CQI;
+}
+
+int flexran_get_deltaPUCCH_Shift(mid_t mod_id, int CC_id) {
+	LTE_DL_FRAME_PARMS   *frame_parms;
+	if (mac_xface_not_ready()) return 0 ;
+
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	return frame_parms->pucch_config_common.deltaPUCCH_Shift;
+}
+
+int flexran_get_prach_ConfigIndex(mid_t mod_id, int CC_id) {
+	LTE_DL_FRAME_PARMS   *frame_parms;
+	if (mac_xface_not_ready()) return 0 ;
+
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	return frame_parms->prach_config_common.prach_ConfigInfo.prach_ConfigIndex;
+}
+
+int flexran_get_prach_FreqOffset(mid_t mod_id, int CC_id) {
+	LTE_DL_FRAME_PARMS   *frame_parms;
+	if (mac_xface_not_ready()) return 0 ;
+
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	return frame_parms->prach_config_common.prach_ConfigInfo.prach_FreqOffset;
+}
+
+int flexran_get_maxHARQ_Msg3Tx(mid_t mod_id, int CC_id) {
+	LTE_DL_FRAME_PARMS   *frame_parms;
+	if (mac_xface_not_ready()) return 0 ;
+
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	return frame_parms->maxHARQ_Msg3Tx;
+}
+
+int flexran_get_ul_cyclic_prefix_length(mid_t mod_id, int CC_id) {
+	LTE_DL_FRAME_PARMS   *frame_parms;
+	if (mac_xface_not_ready()) return 0 ;
+
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	return frame_parms->Ncp_UL;
+}
+
+int flexran_get_dl_cyclic_prefix_length(mid_t mod_id, int CC_id) {
+	LTE_DL_FRAME_PARMS   *frame_parms;
+	if (mac_xface_not_ready()) return 0 ;
+	
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	return frame_parms->Ncp;
+}
+
+int flexran_get_cell_id(mid_t mod_id, int CC_id) {
+	LTE_DL_FRAME_PARMS   *frame_parms;
+
+	if (mac_xface_not_ready()) return 0;
+
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	return frame_parms->Nid_cell;
+}
+
+int flexran_get_srs_BandwidthConfig(mid_t mod_id, int CC_id) {
+	LTE_DL_FRAME_PARMS   *frame_parms;
+	if (mac_xface_not_ready()) return 0 ;	
+	
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	return frame_parms->soundingrs_ul_config_common.srs_BandwidthConfig;
+}
+
+int flexran_get_srs_SubframeConfig(mid_t mod_id, int CC_id) {
+	LTE_DL_FRAME_PARMS   *frame_parms;
+	if (mac_xface_not_ready()) return 0 ;
+
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	return frame_parms->soundingrs_ul_config_common.srs_SubframeConfig;
+}
+
+int flexran_get_srs_MaxUpPts(mid_t mod_id, int CC_id) {
+	LTE_DL_FRAME_PARMS   *frame_parms;
+	if (mac_xface_not_ready()) return 0 ;
+
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	return frame_parms->soundingrs_ul_config_common.srs_MaxUpPts;
+}
+
+int flexran_get_N_RB_DL(mid_t mod_id, int CC_id) {
+	LTE_DL_FRAME_PARMS   *frame_parms;
+	if (mac_xface_not_ready()) return 0 ;
+
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	return frame_parms->N_RB_DL;
+}
+
+int flexran_get_N_RB_UL(mid_t mod_id, int CC_id) {
+	LTE_DL_FRAME_PARMS   *frame_parms;
+	if (mac_xface_not_ready()) return 0 ;
+
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	return frame_parms->N_RB_UL;
+}
+
+int flexran_get_N_RBG(mid_t mod_id, int CC_id) {
+  	LTE_DL_FRAME_PARMS   *frame_parms;
+	if (mac_xface_not_ready()) return 0 ;
+
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	return frame_parms->N_RBG;
+}
+
+int flexran_get_subframe_assignment(mid_t mod_id, int CC_id) {
+	LTE_DL_FRAME_PARMS   *frame_parms;
+	if (mac_xface_not_ready()) return 0 ;
+
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	return frame_parms->tdd_config;
+}
+
+int flexran_get_special_subframe_assignment(mid_t mod_id, int CC_id) {
+	LTE_DL_FRAME_PARMS   *frame_parms;
+	if (mac_xface_not_ready()) return 0 ;
+
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	return  (frame_parms == NULL)? 0:frame_parms->tdd_config_S;
+}
+
+int flexran_get_ra_ResponseWindowSize(mid_t mod_id, int CC_id) {
+  return enb_config_get()->properties[mod_id]->rach_raResponseWindowSize[CC_id];
+}
+
+int flexran_get_mac_ContentionResolutionTimer(mid_t mod_id, int CC_id) {
+  return enb_config_get()->properties[mod_id]->rach_macContentionResolutionTimer[CC_id];
+}
+
+int flexran_get_duplex_mode(mid_t mod_id, int CC_id) {
+	LTE_DL_FRAME_PARMS   *frame_parms;
+	if (mac_xface_not_ready()) return 0 ;
+
+	frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+	if (frame_parms == NULL) return -1;
+	if(frame_parms->frame_type == TDD)
+		return PROTOCOL__FLEX_DUPLEX_MODE__FLDM_TDD;
+	else if (frame_parms->frame_type == FDD)
+		return PROTOCOL__FLEX_DUPLEX_MODE__FLDM_FDD;
+
+	return -1;
+}
+
+long flexran_get_si_window_length(mid_t mod_id, int CC_id) {
+	return  ((eNB_RRC_INST *)enb_rrc[mod_id])->carrier[CC_id].sib1->si_WindowLength;
+}
+
+int flexran_get_sib1_length(mid_t mod_id, int CC_id) {
+	return  ((eNB_RRC_INST *)enb_rrc[mod_id])->carrier[CC_id].sizeof_SIB1;
+}
+
+int flexran_get_num_pdcch_symb(mid_t mod_id, int CC_id) {
+  /* TODO: This should return the number of PDCCH symbols initially used by the cell CC_id */
+  return 0;
+  //(PHY_vars_UE_g[mod_id][CC_id]->lte_ue_pdcch_vars[mod_id]->num_pdcch_symbols);
+}
+
+
+
+/*
+ * ************************************
+ * Get Messages for UE Configuration Reply
+ * ************************************
+ */
+
+
+int flexran_get_time_alignment_timer(mid_t mod_id, mid_t ue_id) {
+  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
+  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
+
+  if (eNB_rrc_inst_not_ready()) return -1;
+  
+  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
+  if(ue_context_p != NULL) {
+    if(ue_context_p->ue_context.mac_MainConfig != NULL) {
+      return ue_context_p->ue_context.mac_MainConfig->timeAlignmentTimerDedicated;
+    } else {
+      return -1;
+    }
+  } else {
+    return -1;
+  }
+}
+
+int flexran_get_meas_gap_config(mid_t mod_id, mid_t ue_id) {
+  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
+  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
+
+  if (eNB_rrc_inst_not_ready()) return -1;
+
+  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
+  if(ue_context_p != NULL) {
+    if(ue_context_p->ue_context.measGapConfig != NULL) {
+      if(ue_context_p->ue_context.measGapConfig->present == MeasGapConfig_PR_setup) {
+	if (ue_context_p->ue_context.measGapConfig->choice.setup.gapOffset.present == MeasGapConfig__setup__gapOffset_PR_gp0) {
+	  return PROTOCOL__FLEX_MEAS_GAP_CONFIG_PATTERN__FLMGCP_GP1;
+	} else if (ue_context_p->ue_context.measGapConfig->choice.setup.gapOffset.present == MeasGapConfig__setup__gapOffset_PR_gp1) {
+	  return PROTOCOL__FLEX_MEAS_GAP_CONFIG_PATTERN__FLMGCP_GP2;
+	} else {
+	  return PROTOCOL__FLEX_MEAS_GAP_CONFIG_PATTERN__FLMGCP_OFF;
+	}
+      }
+    }
+  }
+  return -1;
+}
+
+
+int flexran_get_meas_gap_config_offset(mid_t mod_id, mid_t ue_id) {
+  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
+  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
+
+  if (eNB_rrc_inst_not_ready()) return -1;
+  
+  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
+  
+  if(ue_context_p != NULL) {
+    if(ue_context_p->ue_context.measGapConfig != NULL){
+      if(ue_context_p->ue_context.measGapConfig->present == MeasGapConfig_PR_setup) {
+	if (ue_context_p->ue_context.measGapConfig->choice.setup.gapOffset.present == MeasGapConfig__setup__gapOffset_PR_gp0) {
+	  return ue_context_p->ue_context.measGapConfig->choice.setup.gapOffset.choice.gp0;
+	} else if (ue_context_p->ue_context.measGapConfig->choice.setup.gapOffset.present == MeasGapConfig__setup__gapOffset_PR_gp1) {
+	  return ue_context_p->ue_context.measGapConfig->choice.setup.gapOffset.choice.gp0;
+	} 
+      }
+    }
+  }
+  return -1;
+}
+
+
+int flexran_get_rrc_status(const mid_t mod_id,  const rnti_t  rntiP){
+
+  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
+
+  if (eNB_rrc_inst_not_ready()) return -1;
+
+  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
+
+  if (ue_context_p != NULL) {
+    return(ue_context_p->ue_context.Status);
+  } else {
+    return RRC_INACTIVE;
+  }
+
+}
+
+int flexran_get_ue_aggregated_max_bitrate_dl (mid_t mod_id, mid_t ue_id) {
+  if (enb_ue[mod_id] == NULL) return 0;
+	return ((UE_list_t *)enb_ue[mod_id])->UE_sched_ctrl[ue_id].ue_AggregatedMaximumBitrateDL;
+}
+
+int flexran_get_ue_aggregated_max_bitrate_ul (mid_t mod_id, mid_t ue_id) {
+  if (enb_ue[mod_id] == NULL) return 0;
+	return ((UE_list_t *)enb_ue[mod_id])->UE_sched_ctrl[ue_id].ue_AggregatedMaximumBitrateUL;
+}
+
+int flexran_get_half_duplex(mid_t ue_id) {
+  // TODO
+	//int halfduplex = 0;
+	//int bands_to_scan = ((UE_RRC_INST *)enb_ue_rrc[ue_id])->UECap->UE_EUTRA_Capability->rf_Parameters.supportedBandListEUTRA.list.count;
+	//for (int i =0; i < bands_to_scan; i++){
+		//if(((UE_RRC_INST *)enb_ue_rrc[ue_id])->UECap->UE_EUTRA_Capability->rf_Parameters.supportedBandListEUTRA.list.array[i]->halfDuplex > 0)
+		//	halfduplex = 1;
+	//}
+	//return halfduplex;
+  return 0;
+}
+
+int flexran_get_intra_sf_hopping(mid_t ue_id) {
+	//TODO:Get proper value
+	//temp = (((UE_RRC_INST *)enb_ue_rrc[ue_id])->UECap->UE_EUTRA_Capability->featureGroupIndicators->buf);
+	//return (0 & ( 1 << (31)));
+  return 0;
+}
+
+int flexran_get_type2_sb_1(mid_t ue_id) {
+	//TODO:Get proper value
+	//uint8_t temp = 0;
+	//temp = (((UE_RRC_INST *)enb_ue_rrc[ue_id])->UECap->UE_EUTRA_Capability->featureGroupIndicators->buf);
+	//return (temp & ( 1 << (11)));
+  return 0;
+}
+
+int flexran_get_ue_category(mid_t ue_id) {
+	//TODO:Get proper value
+	//return (((UE_RRC_INST *)enb_ue_rrc[ue_id])->UECap->UE_EUTRA_Capability->ue_Category);
+  return 0;
+}
+
+int flexran_get_res_alloc_type1(mid_t ue_id) {
+	//TODO:Get proper value
+	//uint8_t temp = 0;
+	//temp = (((UE_RRC_INST *)enb_ue_rrc[ue_id])->UECap->UE_EUTRA_Capability->featureGroupIndicators->buf);
+	//return (temp & ( 1 << (30)));
+  return 0;
+}
+
+int flexran_get_ue_transmission_mode(mid_t mod_id, mid_t ue_id) {
+  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
+  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
+
+  if (eNB_rrc_inst_not_ready()) return -1;
+  
+  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
+  
+  if(ue_context_p != NULL) {
+    if(ue_context_p->ue_context.physicalConfigDedicated != NULL){
+      return ue_context_p->ue_context.physicalConfigDedicated->antennaInfo->choice.explicitValue.transmissionMode;
+    } else {
+      return -1;
+    }
+  } else {
+    return -1;
+  }
+}
+
+int flexran_get_tti_bundling(mid_t mod_id, mid_t ue_id) {
+  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
+  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
+
+  if (eNB_rrc_inst_not_ready()) return -1;
+  
+  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
+  if(ue_context_p != NULL) {
+    if(ue_context_p->ue_context.mac_MainConfig != NULL){
+      return ue_context_p->ue_context.mac_MainConfig->ul_SCH_Config->ttiBundling;
+    } else {
+      return -1;
+    }
+  }
+  else {
+    return -1;
+  }
+}
+
+int flexran_get_maxHARQ_TX(mid_t mod_id, mid_t ue_id) {
+  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
+  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
+
+  if (eNB_rrc_inst_not_ready()) return -1;
+  
+  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
+  if(ue_context_p != NULL) {
+    if(ue_context_p->ue_context.mac_MainConfig != NULL){
+      return *ue_context_p->ue_context.mac_MainConfig->ul_SCH_Config->maxHARQ_Tx;
+    }
+  }
+  return -1;
+}
+
+int flexran_get_beta_offset_ack_index(mid_t mod_id, mid_t ue_id) {
+  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
+  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
+
+  if (eNB_rrc_inst_not_ready()) return -1;
+  
+  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
+  if(ue_context_p != NULL) {
+    if(ue_context_p->ue_context.physicalConfigDedicated != NULL){
+      return ue_context_p->ue_context.physicalConfigDedicated->pusch_ConfigDedicated->betaOffset_ACK_Index;
+    } else {
+      return -1;
+    } 
+  } else {
+    return -1;
+  }
+}
+
+int flexran_get_beta_offset_ri_index(mid_t mod_id, mid_t ue_id) {
+  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
+  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
+
+  if (eNB_rrc_inst_not_ready()) return -1;
+  
+  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
+  if(ue_context_p != NULL) {
+    if(ue_context_p->ue_context.physicalConfigDedicated != NULL){
+      return ue_context_p->ue_context.physicalConfigDedicated->pusch_ConfigDedicated->betaOffset_RI_Index;
+    } else {
+      return -1;
+    }
+  } else {
+    return -1;
+  }
+}
+
+int flexran_get_beta_offset_cqi_index(mid_t mod_id, mid_t ue_id) {
+  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
+  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
+
+  if (eNB_rrc_inst_not_ready()) return -1;
+  
+  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
+  if(ue_context_p != NULL) {
+    if(ue_context_p->ue_context.physicalConfigDedicated != NULL){
+      return ue_context_p->ue_context.physicalConfigDedicated->pusch_ConfigDedicated->betaOffset_CQI_Index;
+    } else {
+      return -1;
+    }
+  }
+  else {
+    return -1;
+  }
+}
+
+int flexran_get_simultaneous_ack_nack_cqi(mid_t mod_id, mid_t ue_id) {
+  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
+  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
+
+  if (eNB_rrc_inst_not_ready()) return -1;
+  
+  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
+  if(ue_context_p != NULL) {
+    if(ue_context_p->ue_context.physicalConfigDedicated != NULL){
+      if (ue_context_p->ue_context.physicalConfigDedicated->cqi_ReportConfig->cqi_ReportPeriodic != NULL) {
+	return ue_context_p->ue_context.physicalConfigDedicated->cqi_ReportConfig->cqi_ReportPeriodic->choice.setup.simultaneousAckNackAndCQI;
+      }
+    }
+  }
+  return -1;
+}
+
+int flexran_get_ack_nack_simultaneous_trans(mid_t mod_id,mid_t ue_id) {
+
+  if (eNB_rrc_inst_not_ready()) return -1;
+
+  return (&eNB_rrc_inst[mod_id])->carrier[0].sib2->radioResourceConfigCommon.soundingRS_UL_ConfigCommon.choice.setup.ackNackSRS_SimultaneousTransmission;
+}
+
+int flexran_get_aperiodic_cqi_rep_mode(mid_t mod_id,mid_t ue_id) {
+  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
+  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
+
+  if (eNB_rrc_inst_not_ready()) return -1;
+
+  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
+  
+  if(ue_context_p != NULL) {
+    if(ue_context_p->ue_context.physicalConfigDedicated != NULL){
+      return *ue_context_p->ue_context.physicalConfigDedicated->cqi_ReportConfig->cqi_ReportModeAperiodic;
+    }
+  }
+  return -1;
+}
+
+int flexran_get_tdd_ack_nack_feedback(mid_t mod_id, mid_t ue_id) {
+  // TODO: This needs fixing
+  return -1;
+
+  /* if (eNB_rrc_inst_not_ready()) return -1; */
+
+  /* struct rrc_eNB_ue_context_s* ue_context_p = NULL; */
+  /* uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id); */
+  
+  /* ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP); */
+  
+  /* if(ue_context_p != NULL) { */
+  /*   if(ue_context_p->ue_context.physicalConfigDedicated != NULL){ */
+  /*     return ue_context_p->ue_context.physicalConfigDedicated->pucch_ConfigDedicated->tdd_AckNackFeedbackMode; */
+  /*   } else { */
+  /*     return -1; */
+  /*   } */
+  /* } else { */
+  /*   return -1; */
+  /* } */
+}
+
+int flexran_get_ack_nack_repetition_factor(mid_t mod_id, mid_t ue_id) {
+  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
+  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
+
+  if (eNB_rrc_inst_not_ready()) return -1;
+  
+  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
+  if(ue_context_p != NULL) {
+    if(ue_context_p->ue_context.physicalConfigDedicated != NULL){
+      return ue_context_p->ue_context.physicalConfigDedicated->pucch_ConfigDedicated->ackNackRepetition.choice.setup.repetitionFactor;
+    } else {
+      return -1;
+    }
+  } else {
+    return -1;
+  }
+}
+
+int flexran_get_extended_bsr_size(mid_t mod_id, mid_t ue_id) {
+  //TODO: need to double check
+  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
+  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
+
+  if (eNB_rrc_inst_not_ready()) return -1;
+
+  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
+  if(ue_context_p != NULL) {
+    if(ue_context_p->ue_context.mac_MainConfig != NULL){
+      if(ue_context_p->ue_context.mac_MainConfig->ext2 != NULL){
+	long val = (*(ue_context_p->ue_context.mac_MainConfig->ext2->mac_MainConfig_v1020->extendedBSR_Sizes_r10));
+	if (val > 0) {
+	  return 1;
+	}
+      }
+    }
+  }
+  return -1;
+}
+
+int flexran_get_ue_transmission_antenna(mid_t mod_id, mid_t ue_id) {
+  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
+  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
+
+  if (eNB_rrc_inst_not_ready()) return -1;
+
+  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
+  
+  if(ue_context_p != NULL) {
+    if(ue_context_p->ue_context.physicalConfigDedicated != NULL){
+      if(ue_context_p->ue_context.physicalConfigDedicated->antennaInfo->choice.explicitValue.ue_TransmitAntennaSelection.choice.setup == AntennaInfoDedicated__ue_TransmitAntennaSelection__setup_closedLoop) {
+	return 2;
+      } else if(ue_context_p->ue_context.physicalConfigDedicated->antennaInfo->choice.explicitValue.ue_TransmitAntennaSelection.choice.setup == AntennaInfoDedicated__ue_TransmitAntennaSelection__setup_openLoop) {
+	return 1;
+      } else {
+	return 0;
+      }
+    } else {
+      return -1;
+    }
+  } else {
+    return -1;
+  }
+}
+
+int flexran_get_lcg(mid_t ue_id, mid_t lc_id) {
+  if (UE_mac_inst == NULL) {
+    return -1;
+  }
+  if(UE_mac_inst[ue_id].logicalChannelConfig[lc_id] != NULL) {
+    return *UE_mac_inst[ue_id].logicalChannelConfig[lc_id]->ul_SpecificParameters->logicalChannelGroup;
+  } else {
+    return -1;
+  }
+}
+
+int flexran_get_direction(mid_t ue_id, mid_t lc_id) {
+	/*TODO: fill with the value for the rest of LCID*/
+  if(lc_id == DCCH || lc_id == DCCH1) {
+    return 2;
+  } else if(lc_id == DTCH) {
+    return 1;
+  } else {
+    return -1;
+  }
+}
+
+int flexran_get_antenna_ports(mid_t mod_id, int CC_id){
+
+  LTE_DL_FRAME_PARMS   *frame_parms;
+
+  if (mac_xface_not_ready()) return 0;
+
+  frame_parms = mac_xface->get_lte_frame_parms(mod_id, CC_id);
+  return (frame_parms == NULL)? 0:frame_parms->nb_antenna_ports_eNB;
+
+}
+
+
+uint32_t flexran_agent_get_operating_dl_freq (mid_t mod_id, int cc_id) {
+        
+        return (enb_properties->properties[mod_id]->downlink_frequency[cc_id] / 1000000);
+}
+
+uint32_t flexran_agent_get_operating_ul_freq (mid_t mod_id, int cc_id) {
+        return ((enb_properties->properties[mod_id]->downlink_frequency[cc_id] + enb_properties->properties[0]->uplink_frequency_offset[cc_id]) / 1000000);
+}
+
+int flexran_agent_get_operating_eutra_band (mid_t mod_id, int cc_id) {
+        return enb_properties->properties[mod_id]->eutra_band[cc_id];
+}
+int flexran_agent_get_operating_pdsch_refpower (mid_t mod_id, int cc_id) {
+        return enb_properties->properties[mod_id]->pdsch_referenceSignalPower[cc_id];
+}
+int flexran_agent_get_operating_pusch_p0 (mid_t mod_id, int cc_id) {
+        return enb_properties->properties[mod_id]->pusch_p0_Nominal[cc_id];
+}
+
+void flexran_agent_set_operating_dl_freq (mid_t mod_id, int cc_id, uint32_t dl_freq_mhz) {
+
+        enb_properties->properties[mod_id]->downlink_frequency[cc_id]=dl_freq_mhz * 1000000;
+        /*printf("[ENB_APP] mod id %d ccid %d dl freq %d/%d\n", mod_id, cc_id, dl_freq_mhz, enb_properties->properties[mod_id]->downlink_frequency[cc_id]); */   
+}
+
+void flexran_agent_set_operating_ul_freq (mid_t mod_id, int cc_id, int32_t ul_freq_offset_mhz) {
+        enb_properties->properties[mod_id]->uplink_frequency_offset[cc_id]=ul_freq_offset_mhz * 1000000;
+}
+//TBD
+void flexran_agent_set_operating_eutra_band (mid_t mod_id, int cc_id) {
+        enb_properties->properties[mod_id]->eutra_band[cc_id]=7;
+}
+
+void flexran_agent_set_operating_bandwidth (mid_t mod_id, int cc_id, int bandwidth) {
+        enb_properties->properties[mod_id]->N_RB_DL[cc_id]=bandwidth;
+}
+
+void flexran_agent_set_operating_frame_type (mid_t mod_id, int cc_id, int frame_type) {
+        enb_properties->properties[mod_id]->frame_type[cc_id]=frame_type;
+}
+
+/*********** PDCP  *************/
+/*PDCP super frame counter flexRAN*/
+uint32_t flexran_get_pdcp_sfn(const mid_t mod_id){
+  return pdcp_enb[mod_id].sfn;
+}
+
+/*PDCP super frame counter flexRAN*/
+void flexran_set_pdcp_tx_stat_window(const mid_t mod_id, const mid_t ue_id, uint16_t obs_window){
+  if (obs_window > 0 ){
+    Pdcp_stats_tx_window_ms[mod_id][ue_id]=obs_window;
+  }
+  else{
+    Pdcp_stats_tx_window_ms[mod_id][ue_id]=1000;
+  }
+}
+
+/*PDCP super frame counter flexRAN*/
+void flexran_set_pdcp_rx_stat_window(const mid_t mod_id, const mid_t ue_id, uint16_t obs_window){
+  if (obs_window > 0 ){
+    Pdcp_stats_rx_window_ms[mod_id][ue_id]=obs_window;
+  }
+  else{
+    Pdcp_stats_rx_window_ms[mod_id][ue_id]=1000;
+  }
+}
+
+/*PDCP num tx pdu status flexRAN*/
+uint32_t flexran_get_pdcp_tx(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid){
+  if (mod_id <0 || mod_id> MAX_NUM_CCs || ue_id<0 || ue_id> NUMBER_OF_UE_MAX || lcid<0 || lcid>NB_RB_MAX)
+    return -1;
+  return Pdcp_stats_tx[mod_id][ue_id][lcid];
+}
+
+/*PDCP num tx bytes status flexRAN*/
+uint32_t flexran_get_pdcp_tx_bytes(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid){
+  return Pdcp_stats_tx_bytes[mod_id][ue_id][lcid];
+}
+
+/*PDCP number of transmit packet / second status flexRAN*/
+uint32_t flexran_get_pdcp_tx_w(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid){
+  return Pdcp_stats_tx_w[mod_id][ue_id][lcid];
+}
+
+/*PDCP throughput (bit/s) status flexRAN*/
+uint32_t flexran_get_pdcp_tx_bytes_w(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid){
+  return Pdcp_stats_tx_bytes_w[mod_id][ue_id][lcid];
+}
+
+/*PDCP tx sequence number flexRAN*/
+uint32_t flexran_get_pdcp_tx_sn(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid){
+  return Pdcp_stats_tx_sn[mod_id][ue_id][lcid];
+}
+
+/*PDCP tx aggregated packet arrival  flexRAN*/
+uint32_t flexran_get_pdcp_tx_aiat(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid){
+  return Pdcp_stats_tx_aiat[mod_id][ue_id][lcid];
+}
+
+/*PDCP tx aggregated packet arrival  flexRAN*/
+uint32_t flexran_get_pdcp_tx_aiat_w(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid){
+  return Pdcp_stats_tx_aiat_w[mod_id][ue_id][lcid];
+}
+
+
+/*PDCP num rx pdu status flexRAN*/
+uint32_t flexran_get_pdcp_rx(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid){
+  return Pdcp_stats_rx[mod_id][ue_id][lcid];
+}
+
+/*PDCP num rx bytes status flexRAN*/
+uint32_t flexran_get_pdcp_rx_bytes(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid){
+  return Pdcp_stats_rx_bytes[mod_id][ue_id][lcid];
+}
+
+/*PDCP number of received packet / second  flexRAN*/
+uint32_t flexran_get_pdcp_rx_w(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid){
+  return Pdcp_stats_rx_w[mod_id][ue_id][lcid];
+}
+
+/*PDCP gootput (bit/s) status flexRAN*/
+uint32_t flexran_get_pdcp_rx_bytes_w(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid){
+  return Pdcp_stats_rx_bytes_w[mod_id][ue_id][lcid];
+}
+
+/*PDCP rx sequence number flexRAN*/
+uint32_t flexran_get_pdcp_rx_sn(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid){
+  return Pdcp_stats_rx_sn[mod_id][ue_id][lcid];
+}
+
+/*PDCP rx aggregated packet arrival  flexRAN*/
+uint32_t flexran_get_pdcp_rx_aiat(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid){
+  return Pdcp_stats_rx_aiat[mod_id][ue_id][lcid];
+}
+
+/*PDCP rx aggregated packet arrival  flexRAN*/
+uint32_t flexran_get_pdcp_rx_aiat_w(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid){
+  return Pdcp_stats_rx_aiat_w[mod_id][ue_id][lcid];
+}
+
+/*PDCP num of received outoforder pdu status flexRAN*/
+uint32_t flexran_get_pdcp_rx_oo(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid){
+  return Pdcp_stats_rx_outoforder[mod_id][ue_id][lcid];
+}
+
+/******************** RRC *****************************/
+
+int flexran_get_rrc_pcell_measid(mid_t mod_id, mid_t ue_id) {
+  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
+  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
+
+  if (eNB_rrc_inst_not_ready()) return -1;
+  
+  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
+  if(ue_context_p != NULL) {
+    if(ue_context_p->ue_context.measResults != NULL) {
+      return ue_context_p->ue_context.measResults->measId;
+    } else {
+      return -1;
+    }
+  } else {
+    return -1;
+  }
+}
+int flexran_get_rrc_pcell_rsrp(mid_t mod_id, mid_t ue_id) {
+  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
+  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
+
+  if (eNB_rrc_inst_not_ready()) return -1;
+
+  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
+  if(ue_context_p != NULL) {
+    if(ue_context_p->ue_context.measResults != NULL) {
+      return RSRP_meas_mapping[ue_context_p->ue_context.measResults->measResultPCell.rsrpResult];
+    } else {
+      return -1;
+    }
+  } else {
+    return -1;
+  }
+}
+int flexran_get_rrc_pcell_rsrq(mid_t mod_id, mid_t ue_id) {
+  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
+  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
+
+  if (eNB_rrc_inst_not_ready()) return -1;
+
+  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
+  if(ue_context_p != NULL) {
+    if(ue_context_p->ue_context.measResults != NULL) {
+      return RSRQ_meas_mapping[ue_context_p->ue_context.measResults->measResultPCell.rsrqResult];
+    } else {
+      return -1;
+    }
+  } else {
+    return -1;
+  }
+}
+
+/*Number of neighbouring cells for specific UE*/
+int flexran_get_rrc_num_ncell(mid_t mod_id, mid_t ue_id) {
+  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
+  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
+
+  if (eNB_rrc_inst_not_ready()) return 0;
+  
+  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
+  if(ue_context_p != NULL) {
+
+    if (ue_context_p->ue_context.measResults != NULL){
+
+      if(ue_context_p->ue_context.measResults->measResultNeighCells != NULL) {
+
+       if (ue_context_p->ue_context.measResults->measResultNeighCells->present == MeasResults__measResultNeighCells_PR_measResultListEUTRA) {
+
+        return ue_context_p->ue_context.measResults->measResultNeighCells->choice.measResultListEUTRA.list.count;
+       }
+       else{
+
+        return 0;
+       }
+
+      } else {
+
+        return 0;
+      }
+
+    } else {
+
+      return 0;
+
+    }
+      
+  } else {
+    return 0;
+  }
+    
+}
+
+int flexran_get_rrc_neigh_phy_cell_id(mid_t mod_id, mid_t ue_id, int cell_id) {
+  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
+  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
+
+  if (eNB_rrc_inst_not_ready()) return -1;
+  
+  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
+  if(ue_context_p != NULL) {
+    if(ue_context_p->ue_context.measResults->measResultNeighCells != NULL) {
+
+      if (ue_context_p->ue_context.measResults->measResultNeighCells->present == MeasResults__measResultNeighCells_PR_measResultListEUTRA) {
+
+      return ue_context_p->ue_context.measResults->measResultNeighCells->choice.measResultListEUTRA.list.array[cell_id]->physCellId; 
+
+      }
+      else {
+
+        return -1;
+      }      
+    } else {
+      return -1;
+    }
+  } else {
+    return -1;
+  }
+}
+
+int flexran_get_rrc_neigh_rsrp(mid_t mod_id, mid_t ue_id, int cell_id) {
+  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
+  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
+
+  if (eNB_rrc_inst_not_ready()) return -1;
+  
+  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
+  if(ue_context_p != NULL) {
+
+    if(ue_context_p->ue_context.measResults->measResultNeighCells != NULL) {
+
+      if (ue_context_p->ue_context.measResults->measResultNeighCells->present == MeasResults__measResultNeighCells_PR_measResultListEUTRA) {
+
+          if (ue_context_p->ue_context.measResults->measResultNeighCells->choice.measResultListEUTRA.list.array[cell_id]->measResult.rsrpResult){
+              return RSRP_meas_mapping[*(ue_context_p->ue_context.measResults->measResultNeighCells->choice.measResultListEUTRA.list.array[cell_id]->measResult.rsrpResult)]; 
+
+          }
+          else {
+
+              return 0;
+          }
+
+    }
+      else {
+
+          return -1;
+      }
+
+    } 
+    else {
+      return -1;
+    }
+  
+  }
+   else {
+    return -1;
+  }
+}
+
+int flexran_get_rrc_neigh_rsrq(mid_t mod_id, mid_t ue_id, int cell_id) {
+  struct rrc_eNB_ue_context_s* ue_context_p = NULL;
+  uint32_t rntiP = flexran_get_ue_crnti(mod_id,ue_id);
+
+  if (eNB_rrc_inst_not_ready()) return -1;
+  
+  ue_context_p = rrc_eNB_get_ue_context(&eNB_rrc_inst[mod_id],rntiP);
+  if(ue_context_p != NULL) {
+    if(ue_context_p->ue_context.measResults->measResultNeighCells != NULL) {
+      if (ue_context_p->ue_context.measResults->measResultNeighCells->present == MeasResults__measResultNeighCells_PR_measResultListEUTRA) {
+
+         if (ue_context_p->ue_context.measResults->measResultNeighCells->choice.measResultListEUTRA.list.array[cell_id]->measResult.rsrqResult){
+           return RSRQ_meas_mapping[*(ue_context_p->ue_context.measResults->measResultNeighCells->choice.measResultListEUTRA.list.array[cell_id]->measResult.rsrqResult)]; 
+
+         } 
+         else {
+
+           return 0;
+         }
+      }
+      else {
+
+        return -1;
+      }
+    } else {
+      return -1;
+    }
+  } else {
+    return -1;
+  }
+}
diff --git a/openair2/ENB_APP/flexran_agent_ran_api.h b/openair2/ENB_APP/flexran_agent_ran_api.h
new file mode 100644
index 0000000000000000000000000000000000000000..05c681713628bee30bd7394b26f1002fe6489db6
--- /dev/null
+++ b/openair2/ENB_APP/flexran_agent_ran_api.h
@@ -0,0 +1,426 @@
+/*
+ * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The OpenAirInterface Software Alliance licenses this file to You under
+ * the OAI Public License, Version 1.0  (the "License"); you may not use this file
+ * except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.openairinterface.org/?page_id=698
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *-------------------------------------------------------------------------------
+ * For more information about the OpenAirInterface (OAI) Software Alliance:
+ *      contact@openairinterface.org
+ */ 
+
+/*! \file flexran_agent_ran_api.h
+ * \brief FlexRAN RAN API abstraction header 
+ * \author N. Nikaein, X. Foukas and S. SHARIAT BAGHERI
+ * \date 2017
+ * \version 0.1
+ */
+
+#include <stdio.h>
+#include <time.h>
+
+#include "flexran_agent_common.h"
+#include "flexran_agent_common_internal.h"
+#include "flexran_agent_extern.h"
+#include "flexran_agent_defs.h"
+
+
+#include "enb_config.h"
+#include "LAYER2/MAC/extern.h"
+#include "LAYER2/RLC/rlc.h"
+#include "SCHED/defs.h"
+#include "pdcp.h"
+#include "RRC/LITE/extern.h"
+#include "RRC/L2_INTERFACE/openair_rrc_L2_interface.h"
+#include "RRC/LITE/rrc_eNB_UE_context.h"
+#include "PHY/extern.h"
+#include "log.h"
+
+/****************************
+ * get generic info from RAN
+ ****************************/
+
+void flexran_set_enb_vars(mid_t mod_id, ran_name_t ran);
+
+int flexran_get_current_time_ms (mid_t mod_id, int subframe_flag);
+
+/*Return the current frame number
+ *Could be using implementation specific numbering of frames
+ */
+unsigned int flexran_get_current_frame(mid_t mod_id);
+
+/*Return the current SFN (0-1023)*/ 
+unsigned int flexran_get_current_system_frame_num(mid_t mod_id);
+
+unsigned int flexran_get_current_subframe(mid_t mod_id);
+
+/*Return the frame and subframe number in compact 16-bit format.
+  Bits 0-3 subframe, rest for frame. Required by FlexRAN protocol*/
+uint16_t flexran_get_sfn_sf (mid_t mod_id);
+
+/* Return a future frame and subframe number that is ahead_of_time
+   subframes later in compact 16-bit format. Bits 0-3 subframe,
+   rest for frame */
+uint16_t flexran_get_future_sfn_sf(mid_t mod_id, int ahead_of_time);
+
+/* Return the number of attached UEs */
+int flexran_get_num_ues(mid_t mod_id);
+
+/* Get the rnti of a UE with id ue_id */
+int flexran_get_ue_crnti (mid_t mod_id, mid_t ue_id);
+
+/* Get the RLC buffer status report of a ue for a designated
+   logical channel id */
+int flexran_get_ue_bsr (mid_t mod_id, mid_t ue_id, lcid_t lcid);
+
+/* Get power headroom of UE with id ue_id */
+int flexran_get_ue_phr (mid_t mod_id, mid_t ue_id);
+
+/* Get the UE wideband CQI */
+int flexran_get_ue_wcqi (mid_t mod_id, mid_t ue_id);
+
+/* Get the transmission queue size for a UE with a channel_id logical channel id */
+int flexran_get_tx_queue_size(mid_t mod_id, mid_t ue_id, logical_chan_id_t channel_id);
+
+/*Get number of pdus in RLC buffer*/
+int flexran_get_num_pdus_buffer(mid_t mod_id, mid_t ue_id, logical_chan_id_t channel_id); 
+
+/* Get the head of line delay for a UE with a channel_id logical channel id */
+int flexran_get_hol_delay(mid_t mod_id, mid_t ue_id, logical_chan_id_t channel_id);
+
+/* Check the status of the timing advance for a UE */
+short flexran_get_TA(mid_t mod_id, mid_t ue_id, int CC_id);
+
+/* Update the timing advance status (find out whether a timing advance command is required) */
+void flexran_update_TA(mid_t mod_id, mid_t ue_id, int CC_id);
+
+/* Return timing advance MAC control element for a designated cell and UE */
+int flexran_get_MAC_CE_bitmap_TA(mid_t mod_id, mid_t ue_id, int CC_id);
+
+/* Get the number of active component carriers for a specific UE */
+int flexran_get_active_CC(mid_t mod_id, mid_t ue_id);
+
+/* Get the rank indicator for a designated cell and UE */
+int flexran_get_current_RI(mid_t mod_id, mid_t ue_id, int CC_id);
+
+/* See TS 36.213, section 10.1 */
+int flexran_get_n1pucch_an(mid_t mod_id, int CC_id);
+
+/* See TS 36.211, section 5.4 */
+int flexran_get_nRB_CQI(mid_t mod_id, int CC_id);
+
+/* See TS 36.211, section 5.4 */
+int flexran_get_deltaPUCCH_Shift(mid_t mod_id, int CC_id);
+
+/* See TS 36.211, section 5.7.1 */
+int flexran_get_prach_ConfigIndex(mid_t mod_id, int CC_id);
+
+/* See TS 36.211, section 5.7.1 */
+int flexran_get_prach_FreqOffset(mid_t mod_id, int CC_id);
+
+/* See TS 36.321 */
+int flexran_get_maxHARQ_Msg3Tx(mid_t mod_id, int CC_id);
+
+/* Get the length of the UL cyclic prefix */
+int flexran_get_ul_cyclic_prefix_length(mid_t mod_id, int CC_id);
+
+/* Get the length of the DL cyclic prefix */
+int flexran_get_dl_cyclic_prefix_length(mid_t mod_id, int CC_id);
+
+/* Get the physical cell id of a cell */
+int flexran_get_cell_id(mid_t mod_id, int CC_id);
+
+/* See TS 36.211, section 5.5.3.2 */
+int flexran_get_srs_BandwidthConfig(mid_t mod_id, int CC_id);
+
+/* See TS 36.211, table 5.5.3.3-1 and 2 */
+int flexran_get_srs_SubframeConfig(mid_t mod_id, int CC_id);
+
+/* Boolean value. See TS 36.211,
+   section 5.5.3.2. TDD only */
+int flexran_get_srs_MaxUpPts(mid_t mod_id, int CC_id);
+
+/* Get number of DL resource blocks */
+int flexran_get_N_RB_DL(mid_t mod_id, int CC_id);
+
+/* Get number of UL resource blocks */
+int flexran_get_N_RB_UL(mid_t mod_id, int CC_id);
+
+/* Get number of resource block groups */
+int flexran_get_N_RBG(mid_t mod_id, int CC_id);
+
+/* Get DL/UL subframe assignment. TDD only */
+int flexran_get_subframe_assignment(mid_t mod_id, int CC_id);
+
+/* TDD only. See TS 36.211, table 4.2.1 */
+int flexran_get_special_subframe_assignment(mid_t mod_id, int CC_id);
+
+/* Get the duration of the random access response window in subframes */
+int flexran_get_ra_ResponseWindowSize(mid_t mod_id, int CC_id);
+
+/* Get timer used for random access */
+int flexran_get_mac_ContentionResolutionTimer(mid_t mod_id, int CC_id);
+
+/* Get type of duplex mode (FDD/TDD) */
+int flexran_get_duplex_mode(mid_t mod_id, int CC_id);
+
+/* Get the SI window length */
+long flexran_get_si_window_length(mid_t mod_id, int CC_id);
+
+/* Get the number of PDCCH symbols configured for the cell */
+int flexran_get_num_pdcch_symb(mid_t mod_id, int CC_id);
+
+int flexran_get_antenna_ports(mid_t mod_id, int CC_id);
+
+/* See TS 36.213, sec 5.1.1.1 */
+int flexran_get_tpc(mid_t mod_id, mid_t ue_id);
+
+int flexran_get_ue_pmi(mid_t mod_id);
+
+/* Get the first available HARQ process for a specific cell and UE during 
+   a designated frame and subframe. Returns 0 for success. The id and the 
+   status of the HARQ process are stored in id and status respectively */
+int flexran_get_harq(const mid_t mod_id, const uint8_t CC_id, const mid_t ue_id,
+		     const int frame, const uint8_t subframe, unsigned char *id, unsigned char *round,const uint8_t harq_flag);
+
+/* Uplink power control management*/
+int flexran_get_p0_pucch_dbm(mid_t mod_id, mid_t ue_id, int CC_id);
+
+int flexran_get_p0_nominal_pucch(mid_t mod_id, int CC_id);
+
+int flexran_get_p0_pucch_status(mid_t mod_id, mid_t ue_id, int CC_id);
+
+int flexran_update_p0_pucch(mid_t mod_id, mid_t ue_id, int CC_id);
+
+int flexran_get_threequarter_fs(mid_t mod_id, int CC_id);
+
+int flexran_get_hopping_mode(mid_t mod_id, int CC_id);
+
+int flexran_get_hopping_offset(mid_t mod_id, int CC_id);
+
+int flexran_get_n_SB(mid_t mod_id, int CC_id);
+
+int flexran_get_phich_resource(mid_t mod_id, int CC_id);
+
+int flexran_get_enable64QAM(mid_t mod_id, int CC_id);
+
+int flexran_get_phich_duration(mid_t mod_id, int CC_id);
+
+/*
+ * ************************************
+ * Get Messages for UE Configuration Reply
+ * ************************************
+ */
+
+/* Get timer in subframes. Controls the synchronization
+   status of the UE, not the actual timing 
+   advance procedure. See TS 36.321 */
+int flexran_get_time_alignment_timer(mid_t mod_id, mid_t ue_id);
+
+/* Get measurement gap configuration. See TS 36.133 */
+int flexran_get_meas_gap_config(mid_t mod_id, mid_t ue_id);
+
+/* Get measurement gap configuration offset if applicable */
+int flexran_get_meas_gap_config_offset(mid_t mod_id, mid_t ue_id);
+
+/* DL aggregated bit-rate of non-gbr bearer
+   per UE. See TS 36.413 */
+int flexran_get_ue_aggregated_max_bitrate_dl (mid_t mod_id, mid_t ue_id);
+
+/* UL aggregated bit-rate of non-gbr bearer
+   per UE. See TS 36.413 */
+int flexran_get_ue_aggregated_max_bitrate_ul (mid_t mod_id, mid_t ue_id);
+
+/* Only half-duplex support. FDD
+   operation. Boolean value */
+int flexran_get_half_duplex(mid_t ue_id);
+
+/* Support of intra-subframe hopping.
+   Boolean value */
+int flexran_get_intra_sf_hopping(mid_t ue_id);
+
+/* UE support for type 2 hopping with
+   n_sb>1 */
+int flexran_get_type2_sb_1(mid_t ue_id);
+
+/* Get the UE category */
+int flexran_get_ue_category(mid_t ue_id);
+
+/* UE support for resource allocation
+   type 1 */
+int flexran_get_res_alloc_type1(mid_t ue_id);
+
+/* Get UE transmission mode */
+int flexran_get_ue_transmission_mode(mid_t mod_id, mid_t ue_id);
+
+/* Boolean value. See TS 36.321 */
+int flexran_get_tti_bundling(mid_t mod_id, mid_t ue_id);
+
+/* The max HARQ retransmission for UL.
+   See TS 36.321 */
+int flexran_get_maxHARQ_TX(mid_t mod_id, mid_t ue_id);
+
+/* See TS 36.213 */
+int flexran_get_beta_offset_ack_index(mid_t mod_id, mid_t ue_id);
+
+/* See TS 36.213 */
+int flexran_get_beta_offset_ri_index(mid_t mod_id, mid_t ue_id);
+
+/* See TS 36.213 */
+int flexran_get_beta_offset_cqi_index(mid_t mod_id, mid_t ue_id);
+
+/* Boolean. See TS36.213, Section 10.1 */
+int flexran_get_simultaneous_ack_nack_cqi(mid_t mod_id, mid_t ue_id);
+
+/* Boolean. See TS 36.213, Section 8.2 */
+int flexran_get_ack_nack_simultaneous_trans(mid_t mod_id,mid_t ue_id);
+
+/* Get aperiodic CQI report mode */
+int flexran_get_aperiodic_cqi_rep_mode(mid_t mod_id,mid_t ue_id);
+
+/* Get ACK/NACK feedback mode. TDD only */
+int flexran_get_tdd_ack_nack_feedback(mid_t mod_id, mid_t ue_id);
+
+/* See TS36.213, section 10.1 */
+int flexran_get_ack_nack_repetition_factor(mid_t mod_id, mid_t ue_id);
+
+/* Boolean. Extended buffer status report size */
+int flexran_get_extended_bsr_size(mid_t mod_id, mid_t ue_id);
+
+/* Get number of UE transmission antennas */
+int flexran_get_ue_transmission_antenna(mid_t mod_id, mid_t ue_id);
+
+/* Get logical channel group of a channel with id lc_id */
+int flexran_get_lcg(mid_t ue_id, mid_t lc_id);
+
+/* Get direction of logical channel with id lc_id */
+int flexran_get_direction(mid_t ue_id, mid_t lc_id);
+
+/*Get downlink frequency*/
+uint32_t flexran_agent_get_operating_dl_freq (mid_t mod_id, int cc_id);
+
+/*Get uplink frequency*/
+uint32_t flexran_agent_get_operating_ul_freq (mid_t mod_id, int cc_id);
+
+/*Get eutra band*/
+int flexran_agent_get_operating_eutra_band (mid_t mod_id, int cc_id);
+
+/*Get downlink ref signal power*/
+int flexran_agent_get_operating_pdsch_refpower (mid_t mod_id, int cc_id);
+
+/*Get uplink power*/
+int flexran_agent_get_operating_pusch_p0 (mid_t mod_id, int cc_id);
+
+/*set the dl freq */
+void flexran_agent_set_operating_dl_freq (mid_t mod_id, int cc_id, uint32_t dl_freq_mhz);
+
+/* set the ul freq */
+void flexran_agent_set_operating_ul_freq (mid_t mod_id, int cc_id, int32_t ul_freq_offset_mhz);
+
+/*set the the band */
+void flexran_agent_set_operating_eutra_band (mid_t mod_id, int cc_id);
+
+/* set the bandwidth */
+void flexran_agent_set_operating_bandwidth (mid_t mod_id, int cc_id, int bandwidth);
+
+/*set frame type*/
+void flexran_agent_set_operating_frame_type (mid_t mod_id, int cc_id, int frame_type);
+
+/*RRC status flexRAN*/
+int flexran_get_rrc_status(const mid_t mod_id,  const rnti_t  rntiP);
+
+
+/***************************** PDCP ***********************/
+
+/*PDCP superframe numberflexRAN*/
+uint32_t flexran_get_pdcp_sfn(const mid_t mod_id);
+
+/*PDCP pdcp tx stats window*/
+void flexran_set_pdcp_tx_stat_window(const mid_t mod_id, const mid_t ue_id, uint16_t obs_window);
+
+/*PDCP pdcp rx stats window*/
+void flexran_set_pdcp_rx_stat_window(const mid_t mod_id, const mid_t ue_id, uint16_t obs_window);
+
+/*PDCP num tx pdu status flexRAN*/
+uint32_t flexran_get_pdcp_tx(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid);
+
+/*PDCP num tx bytes status flexRAN*/
+uint32_t flexran_get_pdcp_tx_bytes(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid);
+
+/*PDCP number of transmit packet / second status flexRAN*/
+uint32_t flexran_get_pdcp_tx_w(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid);
+
+/*PDCP pdcp tx bytes in a given window flexRAN*/
+uint32_t flexran_get_pdcp_tx_bytes_w(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid);
+
+/*PDCP tx sequence number flexRAN*/
+uint32_t flexran_get_pdcp_tx_sn(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid);
+
+/*PDCP tx aggregated packet arrival  flexRAN*/
+uint32_t flexran_get_pdcp_tx_aiat(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid);
+
+/*PDCP tx aggregated packet arrival per second flexRAN*/
+uint32_t flexran_get_pdcp_tx_aiat_w(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid);
+
+
+/*PDCP num rx pdu status flexRAN*/
+uint32_t flexran_get_pdcp_rx(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid);
+
+/*PDCP num rx bytes status flexRAN*/
+uint32_t flexran_get_pdcp_rx_bytes(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid);
+
+/*PDCP number of received packet / second  flexRAN*/
+uint32_t flexran_get_pdcp_rx_w(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid);
+
+/*PDCP gootput (bit/s) status flexRAN*/
+uint32_t flexran_get_pdcp_rx_bytes_w(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid);
+
+/*PDCP rx sequence number flexRAN*/
+uint32_t flexran_get_pdcp_rx_sn(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid);
+
+/*PDCP rx aggregated packet arrival  flexRAN*/
+uint32_t flexran_get_pdcp_rx_aiat(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid);
+
+/*PDCP rx aggregated packet arrival per second flexRAN*/
+uint32_t flexran_get_pdcp_rx_aiat_w(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid);
+
+/*PDCP num of received outoforder pdu status flexRAN*/
+uint32_t flexran_get_pdcp_rx_oo(const mid_t mod_id,  const mid_t ue_id, const lcid_t lcid);
+
+/*********************RRC**********************/
+/*Get primary cell measuremeant id flexRAN*/
+int flexran_get_rrc_pcell_measid(mid_t mod_id, mid_t ue_id);
+
+/*Get primary cell RSRP measurement flexRAN*/  
+int flexran_get_rrc_pcell_rsrp(mid_t mod_id, mid_t ue_id);
+
+/*Get primary cell RSRQ measurement flexRAN*/
+int flexran_get_rrc_pcell_rsrq(mid_t mod_id, mid_t ue_id);
+
+/* Get RRC neighbouring measurement */
+int flexran_get_rrc_num_ncell(mid_t mod_id, mid_t ue_id);
+
+/*Get physical cell id*/
+int flexran_get_rrc_neigh_phy_cell_id(mid_t mod_id, mid_t ue_id, int cell_id);
+
+/*Get RSRP of neighbouring Cell*/
+int flexran_get_rrc_neigh_rsrp(mid_t mod_id, mid_t ue_id, int cell_id);
+
+/*Get RSRQ of neighbouring Cell*/
+int flexran_get_rrc_neigh_rsrq(mid_t mod_id, mid_t ue_id, int cell_id);
+
+/*Get MCC PLMN identity neighbouring Cell*/
+int flexran_get_rrc_neigh_plmn_mcc(mid_t mod_id, mid_t ue_id, int cell_id);
+
+/*Get MNC PLMN identity neighbouring Cell*/
+int flexran_get_rrc_neigh_plmn_mnc(mid_t mod_id, mid_t ue_id, int cell_id);
\ No newline at end of file
diff --git a/openair2/ENB_APP/flexran_agent_timer.c b/openair2/ENB_APP/flexran_agent_timer.c
new file mode 100644
index 0000000000000000000000000000000000000000..f5436e4d01dcf192744dac2506978986ad5bc02e
--- /dev/null
+++ b/openair2/ENB_APP/flexran_agent_timer.c
@@ -0,0 +1,217 @@
+/*
+ * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The OpenAirInterface Software Alliance licenses this file to You under
+ * the OAI Public License, Version 1.0  (the "License"); you may not use this file
+ * except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.openairinterface.org/?page_id=698
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *-------------------------------------------------------------------------------
+ * For more information about the OpenAirInterface (OAI) Software Alliance:
+ *      contact@openairinterface.org
+ */ 
+
+/*! \file flexran_agent_timer.c
+ * \brief FlexRAN Timer  
+ * \author shahab SHARIAT BAGHERI
+ * \date 2017
+ * \version 0.1
+ */
+
+/*
+ * timer primitives
+ */
+
+#include "flexran_agent_timer.h"
+
+//struct flexran_agent_map agent_map;
+flexran_agent_timer_instance_t timer_instance;
+int agent_timer_init = 0;
+err_code_t flexran_agent_init_timer(void){
+  
+  LOG_I(FLEXRAN_AGENT, "init RB tree\n");
+  if (!agent_timer_init) {
+    RB_INIT(&timer_instance.flexran_agent_head);
+    agent_timer_init = 1;
+  }
+ 
+ return PROTOCOL__FLEXRAN_ERR__NO_ERR;
+}
+
+RB_GENERATE(flexran_agent_map, flexran_agent_timer_element_s, entry, flexran_agent_compare_timer);
+
+/* The timer_id might not be the best choice for the comparison */
+int flexran_agent_compare_timer(struct flexran_agent_timer_element_s *a, struct flexran_agent_timer_element_s *b){
+
+  if (a->timer_id < b->timer_id) return -1;
+  if (a->timer_id > b->timer_id) return 1;
+
+  // equal timers
+  return 0;
+}
+
+err_code_t flexran_agent_create_timer(uint32_t interval_sec,
+				      uint32_t interval_usec,
+				      agent_id_t     agent_id,
+				      instance_t     instance,
+				      uint32_t timer_type,
+				      xid_t xid,
+				      flexran_agent_timer_callback_t cb,
+				      void*    timer_args,
+				      long *timer_id){
+  
+  struct flexran_agent_timer_element_s *e = calloc(1, sizeof(*e));
+  DevAssert(e != NULL);
+  
+//uint32_t timer_id;
+  int ret=-1;
+  
+  if ((interval_sec == 0) && (interval_usec == 0 ))
+    return TIMER_NULL;
+  
+  if (timer_type >= FLEXRAN_AGENT_TIMER_TYPE_MAX)
+    return TIMER_TYPE_INVALIDE;
+  
+  if (timer_type  ==   FLEXRAN_AGENT_TIMER_TYPE_ONESHOT){ 
+    ret = timer_setup(interval_sec, 
+		      interval_usec, 
+		      TASK_FLEXRAN_AGENT, 
+		      instance, 
+		      TIMER_ONE_SHOT,
+		      timer_args,
+		      timer_id);
+    
+    e->type = TIMER_ONE_SHOT;
+  }
+  else if (timer_type  ==   FLEXRAN_AGENT_TIMER_TYPE_PERIODIC ){
+    ret = timer_setup(interval_sec, 
+		      interval_usec, 
+		      TASK_FLEXRAN_AGENT, 
+		      instance, 
+		      TIMER_PERIODIC,
+		      timer_args,
+		      timer_id);
+    
+    e->type = TIMER_PERIODIC;
+  }
+  
+  if (ret < 0 ) {
+    return TIMER_SETUP_FAILED; 
+  }
+
+  e->agent_id = agent_id;
+  e->instance = instance;
+  e->state = FLEXRAN_AGENT_TIMER_STATE_ACTIVE;
+  e->timer_id = *timer_id;
+  e->xid = xid;
+  e->timer_args = timer_args; 
+  e->cb = cb;
+  /*element should be a real pointer*/
+  RB_INSERT(flexran_agent_map, &timer_instance.flexran_agent_head, e); 
+  
+  LOG_I(FLEXRAN_AGENT,"Created a new timer with id 0x%lx for agent %d, instance %d \n",
+	e->timer_id, e->agent_id, e->instance);
+  
+  return 0; 
+}
+
+err_code_t flexran_agent_destroy_timer(long timer_id){
+  
+  struct flexran_agent_timer_element_s *e = get_timer_entry(timer_id);
+
+  if (e != NULL ) {
+    RB_REMOVE(flexran_agent_map, &timer_instance.flexran_agent_head, e);
+    flexran_agent_destroy_flexran_message(e->timer_args->msg);
+    free(e);
+  }
+  
+  if (timer_remove(timer_id) < 0 ) 
+    goto error;
+  
+  return 0;
+
+ error:
+  LOG_E(FLEXRAN_AGENT, "timer can't be removed\n");
+  return TIMER_REMOVED_FAILED ;
+}
+
+err_code_t flexran_agent_destroy_timer_by_task_id(xid_t xid) {
+  struct flexran_agent_timer_element_s *e = NULL;
+  long timer_id;
+  RB_FOREACH(e, flexran_agent_map, &timer_instance.flexran_agent_head) {
+    if (e->xid == xid) {
+      timer_id = e->timer_id;
+      RB_REMOVE(flexran_agent_map, &timer_instance.flexran_agent_head, e);
+      flexran_agent_destroy_flexran_message(e->timer_args->msg);
+      free(e);
+      if (timer_remove(timer_id) < 0 ) { 
+	goto error;
+      }
+    }
+  }
+  return 0;
+
+ error:
+  LOG_E(FLEXRAN_AGENT, "timer can't be removed\n");
+  return TIMER_REMOVED_FAILED ;
+}
+
+err_code_t flexran_agent_destroy_timers(void){
+  
+  struct flexran_agent_timer_element_s *e = NULL;
+  
+  RB_FOREACH(e, flexran_agent_map, &timer_instance.flexran_agent_head) {
+    RB_REMOVE(flexran_agent_map, &timer_instance.flexran_agent_head, e);
+    timer_remove(e->timer_id);
+    flexran_agent_destroy_flexran_message(e->timer_args->msg);
+    free(e);
+  }  
+
+  return 0;
+
+}
+
+void flexran_agent_sleep_until(struct timespec *ts, int delay) {
+  ts->tv_nsec += delay;
+  if(ts->tv_nsec >= 1000*1000*1000){
+    ts->tv_nsec -= 1000*1000*1000;
+    ts->tv_sec++;
+  }
+  clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ts,  NULL);
+}
+
+
+err_code_t flexran_agent_stop_timer(long timer_id){
+  
+  struct flexran_agent_timer_element_s *e=NULL;
+  struct flexran_agent_timer_element_s search;
+  memset(&search, 0, sizeof(struct flexran_agent_timer_element_s));
+  search.timer_id = timer_id;
+
+  e = RB_FIND(flexran_agent_map, &timer_instance.flexran_agent_head, &search);
+
+  if (e != NULL ) {
+    e->state =  FLEXRAN_AGENT_TIMER_STATE_STOPPED;
+  }
+  
+  timer_remove(timer_id);
+  
+  return 0;
+}
+
+struct flexran_agent_timer_element_s * get_timer_entry(long timer_id) {
+  
+  struct flexran_agent_timer_element_s search;
+  memset(&search, 0, sizeof(struct flexran_agent_timer_element_s));
+  search.timer_id = timer_id;
+
+  return  RB_FIND(flexran_agent_map, &timer_instance.flexran_agent_head, &search); 
+}
diff --git a/openair2/ENB_APP/flexran_agent_timer.h b/openair2/ENB_APP/flexran_agent_timer.h
new file mode 100644
index 0000000000000000000000000000000000000000..86e0d07825c094ed2fc2efa80f929414931db02d
--- /dev/null
+++ b/openair2/ENB_APP/flexran_agent_timer.h
@@ -0,0 +1,133 @@
+/*
+ * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The OpenAirInterface Software Alliance licenses this file to You under
+ * the OAI Public License, Version 1.0  (the "License"); you may not use this file
+ * except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.openairinterface.org/?page_id=698
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *-------------------------------------------------------------------------------
+ * For more information about the OpenAirInterface (OAI) Software Alliance:
+ *      contact@openairinterface.org
+ */ 
+
+/*! \file flexran_agent_timer.h
+ * \brief FlexRAN Timer  header
+ * \author shahab SHARIAT BAGHERI
+ * \date 2017
+ * \version 0.1
+ */
+
+#include <stdio.h>
+#include <time.h>
+
+#include "flexran_agent_common.h"
+#include "flexran_agent_common_internal.h"
+#include "flexran_agent_extern.h"
+#include "flexran_agent_defs.h"
+
+
+# include "tree.h"
+# include "intertask_interface.h"
+# include "timer.h"
+
+
+
+/*******************
+ * timer primitves
+ *******************/
+
+#define TIMER_NULL                 -1 
+#define TIMER_TYPE_INVALIDE        -2
+#define	TIMER_SETUP_FAILED         -3
+#define	TIMER_REMOVED_FAILED       -4
+#define	TIMER_ELEMENT_NOT_FOUND    -5
+
+
+/* Type of the callback executed when the timer expired */
+typedef Protocol__FlexranMessage *(*flexran_agent_timer_callback_t)(void*);
+
+
+typedef struct flexran_agent_timer_args_s{
+  mid_t            mod_id;
+  Protocol__FlexranMessage *msg;
+} flexran_agent_timer_args_t;
+
+
+typedef struct flexran_agent_timer_element_s{
+  RB_ENTRY(flexran_agent_timer_element_s) entry;
+
+  agent_id_t             agent_id;
+  instance_t       instance;
+  
+  flexran_agent_timer_type_t  type;
+  flexran_agent_timer_state_t state;
+
+  uint32_t interval_sec;
+  uint32_t interval_usec;
+
+  long timer_id;  /* Timer id returned by the timer API*/
+  xid_t xid; /*The id of the task as received by the controller
+	       message*/
+  
+  flexran_agent_timer_callback_t cb;
+  flexran_agent_timer_args_t *timer_args;
+  
+} flexran_agent_timer_element_t;
+
+typedef struct flexran_agent_timer_instance_s{
+  RB_HEAD(flexran_agent_map, flexran_agent_timer_element_s) flexran_agent_head;
+}flexran_agent_timer_instance_t;
+
+
+err_code_t flexran_agent_init_timer(void);
+
+/* Create a timer for some agent related event with id xid. Will store the id 
+   of the generated timer in timer_id */
+err_code_t flexran_agent_create_timer(uint32_t interval_sec,
+				  uint32_t interval_usec,
+				  agent_id_t     agent_id,
+				  instance_t     instance,
+				  uint32_t timer_type,
+				  xid_t xid,
+				  flexran_agent_timer_callback_t cb,
+				  void*    timer_args,
+				  long *timer_id);
+
+/* Destroy all existing timers */
+err_code_t flexran_agent_destroy_timers(void);
+
+/* Destroy the timer with the given timer_id */
+err_code_t flexran_agent_destroy_timer(long timer_id);
+
+/* Destroy the timer for task with id xid */
+err_code_t flexran_agent_destroy_timer_by_task_id(xid_t xid);
+
+/* Stop a timer */
+err_code_t flexran_agent_stop_timer(long timer_id);
+
+/* Restart the given timer */
+err_code_t flexran_agent_restart_timer(long *timer_id);
+
+/* Find the timer with the given timer_id */
+struct flexran_agent_timer_element_s * get_timer_entry(long timer_id);
+
+/* Obtain the protocol message stored in the given expired timer */
+Protocol__FlexranMessage * flexran_agent_process_timeout(long timer_id, void* timer_args);
+
+/* Comparator function comparing two timers. Decides the ordering of the timers */
+int flexran_agent_compare_timer(struct flexran_agent_timer_element_s *a, struct flexran_agent_timer_element_s *b);
+
+/*Specify a delay in nanoseconds to timespec and sleep until then*/
+void flexran_agent_sleep_until(struct timespec *ts, int delay);
+
+/* RB_PROTOTYPE is for .h files */
+RB_PROTOTYPE(flexran_agent_map, flexran_agent_timer_element_s, entry, flexran_agent_compare_timer);
diff --git a/openair2/LAYER2/MAC/eNB_scheduler.c b/openair2/LAYER2/MAC/eNB_scheduler.c
index 2c3b88306a821b435d7d31da6364ee710395f6ee..14715aff5a13a8f87eef758b37bd4dcc07a5a51c 100644
--- a/openair2/LAYER2/MAC/eNB_scheduler.c
+++ b/openair2/LAYER2/MAC/eNB_scheduler.c
@@ -558,6 +558,14 @@ check_ul_failure(module_id_t module_idP, int CC_id, int UE_id,
 				   rnti);
 	    UE_list->UE_sched_ctrl[UE_id].ul_failure_timer = 0;
 	    UE_list->UE_sched_ctrl[UE_id].ul_out_of_sync = 1;
+//Inform the controller about the UE deactivation. Should be moved to RRC agent in the future
+#if defined(FLEXRAN_AGENT_SB_IF)
+	    if (rrc_agent_registered[module_idP]) {
+	      agent_rrc_xface[module_idP]->flexran_agent_notify_ue_state_change(module_idP,
+										rnti,
+										PROTOCOL__FLEX_UE_STATE_CHANGE_TYPE__FLUESC_DEACTIVATED);
+	    }
+#endif
 	}
     }				// ul_failure_timer>0
 
@@ -736,18 +744,42 @@ eNB_dlsch_ulsch_scheduler(module_id_t module_idP, frame_t frameP,
     copy_ulreq(module_idP, frameP, subframeP);
     // This schedules SRS in subframeP
     schedule_SRS(module_idP, frameP, subframeP);
+#if defined(FLEXRAN_AGENT_SB_IF)
+    if (mac_agent_registered[module_idP]){
+      agent_mac_xface[module_idP]->flexran_agent_schedule_ul_spec(module_idP,frameP,cooperation_flag,0,4, &msg);   
+    }
+    flexran_agent_mac_destroy_ul_config(msg);
+#else
     // This schedules ULSCH in subframeP (dci0)
     schedule_ulsch(module_idP, frameP, subframeP);
+#endif 
     // This schedules UCI_SR in subframeP
     schedule_SR(module_idP, frameP, subframeP);
     // This schedules UCI_CSI in subframeP
     schedule_CSI(module_idP, frameP, subframeP);
 
+#if defined(FLEXRAN_AGENT_SB_IF)
+     if (mac_agent_registered[module_idP]) {                                  
+	  agent_mac_xface[module_idP]->flexran_agent_schedule_ue_spec(
+								      module_idP,
+								      frameP,                  
+								      subframeP,
+								      mbsfn_status,
+								      &msg);
+	  
+	  flexran_apply_scheduling_decisions(module_idP,
+						frameP,
+						subframeP,
+						mbsfn_status,
+						msg);
+	  flexran_agent_mac_destroy_dl_config(msg);
+	}
+#else
     // This schedules DLSCH in subframeP
     schedule_ue_spec(module_idP, frameP, subframeP, mbsfn_status);
-
+#endif
+    
     // Allocate CCEs for good after scheduling is done
-
     for (CC_id = 0; CC_id < MAX_NUM_CCs; CC_id++)
 	allocate_CCEs(module_idP, CC_id, subframeP, 0);
 
diff --git a/openair2/LAYER2/MAC/eNB_scheduler_primitives.c b/openair2/LAYER2/MAC/eNB_scheduler_primitives.c
index df84675dc1e3fc28dcc1f76061fa5b0e01cf862d..e5f608d74cbfb49da30c49a1febede3b8e1e0c76 100644
--- a/openair2/LAYER2/MAC/eNB_scheduler_primitives.c
+++ b/openair2/LAYER2/MAC/eNB_scheduler_primitives.c
@@ -1927,16 +1927,18 @@ int UE_num_active_CC(UE_list_t * listP, int ue_idP)
 int UE_PCCID(module_id_t mod_idP, int ue_idP)
 //------------------------------------------------------------------------------
 {
-    return (RC.mac[mod_idP]->UE_list.pCC_id[ue_idP]);
+  if (RC.mac[mod_idP] == NULL) return 0;
+  return (RC.mac[mod_idP]->UE_list.pCC_id[ue_idP]);
 }
 
 //------------------------------------------------------------------------------
 rnti_t UE_RNTI(module_id_t mod_idP, int ue_idP)
 //------------------------------------------------------------------------------
 {
-    rnti_t rnti =
-	RC.mac[mod_idP]->
-	UE_list.UE_template[UE_PCCID(mod_idP, ue_idP)][ue_idP].rnti;
+  if (RC.mac[mod_idP] == NULL) return 0;
+  rnti_t rnti =
+    RC.mac[mod_idP]->
+    UE_list.UE_template[UE_PCCID(mod_idP, ue_idP)][ue_idP].rnti;
 
     if (rnti > 0) {
 	return (rnti);
@@ -1951,7 +1953,8 @@ rnti_t UE_RNTI(module_id_t mod_idP, int ue_idP)
 boolean_t is_UE_active(module_id_t mod_idP, int ue_idP)
 //------------------------------------------------------------------------------
 {
-    return (RC.mac[mod_idP]->UE_list.active[ue_idP]);
+  if (RC.mac[mod_idP] == NULL) return 0;
+  return (RC.mac[mod_idP]->UE_list.active[ue_idP]);
 }
 
 /*
@@ -1977,6 +1980,11 @@ uint8_t find_active_UEs(module_id_t module_idP,int CC_id){
 }
 */
 
+int UE_BSR (uint8_t mod_id, uint8_t ue_id, uint8_t lcid) {
+
+  if (eNB_mac_inst == NULL) return 0;
+  return eNB_mac_inst[mod_id].UE_list.UE_template[UE_PCCID(mod_id,ue_id)][ue_id].bsr_info[lcid];
+}
 
 // get aggregation (L) form phy for a give UE
 unsigned char
@@ -2100,6 +2108,12 @@ int add_new_ue(module_id_t mod_idP, int cc_idP, rnti_t rntiP, int harq_pidP
     return (-1);
 }
 
+int  CC_id_rnti_downlink (uint8_t mod_id, int CC_index, uint16_t ue_rnti) {
+
+  return eNB_mac_inst[mod_id].UE_list.ordered_CCids[CC_index][ue_rnti];
+}
+
+
 //------------------------------------------------------------------------------
 int rrc_mac_remove_ue(module_id_t mod_idP, rnti_t rntiP)
 //------------------------------------------------------------------------------
diff --git a/openair2/LAYER2/MAC/eNB_scheduler_ulsch.c b/openair2/LAYER2/MAC/eNB_scheduler_ulsch.c
index 421eab7cd768f9c64997b280eba1a780a85359ea..035e4c5fa307c316721f8f1c307ac74c9ad65dd3 100644
--- a/openair2/LAYER2/MAC/eNB_scheduler_ulsch.c
+++ b/openair2/LAYER2/MAC/eNB_scheduler_ulsch.c
@@ -1115,6 +1115,7 @@ schedule_ulsch_rnti(module_id_t module_idP,
 	   for (n=0; n<UE_list->numactiveULCCs[UE_id]; n++) {
 	   CC_id = UE_list->ordered_ULCCids[n][UE_id];
 
+<<<<<<< HEAD
 	   if (mac_xface->get_eNB_UE_stats(module_idP,CC_id,rnti) == NULL) {
 	   LOG_W(MAC,"[eNB %d] frame %d subframe %d, UE %d/%x CC %d: no PHY context\n", module_idP,frameP,subframeP,UE_id,rnti,CC_id);
 	   drop_ue = 1;
@@ -1141,6 +1142,111 @@ schedule_ulsch_rnti(module_id_t module_idP,
 				       subframeP, rnti);
 		UE_list->UE_sched_ctrl[UE_id].ul_failure_timer = 0;
 		UE_list->UE_sched_ctrl[UE_id].ul_out_of_sync = 1;
+=======
+    // loop over all active UL CC_ids for this UE
+    for (n=0; n<UE_list->numactiveULCCs[UE_id]; n++) {
+      // This is the actual CC_id in the list
+      CC_id = UE_list->ordered_ULCCids[n][UE_id];
+      frame_parms = mac_xface->get_lte_frame_parms(module_idP,CC_id);
+      eNB_UE_stats = mac_xface->get_eNB_UE_stats(module_idP,CC_id,rnti);
+
+      aggregation=get_aggregation(get_bw_index(module_idP,CC_id), 
+				  eNB_UE_stats->DL_cqi[0],
+				  format0);
+      
+      if (CCE_allocation_infeasible(module_idP,CC_id,0,subframeP,aggregation,rnti)) {
+        LOG_W(MAC,"[eNB %d] frame %d subframe %d, UE %d/%x CC %d: not enough nCCE\n", module_idP,frameP,subframeP,UE_id,rnti,CC_id);
+        continue; // break;
+      } else{
+	LOG_D(MAC,"[eNB %d] frame %d subframe %d, UE %d/%x CC %d mode %s: aggregation level %d\n", 
+	      module_idP,frameP,subframeP,UE_id,rnti,CC_id, mode_string[eNB_UE_stats->mode], 1<<aggregation);
+      }
+
+
+      if (eNB_UE_stats->mode == PUSCH) { // ue has a ulsch channel
+
+        DCI_pdu = &eNB->common_channels[CC_id].DCI_pdu;
+        UE_template   = &UE_list->UE_template[CC_id][UE_id];
+        UE_sched_ctrl = &UE_list->UE_sched_ctrl[UE_id];
+
+        if (mac_xface->get_ue_active_harq_pid(module_idP,CC_id,rnti,frameP,subframeP,&harq_pid,&round,openair_harq_UL) == -1 ) {
+          LOG_W(MAC,"[eNB %d] Scheduler Frame %d, subframeP %d: candidate harq_pid from PHY for UE %d CC %d RNTI %x\n",
+                module_idP,frameP,subframeP, UE_id, CC_id, rnti);
+          continue;
+        } else
+          LOG_T(MAC,"[eNB %d] Frame %d, subframeP %d, UE %d CC %d : got harq pid %d  round %d (rnti %x,mode %s)\n",
+                module_idP,frameP,subframeP,UE_id,CC_id, harq_pid, round,rnti,mode_string[eNB_UE_stats->mode]);
+
+	PHY_vars_eNB_g[module_idP][CC_id]->pusch_stats_BO[UE_id][(frameP*10)+subframeP] = UE_template->ul_total_buffer;
+	VCD_SIGNAL_DUMPER_DUMP_VARIABLE_BY_NAME(VCD_SIGNAL_DUMPER_VARIABLES_UE0_BO,PHY_vars_eNB_g[module_idP][CC_id]->pusch_stats_BO[UE_id][(frameP*10)+subframeP]);	
+        if (((UE_is_to_be_scheduled(module_idP,CC_id,UE_id)>0)) || (round>0))// || ((frameP%10)==0))
+          // if there is information on bsr of DCCH, DTCH or if there is UL_SR, or if there is a packet to retransmit, or we want to schedule a periodic feedback every 10 frames
+        {
+	  LOG_D(MAC,"[eNB %d][PUSCH] Frame %d subframe %d Scheduling UE %d/%x in round %d(SR %d,UL_inactivity timer %d,UL_failure timer %d)\n",
+		module_idP,frameP,subframeP,UE_id,rnti,round,UE_template->ul_SR,
+		UE_sched_ctrl->ul_inactivity_timer,
+		UE_sched_ctrl->ul_failure_timer);
+          // reset the scheduling request
+          UE_template->ul_SR = 0;
+          status = mac_eNB_get_rrc_status(module_idP,rnti);
+	  if (status < RRC_CONNECTED)
+	    cqi_req = 0;
+	  else if (UE_sched_ctrl->cqi_req_timer>30) {
+	    cqi_req = 1;
+	    UE_sched_ctrl->cqi_req_timer=0;
+	  }
+	  else
+	    cqi_req = 0;
+
+          //power control
+          //compute the expected ULSCH RX power (for the stats)
+
+          // this is the normalized RX power and this should be constant (regardless of mcs
+          normalized_rx_power = eNB_UE_stats->UL_rssi[0];
+          target_rx_power = mac_xface->get_target_pusch_rx_power(module_idP,CC_id);
+
+          // this assumes accumulated tpc
+	  // make sure that we are only sending a tpc update once a frame, otherwise the control loop will freak out
+	  int32_t framex10psubframe = UE_template->pusch_tpc_tx_frame*10+UE_template->pusch_tpc_tx_subframe;
+          if (((framex10psubframe+10)<=(frameP*10+subframeP)) || //normal case
+	      ((framex10psubframe>(frameP*10+subframeP)) && (((10240-framex10psubframe+frameP*10+subframeP)>=10)))) //frame wrap-around
+	    {
+	    UE_template->pusch_tpc_tx_frame=frameP;
+	    UE_template->pusch_tpc_tx_subframe=subframeP;
+            if (normalized_rx_power>(target_rx_power+1)) {
+              tpc = 0; //-1
+              tpc_accumulated--;
+            } else if (normalized_rx_power<(target_rx_power-1)) {
+              tpc = 2; //+1
+              tpc_accumulated++;
+            } else {
+              tpc = 1; //0
+            }
+          } else {
+            tpc = 1; //0
+          }
+
+	  if (tpc!=1) {
+	    LOG_D(MAC,"[eNB %d] ULSCH scheduler: frame %d, subframe %d, harq_pid %d, tpc %d, accumulated %d, normalized/target rx power %d/%d\n",
+		  module_idP,frameP,subframeP,harq_pid,tpc,
+		  tpc_accumulated,normalized_rx_power,target_rx_power);
+	  }
+
+          // new transmission
+          if (round==0) {
+
+            ndi = 1-UE_template->oldNDI_UL[harq_pid];
+            UE_template->oldNDI_UL[harq_pid]=ndi;
+	    UE_list->eNB_UE_stats[CC_id][UE_id].normalized_rx_power=normalized_rx_power;
+	    UE_list->eNB_UE_stats[CC_id][UE_id].target_rx_power=target_rx_power;
+	    UE_list->eNB_UE_stats[CC_id][UE_id].ulsch_mcs1=UE_template->pre_assigned_mcs_ul;
+            mcs = UE_template->pre_assigned_mcs_ul;//cmin (UE_template->pre_assigned_mcs_ul, openair_daq_vars.target_ue_ul_mcs); // adjust, based on user-defined MCS
+            if (UE_template->pre_allocated_rb_table_index_ul >=0) {
+              rb_table_index=UE_template->pre_allocated_rb_table_index_ul;
+            } else {
+	      mcs=10;//cmin (10, openair_daq_vars.target_ue_ul_mcs);
+              rb_table_index=13; // for PHR
+>>>>>>> feature-68-enb-agent
 	    }
 	    continue;
 	}
diff --git a/openair2/LAYER2/MAC/flexran_agent_mac_proto.h b/openair2/LAYER2/MAC/flexran_agent_mac_proto.h
index d3170aaf919e2a24e4599399729b4078e9d6c254..be61fa159027683e160d16d4e7d8088a5701004b 100644
--- a/openair2/LAYER2/MAC/flexran_agent_mac_proto.h
+++ b/openair2/LAYER2/MAC/flexran_agent_mac_proto.h
@@ -39,19 +39,25 @@
 /*
  * slice specific scheduler 
  */
-typedef void (*slice_scheduler) (module_id_t mod_id,
-				 int slice_id,
-				 uint32_t frame,
-				 uint32_t subframe,
-				 int *mbsfn_flag,
-				 Protocol__FlexranMessage ** dl_info);
+typedef void (*slice_scheduler_dl)(module_id_t mod_id,
+				int slice_id,
+				uint32_t frame,
+				uint32_t subframe,
+				int *mbsfn_flag,
+				Protocol__FlexranMessage **dl_info);
 
+typedef void (*slice_scheduler_ul)(module_id_t mod_id, 
+				frame_t frame,
+				unsigned char cooperation_flag,
+				uint32_t      subframe,
+				unsigned char sched_subframe,
+				Protocol__FlexranMessage **ul_info);
 
 
 /*
  * top level flexran scheduler used by the eNB scheduler
  */
-void flexran_schedule_ue_spec_default(mid_t mod_id,
+void flexran_schedule_ue_dl_spec_default(mid_t mod_id,
 				      uint32_t frame,
 				      uint32_t subframe,
 				      int *mbsfn_flag,
@@ -102,6 +108,7 @@ flexran_schedule_ue_spec_be(mid_t mod_id,
  * common flexran scheduler function
  */
 void
+<<<<<<< HEAD
 flexran_schedule_ue_spec_common(mid_t mod_id,
 				int slice_id,
 				uint32_t frame,
@@ -179,22 +186,122 @@ void _dlsch_scheduler_pre_processor_allocate(module_id_t Mod_id,
 					     unsigned char
 					     MIMO_mode_indicator
 					     [MAX_NUM_CCs][N_RBG_MAX]);
+=======
+flexran_schedule_ue_dl_spec_common(mid_t   mod_id,
+				int       slice_id, 
+				uint32_t      frame,
+				uint32_t      subframe,
+				int           *mbsfn_flag,
+				Protocol__FlexranMessage **dl_info);
+
+void
+flexran_schedule_ue_ul_spec_default(mid_t   mod_id,
+				 uint32_t      frame,
+				 uint32_t      cooperation_flag,
+				 int           subframe,
+				 unsigned char sched_subframe,
+				 Protocol__FlexranMessage **ul_info);
+
+
+uint16_t flexran_nb_rbs_allowed_slice(float rb_percentage, 
+				      int total_rbs);
+
+int flexran_slice_member(int UE_id, 
+			 int slice_id);
+
+int flexran_slice_maxmcs(int slice_id) ;
+
+/* Downlink Primitivies */
+
+void _store_dlsch_buffer (module_id_t Mod_id,
+			  int         slice_id,
+			  frame_t     frameP,
+			  sub_frame_t subframeP);
+
+
+void _assign_rbs_required (module_id_t Mod_id,
+			   int         slice_id,
+			   frame_t     frameP,
+			   sub_frame_t subframe,
+			   uint16_t    nb_rbs_required[MAX_NUM_CCs][NUMBER_OF_UE_MAX],
+			   uint16_t    nb_rbs_allowed_slice[MAX_NUM_CCs][MAX_NUM_SLICES], 
+			   int         min_rb_unit[MAX_NUM_CCs]);
+
+
+/* Uplink Primitivies */
+
+// void _sort_ue_ul (module_id_t module_idP,int frameP, sub_frame_t subframeP);
+
+void _assign_max_mcs_min_rb(module_id_t module_idP, int slice_id, int frameP, sub_frame_t subframeP, uint16_t *first_rb);
+
+
+void _ulsch_scheduler_pre_processor(module_id_t module_idP,
+                                   int slice_id,                                   
+                                   int frameP,
+                                   sub_frame_t subframeP,
+                                   uint16_t *first_rb);
+
+
+void flexran_agent_schedule_ulsch_rnti(module_id_t   module_idP,
+                         unsigned char cooperation_flag,
+                         frame_t       frameP,
+                         sub_frame_t   subframeP,
+                         unsigned char sched_subframe,
+                         uint16_t     *first_rb);
+
+/* Downlink Primitives */
+
+void _dlsch_scheduler_pre_processor (module_id_t   Mod_id,
+				     int           slice_id,
+				     frame_t       frameP,
+				     sub_frame_t   subframeP,
+				     int           N_RBG[MAX_NUM_CCs],
+				     int           *mbsfn_flag);
+
+void _dlsch_scheduler_pre_processor_reset (int module_idP,
+					   int UE_id,
+					   uint8_t  CC_id,
+					   int frameP,
+					   int subframeP,					  
+					   int N_RBG,
+					   uint16_t nb_rbs_required[MAX_NUM_CCs][NUMBER_OF_UE_MAX],
+					   uint16_t nb_rbs_required_remaining[MAX_NUM_CCs][NUMBER_OF_UE_MAX],
+					   uint16_t nb_rbs_allowed_slice[MAX_NUM_CCs][MAX_NUM_SLICES],
+					   unsigned char rballoc_sub[MAX_NUM_CCs][N_RBG_MAX],
+					   unsigned char MIMO_mode_indicator[MAX_NUM_CCs][N_RBG_MAX]);
+
+void _dlsch_scheduler_pre_processor_allocate (module_id_t   Mod_id,
+					      int           UE_id,
+					      uint8_t       CC_id,
+					      int           N_RBG,
+					      int           transmission_mode,
+					      int           min_rb_unit,
+					      uint8_t       N_RB_DL,
+					      uint16_t      nb_rbs_required[MAX_NUM_CCs][NUMBER_OF_UE_MAX],
+					      uint16_t      nb_rbs_required_remaining[MAX_NUM_CCs][NUMBER_OF_UE_MAX],
+					      unsigned char rballoc_sub[MAX_NUM_CCs][N_RBG_MAX],
+					      unsigned char MIMO_mode_indicator[MAX_NUM_CCs][N_RBG_MAX]);
+>>>>>>> feature-68-enb-agent
 
 /*
  * Default scheduler used by the eNB agent
  */
-void flexran_schedule_ue_spec_default(mid_t mod_id, uint32_t frame,
-				      uint32_t subframe, int *mbsfn_flag,
-				      Protocol__FlexranMessage ** dl_info);
+void flexran_schedule_ue_dl_spec_default(mid_t mod_id, uint32_t frame, uint32_t subframe,
+				      int *mbsfn_flag, Protocol__FlexranMessage **dl_info);
+
+/*
+  Uplink scheduler used by MAC agent
+*/
+
+void flexran_agent_schedule_ulsch_ue_spec(module_id_t module_idP,  frame_t frameP,  unsigned char cooperation_flag,
+		    sub_frame_t subframeP, 
+		    unsigned char sched_subframe, Protocol__FlexranMessage **ul_info);
 
 /*
  * Data plane function for applying the DL decisions of the scheduler
  */
-void flexran_apply_dl_scheduling_decisions(mid_t mod_id, uint32_t frame,
-					   uint32_t subframe,
-					   int *mbsfn_flag,
-					   Protocol__FlexranMessage *
-					   dl_scheduling_info);
+void flexran_apply_scheduling_decisions(mid_t mod_id, uint32_t frame, uint32_t subframe, int *mbsfn_flag,
+					   Protocol__FlexranMessage *dl_scheduling_info);
 
 /*
  * Data plane function for applying the UE specific DL decisions of the scheduler
diff --git a/openair2/LAYER2/MAC/flexran_agent_scheduler_dataplane.c b/openair2/LAYER2/MAC/flexran_agent_scheduler_dataplane.c
index 44052a8749191780e5c6c62c39935bfa91081792..6b1c2579b2ee47092ca736afeece062bf545e729 100644
--- a/openair2/LAYER2/MAC/flexran_agent_scheduler_dataplane.c
+++ b/openair2/LAYER2/MAC/flexran_agent_scheduler_dataplane.c
@@ -90,7 +90,6 @@ flexran_apply_dl_scheduling_decisions(mid_t mod_id,
 
 }
 
-
 void
 flexran_apply_ue_spec_scheduling_decisions(mid_t mod_id,
 					   uint32_t frame,
@@ -288,10 +287,6 @@ flexran_apply_ue_spec_scheduling_decisions(mid_t mod_id,
 					       NULL,	// contention res id
 					       padding, post_padding);
 
-
-
-
-
 #ifdef DEBUG_eNB_SCHEDULER
 		LOG_T(MAC, "[eNB %d] First 16 bytes of DLSCH : \n");
 
diff --git a/openair2/LAYER2/MAC/flexran_agent_scheduler_dlsch_ue.c b/openair2/LAYER2/MAC/flexran_agent_scheduler_dlsch_ue.c
index 3a491bd7ea8488d31953d8084935517a6ab81e19..a988862542da31db73f8c600330aa36dffa0ff50 100644
--- a/openair2/LAYER2/MAC/flexran_agent_scheduler_dlsch_ue.c
+++ b/openair2/LAYER2/MAC/flexran_agent_scheduler_dlsch_ue.c
@@ -50,7 +50,7 @@
 #include "RRC/L2_INTERFACE/openair_rrc_L2_interface.h"
 
 #include "ENB_APP/flexran_agent_defs.h"
-
+#include "flexran_agent_ran_api.h"
 #include "pdcp.h"
 
 #include "header.pb-c.h"
@@ -96,10 +96,11 @@ int slicing_strategy = UEID_TO_SLICEID;
 int slicing_strategy_current = UEID_TO_SLICEID;
 
 // RB share for each slice for past and current time
-float slice_percentage[MAX_NUM_SLICES] = { 1.0, 0.0, 0.0, 0.0 };
-float slice_percentage_current[MAX_NUM_SLICES] = { 1.0, 0.0, 0.0, 0.0 };
-
+float avg_slice_percentage=0.25;
+float slice_percentage[MAX_NUM_SLICES] = {1.0, 0.0, 0.0, 0.0};
+float slice_percentage_current[MAX_NUM_SLICES] = {1.0, 0.0, 0.0, 0.0};
 float total_slice_percentage = 0;
+float total_slice_percentage_current = 0;
 
 // MAX MCS for each slice for past and current time
 int slice_maxmcs[MAX_NUM_SLICES] = { 28, 28, 28, 28 };
@@ -117,7 +118,7 @@ char *dl_scheduler_type[MAX_NUM_SLICES] =
 };
 
 // pointer to the slice specific scheduler 
-slice_scheduler slice_sched[MAX_NUM_SLICES] = { 0 };
+slice_scheduler_dl slice_sched_dl[MAX_NUM_SLICES] = {0};
 
 
 /**
@@ -274,74 +275,45 @@ _assign_rbs_required(module_id_t Mod_id,
 		}
 	    }
 	}
-
 	/* NN --> RK
 	 * check the index of UE_template"
 	 */
-	if (UE_list->UE_template[pCCid][UE_id].dl_buffer_total > 0) {
-	    LOG_D(MAC, "[preprocessor] assign RB for UE %d\n", UE_id);
-
-	    for (i = 0; i < UE_list->numactiveCCs[UE_id]; i++) {
-		CC_id = UE_list->ordered_CCids[i][UE_id];
-		eNB_UE_stats[CC_id] =
-		    mac_xface->get_eNB_UE_stats(Mod_id, CC_id, rnti);
-
-		if (cqi_to_mcs[flexran_get_ue_wcqi(Mod_id, UE_id)] == 0) {	//eNB_UE_stats[CC_id]->dlsch_mcs1==0) {
-		    nb_rbs_required[CC_id][UE_id] = 4;	// don't let the TBS get too small
-		} else {
-		    nb_rbs_required[CC_id][UE_id] = min_rb_unit[CC_id];
-		}
-
-		TBS =
-		    mac_xface->get_TBS_DL(cqi_to_mcs
-					  [flexran_get_ue_wcqi
-					   (Mod_id, UE_id)],
-					  nb_rbs_required[CC_id][UE_id]);
-		nb_rbs_allowed_slice[CC_id][slice_id] =
-		    flexran_nb_rbs_allowed_slice(slice_percentage
-						 [slice_id],
-						 flexran_get_N_RB_DL
-						 (Mod_id, CC_id));
-		LOG_D(MAC,
-		      "[preprocessor] start RB assignement for UE %d CC_id %d dl buffer %d (RB unit %d, MCS %d, TBS %d) \n",
-		      UE_id, CC_id,
-		      UE_list->UE_template[pCCid][UE_id].dl_buffer_total,
-		      nb_rbs_required[CC_id][UE_id],
-		      flexran_get_ue_wcqi(Mod_id, UE_id), TBS);
-
-		/* calculating required number of RBs for each UE */
-		while (TBS <
-		       UE_list->UE_template[pCCid][UE_id].
-		       dl_buffer_total) {
-		    nb_rbs_required[CC_id][UE_id] += min_rb_unit[CC_id];
-
-		    if (nb_rbs_required[CC_id][UE_id] >
-			nb_rbs_allowed_slice[CC_id][slice_id]) {
-			TBS =
-			    mac_xface->get_TBS_DL(flexran_get_ue_wcqi
-						  (Mod_id, UE_id),
-						  nb_rbs_allowed_slice
-						  [CC_id]
-						  [slice_id]);
-			nb_rbs_required[CC_id][UE_id] =
-			    nb_rbs_allowed_slice[CC_id][slice_id];
-			break;
-		    }
-
-		    TBS =
-			mac_xface->get_TBS_DL(cqi_to_mcs
-					      [flexran_get_ue_wcqi
-					       (Mod_id, UE_id)],
-					      nb_rbs_required[CC_id]
-					      [UE_id]);
-		}		// end of while
-
-		LOG_D(MAC,
-		      "[eNB %d][SLICE %d] Frame %d: UE %d on CC %d: RB unit %d,  nb_required RB %d (TBS %d, mcs %d)\n",
-		      Mod_id, slice_id, frameP, UE_id, CC_id,
-		      min_rb_unit[CC_id], nb_rbs_required[CC_id][UE_id],
-		      TBS, cqi_to_mcs[flexran_get_ue_wcqi(Mod_id, UE_id)]);
+	if (UE_list->UE_template[pCCid][UE_id].dl_buffer_total> 0) {
+	  LOG_D(MAC,"[preprocessor] assign RB for UE %d\n",UE_id);
+	  
+	  for (i=0; i<UE_list->numactiveCCs[UE_id]; i++) {
+	    CC_id = UE_list->ordered_CCids[i][UE_id];
+	    eNB_UE_stats[CC_id] = mac_xface->get_eNB_UE_stats(Mod_id,CC_id,rnti);
+	    
+	    if (cqi_to_mcs[flexran_get_ue_wcqi(Mod_id, UE_id)] == 0) {//eNB_UE_stats[CC_id]->dlsch_mcs1==0) {
+	      nb_rbs_required[CC_id][UE_id] = 4;  // don't let the TBS get too small
+	    } else {
+	      nb_rbs_required[CC_id][UE_id] = min_rb_unit[CC_id];
 	    }
+	    
+	    TBS = mac_xface->get_TBS_DL(cqi_to_mcs[flexran_get_ue_wcqi(Mod_id, UE_id)], nb_rbs_required[CC_id][UE_id]);
+	    nb_rbs_allowed_slice[CC_id][slice_id] = flexran_nb_rbs_allowed_slice(slice_percentage[slice_id],
+										 flexran_get_N_RB_DL(Mod_id, CC_id));
+	    LOG_D(MAC,"[preprocessor] start RB assignement for UE %d CC_id %d dl buffer %d (RB unit %d, MCS %d, TBS %d) \n",
+		  UE_id, CC_id, UE_list->UE_template[pCCid][UE_id].dl_buffer_total,
+		  nb_rbs_required[CC_id][UE_id], flexran_get_ue_wcqi(Mod_id, UE_id), TBS);
+	    
+	    /* calculating required number of RBs for each UE */
+	    while (TBS < UE_list->UE_template[pCCid][UE_id].dl_buffer_total)  {
+	      nb_rbs_required[CC_id][UE_id] += min_rb_unit[CC_id];
+	      
+	      if (nb_rbs_required[CC_id][UE_id] > nb_rbs_allowed_slice[CC_id][slice_id]) {
+		TBS = mac_xface->get_TBS_DL(cqi_to_mcs[flexran_get_ue_wcqi(Mod_id, UE_id)], nb_rbs_allowed_slice[CC_id][slice_id]);
+		nb_rbs_required[CC_id][UE_id] = nb_rbs_allowed_slice[CC_id][slice_id];
+		break;
+	      }
+	      
+	      TBS = mac_xface->get_TBS_DL(cqi_to_mcs[flexran_get_ue_wcqi(Mod_id, UE_id)], nb_rbs_required[CC_id][UE_id]);
+	    } // end of while
+	    
+	    LOG_D(MAC,"[eNB %d][SLICE %d] Frame %d: UE %d on CC %d: RB unit %d,  nb_required RB %d (TBS %d, mcs %d)\n",
+		  Mod_id, slice_id,frameP,UE_id, CC_id,  min_rb_unit[CC_id], nb_rbs_required[CC_id][UE_id], TBS, cqi_to_mcs[flexran_get_ue_wcqi(Mod_id, UE_id)]);
+	  }
 	}
     }
 }
@@ -577,357 +549,393 @@ _dlsch_scheduler_pre_processor(module_id_t Mod_id,
 
 	}
     }
-
-    // Store the DLSCH buffer for each logical channel
-    _store_dlsch_buffer(Mod_id, slice_id, frameP, subframeP);
-
+    
+  
+    /* Store the DLSCH buffer for each logical channel for each UE */
+    _store_dlsch_buffer (Mod_id,slice_id,frameP,subframeP);
+    
     // Calculate the number of RBs required by each UE on the basis of logical channel's buffer
-    _assign_rbs_required(Mod_id, slice_id, frameP, subframeP,
-			 nb_rbs_required, nb_rbs_allowed_slice,
-			 min_rb_unit);
-
+    _assign_rbs_required (Mod_id,slice_id, frameP,subframeP,nb_rbs_required,nb_rbs_allowed_slice,min_rb_unit);
+    
     // Sorts the user on the basis of dlsch logical channel buffer and CQI
-    sort_UEs(Mod_id, frameP, subframeP);
-
+    sort_UEs (Mod_id,frameP,subframeP);
+    
     total_ue_count = 0;
-
+    
     // loop over all active UEs
-    for (i = UE_list->head; i >= 0; i = UE_list->next[i]) {
-	rnti = flexran_get_ue_crnti(Mod_id, i);
-	if (rnti == NOT_A_RNTI)
-	    continue;
-	if (UE_list->UE_sched_ctrl[i].ul_out_of_sync == 1)
-	    continue;
-
-	UE_id = i;
-
-	if (flexran_slice_member(UE_id, slice_id) == 0)
-	    continue;
-
-	if (!phy_stats_exist(Mod_id, rnti))
-	    continue;
-
-	for (ii = 0; ii < UE_num_active_CC(UE_list, UE_id); ii++) {
-	    CC_id = UE_list->ordered_CCids[ii][UE_id];
-	    ue_sched_ctl = &UE_list->UE_sched_ctrl[UE_id];
-	    ue_sched_ctl->max_allowed_rbs[CC_id] =
-		nb_rbs_allowed_slice[CC_id][slice_id];
-	    flexran_get_harq(Mod_id, CC_id, UE_id, frameP, subframeP,
-			     &harq_pid, &round);
-
-	    // if there is no available harq_process, skip the UE
-	    if (UE_list->UE_sched_ctrl[UE_id].harq_pid[CC_id] < 0)
-		continue;
-
-	    average_rbs_per_user[CC_id] = 0;
-
-	    frame_parms[CC_id] =
-		mac_xface->get_lte_frame_parms(Mod_id, CC_id);
-
-	    //      mac_xface->get_ue_active_harq_pid(Mod_id,CC_id,rnti,frameP,subframeP,&harq_pid,&round,0);
-
-	    if (round > 0) {
-		nb_rbs_required[CC_id][UE_id] =
-		    UE_list->UE_template[CC_id][UE_id].nb_rb[harq_pid];
-	    }
-	    //nb_rbs_required_remaining[UE_id] = nb_rbs_required[UE_id];
-	    if (nb_rbs_required[CC_id][UE_id] > 0) {
-		total_ue_count = total_ue_count + 1;
-	    }
-	    // hypotetical assignement
-	    /*
-	     * If schedule is enabled and if the priority of the UEs is modified
-	     * The average rbs per logical channel per user will depend on the level of
-	     * priority. Concerning the hypothetical assignement, we should assign more
-	     * rbs to prioritized users. Maybe, we can do a mapping between the
-	     * average rbs per user and the level of priority or multiply the average rbs
-	     * per user by a coefficient which represents the degree of priority.
-	     */
-
-	    if (total_ue_count == 0) {
-		average_rbs_per_user[CC_id] = 0;
-	    } else if ((min_rb_unit[CC_id] * total_ue_count) <=
-		       nb_rbs_allowed_slice[CC_id][slice_id]) {
-		average_rbs_per_user[CC_id] =
-		    (uint16_t) floor(nb_rbs_allowed_slice[CC_id][slice_id]
-				     / total_ue_count);
-	    } else {
-		average_rbs_per_user[CC_id] = min_rb_unit[CC_id];	// consider the total number of use that can be scheduled UE
-	    }
+    for (i=UE_list->head; i>=0; i=UE_list->next[i]) { 
+      rnti = flexran_get_ue_crnti(Mod_id, i);
+      if(rnti == NOT_A_RNTI)
+	continue;
+      if (UE_list->UE_sched_ctrl[i].ul_out_of_sync == 1)
+	continue;
+      
+      UE_id = i;
+      
+      if (flexran_slice_member(UE_id, slice_id) == 0)
+	continue;
+      
+      if (!phy_stats_exist(Mod_id, rnti))
+	continue;
+      
+      for (ii=0; ii < UE_num_active_CC(UE_list,UE_id); ii++) {
+	CC_id = UE_list->ordered_CCids[ii][UE_id];
+	ue_sched_ctl = &UE_list->UE_sched_ctrl[UE_id];
+	ue_sched_ctl->max_allowed_rbs[CC_id]=nb_rbs_allowed_slice[CC_id][slice_id];
+	flexran_get_harq(Mod_id, CC_id, UE_id, frameP, subframeP, &harq_pid, &round, openair_harq_DL);
+	
+	// if there is no available harq_process, skip the UE
+	if (UE_list->UE_sched_ctrl[UE_id].harq_pid[CC_id]<0)
+	  continue;
+	
+	average_rbs_per_user[CC_id]=0;
+	
+	frame_parms[CC_id] = mac_xface->get_lte_frame_parms(Mod_id,CC_id);
+	
+	//      mac_xface->get_ue_active_harq_pid(Mod_id,CC_id,rnti,frameP,subframeP,&harq_pid,&round,0);
+	
+	if(round>0) {
+	  nb_rbs_required[CC_id][UE_id] = UE_list->UE_template[CC_id][UE_id].nb_rb[harq_pid];
+	}
+	
+	//nb_rbs_required_remaining[UE_id] = nb_rbs_required[UE_id];
+	if (nb_rbs_required[CC_id][UE_id] > 0) {
+	  total_ue_count = total_ue_count + 1;
+	}
+	
+	
+	// hypotetical assignement
+	/*
+	 * If schedule is enabled and if the priority of the UEs is modified
+	 * The average rbs per logical channel per user will depend on the level of
+	 * priority. Concerning the hypothetical assignement, we should assign more
+	 * rbs to prioritized users. Maybe, we can do a mapping between the
+	 * average rbs per user and the level of priority or multiply the average rbs
+	 * per user by a coefficient which represents the degree of priority.
+	 */
+	
+	if (total_ue_count == 0) {
+	  average_rbs_per_user[CC_id] = 0;
+	} else if( (min_rb_unit[CC_id] * total_ue_count) <= nb_rbs_allowed_slice[CC_id][slice_id] ) {
+	  average_rbs_per_user[CC_id] = (uint16_t) floor(nb_rbs_allowed_slice[CC_id][slice_id]/total_ue_count);
+	} else {
+	  average_rbs_per_user[CC_id] = min_rb_unit[CC_id]; // consider the total number of use that can be scheduled UE
 	}
+      }
     }
-
+    
     // note: nb_rbs_required is assigned according to total_buffer_dl
     // extend nb_rbs_required to capture per LCID RB required
-    for (i = UE_list->head; i >= 0; i = UE_list->next[i]) {
+    for(i=UE_list->head; i>=0; i=UE_list->next[i]) {
+      rnti = UE_RNTI(Mod_id,i);
+      
+      if(rnti == NOT_A_RNTI)
+	continue;
+      
+      if (UE_list->UE_sched_ctrl[i].ul_out_of_sync == 1)
+	continue;
+      
+      if (!phy_stats_exist(Mod_id, rnti))
+	continue;
+      
+      if (flexran_slice_member(i, slice_id) == 0)
+	continue;
+      
+      for (ii=0; ii<UE_num_active_CC(UE_list,i); ii++) {
+	CC_id = UE_list->ordered_CCids[ii][i];
+	
+	// control channel
+	if (mac_eNB_get_rrc_status(Mod_id,rnti) < RRC_RECONFIGURED) {
+	  nb_rbs_required_remaining_1[CC_id][i] = nb_rbs_required[CC_id][i];
+	} else {
+	  nb_rbs_required_remaining_1[CC_id][i] = cmin(average_rbs_per_user[CC_id],nb_rbs_required[CC_id][i]);
+	  
+	}
+      }
+      
+      // note: nb_rbs_required is assigned according to total_buffer_dl
+      // extend nb_rbs_required to capture per LCID RB required
+      for (i = UE_list->head; i >= 0; i = UE_list->next[i]) {
 	rnti = UE_RNTI(Mod_id, i);
-
+	
 	if (rnti == NOT_A_RNTI)
-	    continue;
-
+	  continue;
+	
 	if (UE_list->UE_sched_ctrl[i].ul_out_of_sync == 1)
-	    continue;
-
+	  continue;
+	
 	if (!phy_stats_exist(Mod_id, rnti))
-	    continue;
-
+	  continue;
+	
 	if (flexran_slice_member(i, slice_id) == 0)
-	    continue;
-
+	  continue;
+	
 	for (ii = 0; ii < UE_num_active_CC(UE_list, i); ii++) {
-	    CC_id = UE_list->ordered_CCids[ii][i];
-
-	    // control channel
-	    if (mac_eNB_get_rrc_status(Mod_id, rnti) < RRC_RECONFIGURED) {
-		nb_rbs_required_remaining_1[CC_id][i] =
-		    nb_rbs_required[CC_id][i];
-	    } else {
-		nb_rbs_required_remaining_1[CC_id][i] =
-		    cmin(average_rbs_per_user[CC_id],
-			 nb_rbs_required[CC_id][i]);
-
-	    }
+	  CC_id = UE_list->ordered_CCids[ii][i];
+	  
+	  // control channel
+	  if (mac_eNB_get_rrc_status(Mod_id, rnti) < RRC_RECONFIGURED) {
+	    nb_rbs_required_remaining_1[CC_id][i] =
+	      nb_rbs_required[CC_id][i];
+	  } else {
+	    nb_rbs_required_remaining_1[CC_id][i] =
+	      cmin(average_rbs_per_user[CC_id],
+		   nb_rbs_required[CC_id][i]);
+	    
+	  }
 	}
-    }
-
-    //Allocation to UEs is done in 2 rounds,
-    // 1st stage: average number of RBs allocated to each UE
-    // 2nd stage: remaining RBs are allocated to high priority UEs
-    for (r1 = 0; r1 < 2; r1++) {
-
+      }
+      
+      //Allocation to UEs is done in 2 rounds,
+      // 1st stage: average number of RBs allocated to each UE
+      // 2nd stage: remaining RBs are allocated to high priority UEs
+      for (r1 = 0; r1 < 2; r1++) {
+	
 	for (i = UE_list->head; i >= 0; i = UE_list->next[i]) {
-
-	    if (flexran_slice_member(i, slice_id) == 0)
-		continue;
-
-	    for (ii = 0; ii < UE_num_active_CC(UE_list, i); ii++) {
-		CC_id = UE_list->ordered_CCids[ii][i];
-
-		if (r1 == 0) {
-		    nb_rbs_required_remaining[CC_id][i] =
-			nb_rbs_required_remaining_1[CC_id][i];
-		} else {	// rb required based only on the buffer - rb allloctaed in the 1st round + extra reaming rb form the 1st round
-		    nb_rbs_required_remaining[CC_id][i] =
-			nb_rbs_required[CC_id][i] -
-			nb_rbs_required_remaining_1[CC_id][i] +
-			nb_rbs_required_remaining[CC_id][i];
-		}
-
-		if (nb_rbs_required[CC_id][i] > 0)
-		    LOG_D(MAC,
-			  "round %d : nb_rbs_required_remaining[%d][%d]= %d (remaining_1 %d, required %d,  pre_nb_available_rbs %d, N_RBG %d, rb_unit %d)\n",
-			  r1, CC_id, i,
-			  nb_rbs_required_remaining[CC_id][i],
-			  nb_rbs_required_remaining_1[CC_id][i],
-			  nb_rbs_required[CC_id][i],
-			  UE_list->UE_sched_ctrl[i].
-			  pre_nb_available_rbs[CC_id], N_RBG[CC_id],
-			  min_rb_unit[CC_id]);
-
+	  
+	  if (flexran_slice_member(i, slice_id) == 0)
+	    continue;
+	  
+	  for (ii = 0; ii < UE_num_active_CC(UE_list, i); ii++) {
+	    CC_id = UE_list->ordered_CCids[ii][i];
+	    
+	    if (r1 == 0) {
+	      nb_rbs_required_remaining[CC_id][i] =
+		nb_rbs_required_remaining_1[CC_id][i];
+	    } else {	// rb required based only on the buffer - rb allloctaed in the 1st round + extra reaming rb form the 1st round
+	      nb_rbs_required_remaining[CC_id][i] =
+		nb_rbs_required[CC_id][i] -
+		nb_rbs_required_remaining_1[CC_id][i] +
+		nb_rbs_required_remaining[CC_id][i];
 	    }
+	    
+	    if (nb_rbs_required[CC_id][i] > 0)
+	      LOG_D(MAC,
+		    "round %d : nb_rbs_required_remaining[%d][%d]= %d (remaining_1 %d, required %d,  pre_nb_available_rbs %d, N_RBG %d, rb_unit %d)\n",
+		    r1, CC_id, i,
+		    nb_rbs_required_remaining[CC_id][i],
+		    nb_rbs_required_remaining_1[CC_id][i],
+		    nb_rbs_required[CC_id][i],
+		    UE_list->UE_sched_ctrl[i].
+		    pre_nb_available_rbs[CC_id], N_RBG[CC_id],
+		    min_rb_unit[CC_id]);
+	    
+	  }
 	}
-
+	
 	if (total_ue_count > 0) {
-	    for (i = UE_list->head; i >= 0; i = UE_list->next[i]) {
-		UE_id = i;
-
-		if (flexran_slice_member(UE_id, slice_id) == 0)
-		    continue;
-
-		for (ii = 0; ii < UE_num_active_CC(UE_list, UE_id); ii++) {
-		    CC_id = UE_list->ordered_CCids[ii][UE_id];
-		    ue_sched_ctl = &UE_list->UE_sched_ctrl[UE_id];
-		    flexran_get_harq(Mod_id, CC_id, UE_id, frameP,
-				     subframeP, &harq_pid, &round);
-		    rnti = UE_RNTI(Mod_id, UE_id);
-
-		    // LOG_D(MAC,"UE %d rnti 0x\n", UE_id, rnti );
-		    if (rnti == NOT_A_RNTI)
-			continue;
-
-		    if (UE_list->UE_sched_ctrl[UE_id].ul_out_of_sync == 1)
-			continue;
-
-		    if (!phy_stats_exist(Mod_id, rnti))
-			continue;
-
-		    transmission_mode =
-			mac_xface->get_transmission_mode(Mod_id, CC_id,
-							 rnti);
-		    //rrc_status = mac_eNB_get_rrc_status(Mod_id,rnti);
-		    /* 1st allocate for the retx */
-
-		    // retransmission in data channels
-		    // control channel in the 1st transmission
-		    // data channel for all TM
-		    LOG_T(MAC,
-			  "calling dlsch_scheduler_pre_processor_allocate .. \n ");
-		    _dlsch_scheduler_pre_processor_allocate(Mod_id, UE_id,
-							    CC_id,
-							    N_RBG[CC_id],
-							    transmission_mode,
-							    min_rb_unit
-							    [CC_id],
-							    frame_parms
-							    [CC_id]->
-							    N_RB_DL,
-							    nb_rbs_required,
-							    nb_rbs_required_remaining,
-							    rballoc_sub,
-							    MIMO_mode_indicator);
-		}
+	  for (i = UE_list->head; i >= 0; i = UE_list->next[i]) {
+	    UE_id = i;
+	    
+	    if (flexran_slice_member(UE_id, slice_id) == 0)
+	      continue;
+	    
+	    for (ii = 0; ii < UE_num_active_CC(UE_list, UE_id); ii++) {
+	      CC_id = UE_list->ordered_CCids[ii][UE_id];
+	      ue_sched_ctl = &UE_list->UE_sched_ctrl[UE_id];
+	      flexran_get_harq(Mod_id, CC_id, UE_id, frameP,
+			       subframeP, &harq_pid, &round);
+	      rnti = UE_RNTI(Mod_id, UE_id);
+	      
+	      // LOG_D(MAC,"UE %d rnti 0x\n", UE_id, rnti );
+	      if (rnti == NOT_A_RNTI)
+		continue;
+	      
+	      if (UE_list->UE_sched_ctrl[UE_id].ul_out_of_sync == 1)
+		continue;
+	      
+	      if (!phy_stats_exist(Mod_id, rnti))
+		continue;
+	      
+	      transmission_mode =
+		mac_xface->get_transmission_mode(Mod_id, CC_id,
+						 rnti);
+	      //rrc_status = mac_eNB_get_rrc_status(Mod_id,rnti);
+	      /* 1st allocate for the retx */
+	      
+	      // retransmission in data channels
+	      // control channel in the 1st transmission
+	      // data channel for all TM
+	      LOG_T(MAC,
+		    "calling dlsch_scheduler_pre_processor_allocate .. \n ");
+	      _dlsch_scheduler_pre_processor_allocate(Mod_id, UE_id,
+						      CC_id,
+						      N_RBG[CC_id],
+						      transmission_mode,
+						      min_rb_unit
+						      [CC_id],
+						      frame_parms
+						      [CC_id]->
+						      N_RB_DL,
+						      nb_rbs_required,
+						      nb_rbs_required_remaining,
+						      rballoc_sub,
+						      MIMO_mode_indicator);
 	    }
+	  }
 	}			// total_ue_count
-    }				// end of for for r1 and r2
-
-    for (i = UE_list->head; i >= 0; i = UE_list->next[i]) {
+      }				// end of for for r1 and r2
+      
+      for (i = UE_list->head; i >= 0; i = UE_list->next[i]) {
 	UE_id = i;
 	ue_sched_ctl = &UE_list->UE_sched_ctrl[UE_id];
-
+	
 	if (flexran_slice_member(UE_id, slice_id) == 0)
+	  continue;
+        
+	for (ii=0; ii<UE_num_active_CC(UE_list,UE_id); ii++) {
+          CC_id = UE_list->ordered_CCids[ii][UE_id];
+	  flexran_get_harq(Mod_id, CC_id, UE_id, frameP, subframeP, &harq_pid, &round, openair_harq_DL);	  
+          rnti = UE_RNTI(Mod_id,UE_id);
+
+          // LOG_D(MAC,"UE %d rnti 0x\n", UE_id, rnti );
+          if(rnti == NOT_A_RNTI)
+            continue;
+
+	  if (UE_list->UE_sched_ctrl[UE_id].ul_out_of_sync == 1)
 	    continue;
 
-	for (ii = 0; ii < UE_num_active_CC(UE_list, UE_id); ii++) {
-	    CC_id = UE_list->ordered_CCids[ii][UE_id];
-	    //PHY_vars_eNB_g[Mod_id]->mu_mimo_mode[UE_id].dl_pow_off = dl_pow_off[UE_id];
-
-	    if (ue_sched_ctl->pre_nb_available_rbs[CC_id] > 0) {
-		LOG_D(MAC,
-		      "******************DL Scheduling Information for UE%d ************************\n",
-		      UE_id);
-		LOG_D(MAC, "dl power offset UE%d = %d \n", UE_id,
-		      ue_sched_ctl->dl_pow_off[CC_id]);
-		LOG_D(MAC,
-		      "***********RB Alloc for every subband for UE%d ***********\n",
-		      UE_id);
-
-		for (j = 0; j < N_RBG[CC_id]; j++) {
-		    //PHY_vars_eNB_g[Mod_id]->mu_mimo_mode[UE_id].rballoc_sub[i] = rballoc_sub_UE[CC_id][UE_id][i];
-		    LOG_D(MAC, "RB Alloc for UE%d and Subband%d = %d\n",
-			  UE_id, j,
-			  ue_sched_ctl->rballoc_sub_UE[CC_id][j]);
-		}
-
-		//PHY_vars_eNB_g[Mod_id]->mu_mimo_mode[UE_id].pre_nb_available_rbs = pre_nb_available_rbs[CC_id][UE_id];
-		LOG_D(MAC,
-		      "[eNB %d][SLICE %d] Total RBs allocated for UE%d = %d\n",
-		      Mod_id, slice_id, UE_id,
-		      ue_sched_ctl->pre_nb_available_rbs[CC_id]);
+	  if (ue_sched_ctl->pre_nb_available_rbs[CC_id] > 0) {
+	    LOG_D(MAC,
+		  "******************DL Scheduling Information for UE%d ************************\n",
+		  UE_id);
+	    LOG_D(MAC, "dl power offset UE%d = %d \n", UE_id,
+		  ue_sched_ctl->dl_pow_off[CC_id]);
+	    LOG_D(MAC,
+		  "***********RB Alloc for every subband for UE%d ***********\n",
+		  UE_id);
+	    
+	    for (j = 0; j < N_RBG[CC_id]; j++) {
+	      //PHY_vars_eNB_g[Mod_id]->mu_mimo_mode[UE_id].rballoc_sub[i] = rballoc_sub_UE[CC_id][UE_id][i];
+	      LOG_D(MAC, "RB Alloc for UE%d and Subband%d = %d\n",
+		    UE_id, j,
+		    ue_sched_ctl->rballoc_sub_UE[CC_id][j]);
 	    }
+	    
+	    //PHY_vars_eNB_g[Mod_id]->mu_mimo_mode[UE_id].pre_nb_available_rbs = pre_nb_available_rbs[CC_id][UE_id];
+	    LOG_D(MAC,
+		  "[eNB %d][SLICE %d] Total RBs allocated for UE%d = %d\n",
+		  Mod_id, slice_id, UE_id,
+		  ue_sched_ctl->pre_nb_available_rbs[CC_id]);
+	  }
 	}
+      }
     }
 }
 
 #define SF05_LIMIT 1
 
 /*
- * Main scheduling functions to support slicing
+ * Main Downlink Slicing
  *
  */
 
 void
-flexran_schedule_ue_spec_default(mid_t mod_id,
-				 uint32_t frame,
-				 uint32_t subframe,
-				 int *mbsfn_flag,
-				 Protocol__FlexranMessage ** dl_info)
+flexran_schedule_ue_dl_spec_default(mid_t   mod_id,
+				 uint32_t      frame,
+				 uint32_t      subframe,
+				 int           *mbsfn_flag,
+				 Protocol__FlexranMessage **dl_info)
 //------------------------------------------------------------------------------
 {
-    int i = 0;
-
-    flexran_agent_mac_create_empty_dl_config(mod_id, dl_info);
-
-    for (i = 0; i < n_active_slices; i++) {
+  int i=0;
+  
+  flexran_agent_mac_create_empty_dl_config(mod_id, dl_info);
+ 
+  total_slice_percentage=0;
+  avg_slice_percentage=1.0/n_active_slices;
+  
+  // reset the slice percentage for inactive slices 
+  for (i = n_active_slices; i< MAX_NUM_SLICES; i++) {
+    slice_percentage[i]=0;
+  }
+  for (i = 0; i < n_active_slices; i++) {
+    if (slice_percentage[i] < 0 ){
+      LOG_W(MAC, "[eNB %d] frame %d subframe %d:invalid slice %d percentage %f. resetting to zero",
+	    mod_id, frame, subframe, i, slice_percentage[i]);
+      slice_percentage[i]=0;
+    }
+    total_slice_percentage+=slice_percentage[i];
+  }
+
+  for (i = 0; i < n_active_slices; i++) {
+    
+    // Load any updated functions
+    if (update_dl_scheduler[i] > 0 ) {
+      slice_sched_dl[i] = dlsym(NULL, dl_scheduler_type[i]); 
+      update_dl_scheduler[i] = 0;
+      update_dl_scheduler_current[i] = 0;
+      LOG_N(MAC,"update dl scheduler slice %d\n", i);
+    }
 
-	// Load any updated functions
-	if (update_dl_scheduler[i] > 0) {
-	    slice_sched[i] = dlsym(NULL, dl_scheduler_type[i]);
-	    update_dl_scheduler[i] = 0;
-	    update_dl_scheduler_current[i] = 0;
-	    slice_percentage_current[i] = slice_percentage[i];
-	    total_slice_percentage += slice_percentage[i];
-	    LOG_N(MAC, "update dl scheduler slice %d\n", i);
+    if (total_slice_percentage <= 1.0){ // the new total RB share is within the range
+
+      // check if the number of slices has changed, and log 
+      if (n_active_slices_current != n_active_slices ){
+	if ((n_active_slices > 0) && (n_active_slices <= MAX_NUM_SLICES)) {
+	  LOG_N(MAC,"[eNB %d]frame %d subframe %d: number of active DL slices has changed: %d-->%d\n",
+		mod_id, frame, subframe, n_active_slices_current, n_active_slices);
+	  
+	  n_active_slices_current = n_active_slices;
+	  
+	} else {
+	  LOG_W(MAC,"invalid number of DL slices %d, revert to the previous value %d\n",n_active_slices, n_active_slices_current);
+	  n_active_slices = n_active_slices_current;
 	}
-	// check if the number of slices has changed, and log 
-	if (n_active_slices_current != n_active_slices) {
-	    if ((n_active_slices > 0)
-		&& (n_active_slices <= MAX_NUM_SLICES)) {
-		LOG_N(MAC,
-		      "[eNB %d]frame %d subframe %d: number of active slices has changed: %d-->%d\n",
-		      mod_id, frame, subframe, n_active_slices_current,
-		      n_active_slices);
-		n_active_slices_current = n_active_slices;
-	    } else {
-		LOG_W(MAC,
-		      "invalid number of slices %d, revert to the previous value %d\n",
-		      n_active_slices, n_active_slices_current);
-		n_active_slices = n_active_slices_current;
-	    }
+      }
+      
+      // check if the slice rb share has changed, and log the console
+      if (slice_percentage_current[i] != slice_percentage[i]){ // new slice percentage
+	LOG_N(MAC,"[eNB %d][SLICE %d][DL] frame %d subframe %d: total percentage %f-->%f, slice RB percentage has changed: %f-->%f\n",
+	      mod_id, i, frame, subframe, total_slice_percentage_current, total_slice_percentage, slice_percentage_current[i], slice_percentage[i]);
+	total_slice_percentage_current= total_slice_percentage;
+	slice_percentage_current[i] = slice_percentage[i];
+	
+      } 
+ 
+      // check if the slice max MCS, and log the console
+      if (slice_maxmcs_current[i] != slice_maxmcs[i]){
+	if ((slice_maxmcs[i] >= 0) && (slice_maxmcs[i] < 29)){
+	  LOG_N(MAC,"[eNB %d][SLICE %d][DL] frame %d subframe %d: slice MAX MCS has changed: %d-->%d\n",
+		mod_id, i, frame, subframe, slice_maxmcs_current[i], slice_maxmcs[i]);
+	  slice_maxmcs_current[i] = slice_maxmcs[i];
+	} else {
+	  LOG_W(MAC,"[eNB %d][SLICE %d][DL] invalid slice max mcs %d, revert the previous value %d\n",mod_id, i, slice_maxmcs[i],slice_maxmcs_current[i]);
+	  slice_maxmcs[i]= slice_maxmcs_current[i];
 	}
-	// check if the slice rb share has changed, and log the console
-	if (slice_percentage_current[i] != slice_percentage[i]) {
-	    if ((slice_percentage[i] >= 0.0)
-		&& (slice_percentage[i] <= 1.0)) {
-		if ((total_slice_percentage - slice_percentage_current[i] +
-		     slice_percentage[i]) <= 1.0) {
-		    total_slice_percentage =
-			total_slice_percentage -
-			slice_percentage_current[i] + slice_percentage[i];
-		    LOG_N(MAC,
-			  "[eNB %d][SLICE %d] frame %d subframe %d: total percentage %f, slice RB percentage has changed: %f-->%f\n",
-			  mod_id, i, frame, subframe,
-			  total_slice_percentage,
-			  slice_percentage_current[i],
-			  slice_percentage[i]);
-		    slice_percentage_current[i] = slice_percentage[i];
-		} else {
-		    LOG_W(MAC,
-			  "[eNB %d][SLICE %d] invalid total RB share (%f->%f), revert the previous value (%f->%f)\n",
-			  mod_id, i, total_slice_percentage,
-			  total_slice_percentage -
-			  slice_percentage_current[i] +
-			  slice_percentage[i], slice_percentage[i],
-			  slice_percentage_current[i]);
-		    slice_percentage[i] = slice_percentage_current[i];
-
-		}
-	    } else {
-		LOG_W(MAC,
-		      "[eNB %d][SLICE %d] invalid slice RB share, revert the previous value (%f->%f)\n",
-		      mod_id, i, slice_percentage[i],
-		      slice_percentage_current[i]);
-		slice_percentage[i] = slice_percentage_current[i];
-
-	    }
-	}
-	// check if the slice max MCS, and log the console
-	if (slice_maxmcs_current[i] != slice_maxmcs[i]) {
-	    if ((slice_maxmcs[i] >= 0) && (slice_maxmcs[i] < 29)) {
-		LOG_N(MAC,
-		      "[eNB %d][SLICE %d] frame %d subframe %d: slice MAX MCS has changed: %d-->%d\n",
-		      mod_id, i, frame, subframe, slice_maxmcs_current[i],
-		      slice_maxmcs[i]);
-		slice_maxmcs_current[i] = slice_maxmcs[i];
-	    } else {
-		LOG_W(MAC,
-		      "[eNB %d][SLICE %d] invalid slice max mcs %d, revert the previous value %d\n",
-		      mod_id, i, slice_percentage[i], slice_percentage[i]);
-		slice_maxmcs[i] = slice_maxmcs_current[i];
-	    }
+      }
+      
+      // check if a new scheduler, and log the console
+      if (update_dl_scheduler_current[i] != update_dl_scheduler[i]){
+	LOG_N(MAC,"[eNB %d][SLICE %d][DL] frame %d subframe %d: DL scheduler for this slice is updated: %s \n",
+	      mod_id, i, frame, subframe, dl_scheduler_type[i]);
+	update_dl_scheduler_current[i] = update_dl_scheduler[i];
+      } 
+    
+    } else {
+      // here we can correct the values, e.g. reduce proportionally 
+      
+      if (n_active_slices == n_active_slices_current){
+	LOG_W(MAC,"[eNB %d][SLICE %d][DL] invalid total RB share (%f->%f), reduce proportionally the RB share by 0.1\n",
+	      mod_id,i,  
+	      total_slice_percentage_current, total_slice_percentage);
+	if (slice_percentage[i] >= avg_slice_percentage){
+	  slice_percentage[i]-=0.1;
+	  total_slice_percentage-=0.1;
 	}
-	// check if a new scheduler, and log the console
-	if (update_dl_scheduler_current[i] != update_dl_scheduler[i]) {
-	    LOG_N(MAC,
-		  "[eNB %d][SLICE %d] frame %d subframe %d: DL scheduler for this slice is updated: %s \n",
-		  mod_id, i, frame, subframe, dl_scheduler_type[i]);
-	    update_dl_scheduler_current[i] = update_dl_scheduler[i];
-	}
-	// Run each enabled slice-specific schedulers one by one
-	//LOG_N(MAC,"[eNB %d]frame %d subframe %d slice %d: calling the scheduler\n", mod_id, frame, subframe,i);
-	slice_sched[i] (mod_id, i, frame, subframe, mbsfn_flag, dl_info);
-
+      } else {
+	LOG_W(MAC,"[eNB %d][SLICE %d][DL] invalid total RB share (%f->%f), revert the number of slice to its previous value (%d->%d)\n",
+	      mod_id,i,  
+	      total_slice_percentage_current, total_slice_percentage,
+	      n_active_slices, n_active_slices_current );
+	n_active_slices = n_active_slices_current;
+	slice_percentage[i] = slice_percentage_current[i];
+      }
     }
-
+    
+    // Run each enabled slice-specific schedulers one by one
+    slice_sched_dl[i](mod_id, i, frame, subframe, mbsfn_flag,dl_info);
+  }
 }
 
 uint16_t flexran_nb_rbs_allowed_slice(float rb_percentage, int total_rbs)
@@ -997,10 +1005,12 @@ flexran_schedule_ue_spec_embb(mid_t mod_id,
 			      int *mbsfn_flag,
 			      Protocol__FlexranMessage ** dl_info)
 {
-    flexran_schedule_ue_spec_common(mod_id,
-				    slice_id,
-				    frame, subframe, mbsfn_flag, dl_info);
-
+  flexran_schedule_ue_dl_spec_common(mod_id,
+				  slice_id,
+				  frame,
+				  subframe,
+				  mbsfn_flag,
+				  dl_info);
 }
 
 /* more conservative mcs allocation with high priority and the traffic qci */
@@ -1012,10 +1022,12 @@ flexran_schedule_ue_spec_urllc(mid_t mod_id,
 			       int *mbsfn_flag,
 			       Protocol__FlexranMessage ** dl_info)
 {
-    flexran_schedule_ue_spec_common(mod_id,
-				    slice_id,
-				    frame, subframe, mbsfn_flag, dl_info);
-
+  flexran_schedule_ue_dl_spec_common(mod_id,
+				  slice_id,
+				  frame,
+				  subframe,
+				  mbsfn_flag,
+				  dl_info);
 }
 
 /* constant rb allocation with low mcs with low priority and given the UE capabilities */
@@ -1027,11 +1039,12 @@ flexran_schedule_ue_spec_mmtc(mid_t mod_id,
 			      int *mbsfn_flag,
 			      Protocol__FlexranMessage ** dl_info)
 {
-
-    flexran_schedule_ue_spec_common(mod_id,
-				    slice_id,
-				    frame, subframe, mbsfn_flag, dl_info);
-
+  flexran_schedule_ue_dl_spec_common(mod_id,
+				  slice_id,
+				  frame,
+				  subframe,
+				  mbsfn_flag,
+				  dl_info);
 }
 
 /* regular rb and mcs allocation with low priority */
@@ -1043,21 +1056,22 @@ flexran_schedule_ue_spec_be(mid_t mod_id,
 			    int *mbsfn_flag,
 			    Protocol__FlexranMessage ** dl_info)
 {
-
-    flexran_schedule_ue_spec_common(mod_id,
-				    slice_id,
-				    frame, subframe, mbsfn_flag, dl_info);
-
+  flexran_schedule_ue_dl_spec_common(mod_id,
+				  slice_id,
+				  frame,
+				  subframe,
+				  mbsfn_flag,
+				  dl_info);
 }
 
 //------------------------------------------------------------------------------
 void
-flexran_schedule_ue_spec_common(mid_t mod_id,
-				int slice_id,
-				uint32_t frame,
-				uint32_t subframe,
-				int *mbsfn_flag,
-				Protocol__FlexranMessage ** dl_info)
+flexran_schedule_ue_dl_spec_common(mid_t   mod_id,
+				int           slice_id, 
+				uint32_t      frame,
+				uint32_t      subframe,
+				int           *mbsfn_flag,
+				Protocol__FlexranMessage **dl_info)
 //------------------------------------------------------------------------------
 {
     uint8_t CC_id;
@@ -1104,902 +1118,697 @@ flexran_schedule_ue_spec_common(mid_t mod_id,
     }
 #endif
 
-    start_meas(&eNB->schedule_dlsch);
-    VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME
-	(VCD_SIGNAL_DUMPER_FUNCTIONS_SCHEDULE_DLSCH, VCD_FUNCTION_IN);
-
-    //weight = get_ue_weight(module_idP,UE_id);
-    aggregation = 1;		// set to the maximum aggregation level
-
-    for (CC_id = 0; CC_id < MAX_NUM_CCs; CC_id++) {
-	min_rb_unit[CC_id] = get_min_rb_unit(mod_id, CC_id);
-	// get number of PRBs less those used by common channels
-	total_nb_available_rb[CC_id] = flexran_get_N_RB_DL(mod_id, CC_id);
-	for (i = 0; i < flexran_get_N_RB_DL(mod_id, CC_id); i++)
-	    if (eNB->common_channels[CC_id].vrb_map[i] != 0)
-		total_nb_available_rb[CC_id]--;
-
-	N_RBG[CC_id] = flexran_get_N_RBG(mod_id, CC_id);
-
-	// store the global enb stats:
-	eNB->eNB_stats[CC_id].num_dlactive_UEs = UE_list->num_UEs;
-	eNB->eNB_stats[CC_id].available_prbs =
-	    total_nb_available_rb[CC_id];
-	eNB->eNB_stats[CC_id].total_available_prbs +=
-	    total_nb_available_rb[CC_id];
-	eNB->eNB_stats[CC_id].dlsch_bytes_tx = 0;
-	eNB->eNB_stats[CC_id].dlsch_pdus_tx = 0;
-    }
-
-    VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME
-	(VCD_SIGNAL_DUMPER_FUNCTIONS_DLSCH_PREPROCESSOR, VCD_FUNCTION_IN);
-
-    start_meas(&eNB->schedule_dlsch_preprocessor);
-    _dlsch_scheduler_pre_processor(mod_id,
-				   slice_id,
-				   frame, subframe, N_RBG, mbsfn_flag);
-    stop_meas(&eNB->schedule_dlsch_preprocessor);
-    VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME
-	(VCD_SIGNAL_DUMPER_FUNCTIONS_DLSCH_PREPROCESSOR, VCD_FUNCTION_OUT);
-
-    for (CC_id = 0; CC_id < MAX_NUM_CCs; CC_id++) {
-	LOG_D(MAC, "doing schedule_ue_spec for CC_id %d\n", CC_id);
-
-	if (mbsfn_flag[CC_id] > 0)
-	    continue;
-
-	for (UE_id = UE_list->head; UE_id >= 0;
-	     UE_id = UE_list->next[UE_id]) {
-
-	    rnti = flexran_get_ue_crnti(mod_id, UE_id);
-	    eNB_UE_stats =
-		mac_xface->get_eNB_UE_stats(mod_id, CC_id, rnti);
-	    ue_sched_ctl = &UE_list->UE_sched_ctrl[UE_id];
-
-	    if (eNB_UE_stats == NULL) {
-		LOG_D(MAC, "[eNB] Cannot find eNB_UE_stats\n");
-		//  mac_xface->macphy_exit("[MAC][eNB] Cannot find eNB_UE_stats\n");
-		continue;
-	    }
-
-	    if (flexran_slice_member(UE_id, slice_id) == 0)
-		continue;
-
-	    if (rnti == NOT_A_RNTI) {
-		LOG_D(MAC, "Cannot find rnti for UE_id %d (num_UEs %d)\n",
-		      UE_id, UE_list->num_UEs);
-		// mac_xface->macphy_exit("Cannot find rnti for UE_id");
-		continue;
-	    }
-
-	    switch (mac_xface->get_transmission_mode(mod_id, CC_id, rnti)) {
-	    case 1:
-	    case 2:
-	    case 7:
-		aggregation = get_aggregation(get_bw_index(mod_id, CC_id),
-					      eNB_UE_stats->DL_cqi[0],
-					      format1);
-		break;
-	    case 3:
-		aggregation = get_aggregation(get_bw_index(mod_id, CC_id),
-					      eNB_UE_stats->DL_cqi[0],
-					      format2A);
-		break;
-	    default:
-		LOG_W(MAC, "Unsupported transmission mode %d\n",
-		      mac_xface->get_transmission_mode(mod_id, CC_id,
-						       rnti));
-		aggregation = 2;
-	    }
-
-	    if ((ue_sched_ctl->pre_nb_available_rbs[CC_id] == 0) ||	// no RBs allocated 
-		CCE_allocation_infeasible(mod_id, CC_id, 0, subframe,
-					  aggregation, rnti)) {
-		LOG_D(MAC,
-		      "[eNB %d] Frame %d : no RB allocated for UE %d on CC_id %d: continue \n",
-		      mod_id, frame, UE_id, CC_id);
-		//if(mac_xface->get_transmission_mode(module_idP,rnti)==5)
-		continue;	//to next user (there might be rbs availiable for other UEs in TM5
-		// else
-		//  break;
-	    }
-
-	    if (flexran_get_duplex_mode(mod_id, CC_id) ==
-		PROTOCOL__FLEX_DUPLEX_MODE__FLDM_TDD) {
-		set_ue_dai(subframe,
-			   flexran_get_subframe_assignment(mod_id, CC_id),
-			   UE_id, CC_id, UE_list);
-		//TODO: update UL DAI after DLSCH scheduling
-		//set_ul_DAI(mod_id, UE_id, CC_id, frame, subframe,frame_parms);
-	    }
-
-	    channels_added = 0;
-
-	    // After this point all the UEs will be scheduled
-	    dl_data[num_ues_added] =
-		(Protocol__FlexDlData *)
-		malloc(sizeof(Protocol__FlexDlData));
-	    protocol__flex_dl_data__init(dl_data[num_ues_added]);
-	    dl_data[num_ues_added]->has_rnti = 1;
-	    dl_data[num_ues_added]->rnti = rnti;
-	    dl_data[num_ues_added]->n_rlc_pdu = 0;
-	    dl_data[num_ues_added]->has_serv_cell_index = 1;
-	    dl_data[num_ues_added]->serv_cell_index = CC_id;
-
-	    nb_available_rb = ue_sched_ctl->pre_nb_available_rbs[CC_id];
-	    flexran_get_harq(mod_id, CC_id, UE_id, frame, subframe,
-			     &harq_pid, &round);
-	    sdu_length_total = 0;
-	    mcs = cqi_to_mcs[flexran_get_ue_wcqi(mod_id, UE_id)];
-	    //      LOG_I(FLEXRAN_AGENT, "The MCS is %d\n", mcs);
-	    mcs = cmin(mcs, flexran_slice_maxmcs(slice_id));
-#ifdef EXMIMO
-
-	    if (mac_xface->get_transmission_mode(mod_id, CC_id, rnti) == 5) {
-		mcs = cqi_to_mcs[flexran_get_ue_wcqi(mod_id, UE_id)];
-		mcs = cmin(mcs, 16);
-	    }
-#endif
-
-	    // initializing the rb allocation indicator for each UE
-	    for (j = 0; j < flexran_get_N_RBG(mod_id, CC_id); j++) {
-		UE_list->
-		    UE_template[CC_id][UE_id].rballoc_subband[harq_pid][j]
-		    = 0;
-		rballoc_sub[j] = 0;
-	    }
-
-	    /* LOG_D(MAC,"[eNB %d] Frame %d: Scheduling UE %d on CC_id %d (rnti %x, harq_pid %d, round %d, rb %d, cqi %d, mcs %d, rrc %d)\n", */
-	    /*       mod_id, frame, UE_id, CC_id, rnti, harq_pid, round, nb_available_rb, */
-	    /*       eNB_UE_stats->DL_cqi[0], mcs, */
-	    /*       UE_list->eNB_UE_stats[CC_id][UE_id].rrc_status); */
-
-	    dl_dci =
-		(Protocol__FlexDlDci *)
-		malloc(sizeof(Protocol__FlexDlDci));
-	    protocol__flex_dl_dci__init(dl_dci);
-	    dl_data[num_ues_added]->dl_dci = dl_dci;
-
-
-	    dl_dci->has_rnti = 1;
-	    dl_dci->rnti = rnti;
-	    dl_dci->has_harq_process = 1;
-	    dl_dci->harq_process = harq_pid;
-
-	    /* process retransmission  */
-	    if (round > 0) {
-
-		LOG_D(FLEXRAN_AGENT,
-		      "There was a retransmission just now and the round was %d\n",
-		      round);
-
-		if (flexran_get_duplex_mode(mod_id, CC_id) ==
-		    PROTOCOL__FLEX_DUPLEX_MODE__FLDM_TDD) {
-		    UE_list->UE_template[CC_id][UE_id].DAI++;
-		    update_ul_dci(mod_id, CC_id, rnti,
-				  UE_list->UE_template[CC_id][UE_id].DAI);
-		    LOG_D(MAC,
-			  "DAI update: CC_id %d subframeP %d: UE %d, DAI %d\n",
-			  CC_id, subframe, UE_id,
-			  UE_list->UE_template[CC_id][UE_id].DAI);
-		}
-
-		mcs = UE_list->UE_template[CC_id][UE_id].mcs[harq_pid];
-
-		// get freq_allocation
-		nb_rb = UE_list->UE_template[CC_id][UE_id].nb_rb[harq_pid];
-
-		/*TODO: Must add this to FlexRAN agent API */
-		dci_tbs = mac_xface->get_TBS_DL(mcs, nb_rb);
-
-		if (nb_rb <= nb_available_rb) {
-
-		    if (nb_rb == ue_sched_ctl->pre_nb_available_rbs[CC_id]) {
-			for (j = 0; j < flexran_get_N_RBG(mod_id, CC_id); j++) {	// for indicating the rballoc for each sub-band
-			    UE_list->UE_template[CC_id][UE_id].
-				rballoc_subband[harq_pid][j] =
-				ue_sched_ctl->rballoc_sub_UE[CC_id][j];
-			}
-		    } else {
-			nb_rb_temp = nb_rb;
-			j = 0;
-
-			while ((nb_rb_temp > 0)
-			       && (j < flexran_get_N_RBG(mod_id, CC_id))) {
-			    if (ue_sched_ctl->rballoc_sub_UE[CC_id][j] ==
-				1) {
-				UE_list->
-				    UE_template[CC_id]
-				    [UE_id].rballoc_subband[harq_pid][j] =
-				    ue_sched_ctl->rballoc_sub_UE[CC_id][j];
-
-				if ((j ==
-				     flexran_get_N_RBG(mod_id, CC_id) - 1)
-				    &&
-				    ((flexran_get_N_RB_DL(mod_id, CC_id) ==
-				      25)
-				     || (flexran_get_N_RB_DL(mod_id, CC_id)
-					 == 50))) {
-				    nb_rb_temp =
-					nb_rb_temp - min_rb_unit[CC_id] +
-					1;
-				} else {
-				    nb_rb_temp =
-					nb_rb_temp - min_rb_unit[CC_id];
-				}
-			    }
-			    j = j + 1;
-			}
-		    }
-
-		    nb_available_rb -= nb_rb;
-		    PHY_vars_eNB_g[mod_id][CC_id]->
-			mu_mimo_mode[UE_id].pre_nb_available_rbs = nb_rb;
-		    PHY_vars_eNB_g[mod_id][CC_id]->
-			mu_mimo_mode[UE_id].dl_pow_off =
-			ue_sched_ctl->dl_pow_off[CC_id];
-
-		    for (j = 0; j < flexran_get_N_RBG(mod_id, CC_id); j++) {
-			PHY_vars_eNB_g[mod_id][CC_id]->
-			    mu_mimo_mode[UE_id].rballoc_sub[j] =
-			    UE_list->
-			    UE_template[CC_id][UE_id].rballoc_subband
-			    [harq_pid][j];
-			rballoc_sub[j] =
-			    UE_list->
-			    UE_template[CC_id][UE_id].rballoc_subband
-			    [harq_pid][j];
-		    }
-
-		    // Keep the old NDI, do not toggle
-		    ndi =
-			UE_list->UE_template[CC_id][UE_id].
-			oldNDI[harq_pid];
-		    tpc =
-			UE_list->UE_template[CC_id][UE_id].
-			oldTPC[harq_pid];
-		    UE_list->UE_template[CC_id][UE_id].mcs[harq_pid] = mcs;
-
-		    ue_has_transmission = 1;
-		    num_ues_added++;
-		} else {
-		    LOG_D(MAC,
-			  "[eNB %d] Frame %d CC_id %d : don't schedule UE %d, its retransmission takes more resources than we have\n",
-			  mod_id, frame, CC_id, UE_id);
-		    ue_has_transmission = 0;
-		}
-		//End of retransmission
-	    } else {		/* This is a potentially new SDU opportunity */
-		rlc_status.bytes_in_buffer = 0;
-		// Now check RLC information to compute number of required RBs
-		// get maximum TBS size for RLC request
-		//TBS = mac_xface->get_TBS(eNB_UE_stats->DL_cqi[0]<<1,nb_available_rb);
-		TBS = mac_xface->get_TBS_DL(mcs, nb_available_rb);
-		dci_tbs = TBS;
-		LOG_D(FLEXRAN_AGENT, "TBS is %d\n", TBS);
-
-		// check first for RLC data on DCCH
-		// add the length for  all the control elements (timing adv, drx, etc) : header + payload
-
-		ta_len = (ue_sched_ctl->ta_update != 0) ? 2 : 0;
-
-		dl_data[num_ues_added]->n_ce_bitmap = 2;
-		dl_data[num_ues_added]->ce_bitmap =
-		    (uint32_t *) calloc(2, sizeof(uint32_t));
-
-		if (ta_len > 0) {
-		    ce_flags |= PROTOCOL__FLEX_CE_TYPE__FLPCET_TA;
-		}
-
-		/*TODO: Add other flags if DRX and other CE are required */
-
-		// Add the control element flags to the flexran message
-		dl_data[num_ues_added]->ce_bitmap[0] = ce_flags;
-		dl_data[num_ues_added]->ce_bitmap[1] = ce_flags;
-
-		// TODO : Need to prioritize DRBs
-		// Loop through the UE logical channels (DCCH, DCCH1, DTCH for now)
-		header_len = 0;
-		header_len_last = 0;
-		sdu_length_total = 0;
-		for (j = 1; j < NB_RB_MAX; j++) {
-		    header_len += 3;
-		    // Need to see if we have space for data from this channel
-		    if (dci_tbs - ta_len - header_len - sdu_length_total >
-			0) {
-			LOG_D(MAC,
-			      "[TEST]Requested %d bytes from RLC buffer on channel %d during first call\n",
-			      dci_tbs - ta_len - header_len);
-			//If we have space, we need to see how much data we can request at most (if any available)
-			rlc_status = mac_rlc_status_ind(mod_id, rnti, mod_id, frame, subframe, ENB_FLAG_YES, MBMS_FLAG_NO, j, (dci_tbs - ta_len - header_len - sdu_length_total));	// transport block set size
-
-			//If data are available in channel j
-			if (rlc_status.bytes_in_buffer > 0) {
-			    LOG_D(MAC,
-				  "[TEST]Have %d bytes in DCCH buffer during first call\n",
-				  rlc_status.bytes_in_buffer);
-			    //Fill in as much as possible
-			    data_to_request =
-				cmin(dci_tbs - ta_len - header_len -
-				     sdu_length_total,
-				     rlc_status.bytes_in_buffer);
-			    LOG_D(FLEXRAN_AGENT,
-				  "Will request %d bytes from channel %d\n",
-				  data_to_request, j);
-			    if (data_to_request < 128) {	//The header will be one byte less
-				header_len--;
-				header_len_last = 2;
-			    } else {
-				header_len_last = 3;
-			    }
-			    /* if (j == 1 || j == 2) {
-			       data_to_request+=0; 
-			       } */
-			    LOG_D(MAC,
-				  "[TEST]Will request %d from channel %d\n",
-				  data_to_request, j);
-			    rlc_pdus[channels_added] =
-				(Protocol__FlexRlcPdu *)
-				malloc(sizeof(Protocol__FlexRlcPdu));
-			    protocol__flex_rlc_pdu__init(rlc_pdus
-							 [channels_added]);
-			    rlc_pdus[channels_added]->n_rlc_pdu_tb = 2;
-			    rlc_pdus[channels_added]->rlc_pdu_tb =
-				(Protocol__FlexRlcPduTb **)
-				malloc(sizeof(Protocol__FlexRlcPduTb *) *
-				       2);
-			    rlc_pdus[channels_added]->rlc_pdu_tb[0] =
-				(Protocol__FlexRlcPduTb *)
-				malloc(sizeof(Protocol__FlexRlcPduTb));
-			    protocol__flex_rlc_pdu_tb__init(rlc_pdus
-							    [channels_added]->rlc_pdu_tb
-							    [0]);
-			    rlc_pdus[channels_added]->
-				rlc_pdu_tb[0]->has_logical_channel_id = 1;
-			    rlc_pdus[channels_added]->
-				rlc_pdu_tb[0]->logical_channel_id = j;
-			    rlc_pdus[channels_added]->rlc_pdu_tb[0]->
-				has_size = 1;
-			    rlc_pdus[channels_added]->rlc_pdu_tb[0]->size =
-				data_to_request;
-			    rlc_pdus[channels_added]->rlc_pdu_tb[1] =
-				(Protocol__FlexRlcPduTb *)
-				malloc(sizeof(Protocol__FlexRlcPduTb));
-			    protocol__flex_rlc_pdu_tb__init(rlc_pdus
-							    [channels_added]->rlc_pdu_tb
-							    [1]);
-			    rlc_pdus[channels_added]->
-				rlc_pdu_tb[1]->has_logical_channel_id = 1;
-			    rlc_pdus[channels_added]->
-				rlc_pdu_tb[1]->logical_channel_id = j;
-			    rlc_pdus[channels_added]->rlc_pdu_tb[1]->
-				has_size = 1;
-			    rlc_pdus[channels_added]->rlc_pdu_tb[1]->size =
-				data_to_request;
-			    dl_data[num_ues_added]->n_rlc_pdu++;
-			    channels_added++;
-			    //Set this to the max value that we might request
-			    sdu_length_total += data_to_request;
-			} else {
-			    //Take back the assumption of a header for this channel
-			    header_len -= 3;
-			}	//End rlc_status.bytes_in_buffer <= 0
-		    }		//end of if dci_tbs - ta_len - header_len > 0
-		}		// End of iterating the logical channels
-
-		// Add rlc_pdus to the dl_data message
-		dl_data[num_ues_added]->rlc_pdu = (Protocol__FlexRlcPdu **)
-		    malloc(sizeof(Protocol__FlexRlcPdu *) *
-			   dl_data[num_ues_added]->n_rlc_pdu);
-		for (i = 0; i < dl_data[num_ues_added]->n_rlc_pdu; i++) {
-		    dl_data[num_ues_added]->rlc_pdu[i] = rlc_pdus[i];
-		}
-
-		if (header_len == 0) {
-		    LOG_D(FLEXRAN_AGENT, "Header was empty\n");
-		    header_len_last = 0;
-		}
-		// there is a payload
-		if ((dl_data[num_ues_added]->n_rlc_pdu > 0)) {
-		    // Now compute number of required RBs for total sdu length
-		    // Assume RAH format 2
-		    // adjust  header lengths
-		    LOG_D(FLEXRAN_AGENT, "We have %d bytes to transfer\n",
-			  sdu_length_total);
-		    if (header_len != 0) {
-			LOG_D(FLEXRAN_AGENT, "Header length was %d ",
-			      header_len);
-			header_len_last--;
-			header_len -= header_len_last;
-			LOG_D(FLEXRAN_AGENT, "so we resized it to %d\n",
-			      header_len);
-		    }
-
-		    /* if (header_len == 2 || header_len == 3) { //Only one SDU, remove length field */
-		    /*   header_len = 1; */
-		    /* } else { //Remove length field from the last SDU */
-		    /*   header_len--; */
-		    /* } */
-
-		    mcs_tmp = mcs;
-		    if (mcs_tmp == 0) {
-			nb_rb = 4;	// don't let the TBS get too small
-		    } else {
-			nb_rb = min_rb_unit[CC_id];
-		    }
-
-		    LOG_D(MAC,
-			  "[TEST]The initial number of resource blocks was %d\n",
-			  nb_rb);
-		    LOG_D(MAC, "[TEST] The initial mcs was %d\n", mcs_tmp);
-
-		    TBS = mac_xface->get_TBS_DL(mcs_tmp, nb_rb);
-		    LOG_D(MAC,
-			  "[TEST]The TBS during rate matching was %d\n",
-			  TBS);
-
-		    while (TBS < (sdu_length_total + header_len + ta_len)) {
-			nb_rb += min_rb_unit[CC_id];	//
-			LOG_D(MAC,
-			      "[TEST]Had to increase the number of RBs\n");
-			if (nb_rb > nb_available_rb) {	// if we've gone beyond the maximum number of RBs
-			    // (can happen if N_RB_DL is odd)
-			    TBS =
-				mac_xface->get_TBS_DL(mcs_tmp,
-						      nb_available_rb);
-			    nb_rb = nb_available_rb;
-			    break;
-			}
-
-			TBS = mac_xface->get_TBS_DL(mcs_tmp, nb_rb);
-		    }
-
-		    if (nb_rb == ue_sched_ctl->pre_nb_available_rbs[CC_id]) {
-			LOG_D(MAC,
-			      "[TEST]We had the exact number of rbs. Time to fill the rballoc subband\n");
-			for (j = 0; j < flexran_get_N_RBG(mod_id, CC_id); j++) {	// for indicating the rballoc for each sub-band
-			    UE_list->UE_template[CC_id][UE_id].
-				rballoc_subband[harq_pid][j] =
-				ue_sched_ctl->rballoc_sub_UE[CC_id][j];
-			}
-		    } else {
-			nb_rb_temp = nb_rb;
-			j = 0;
-			LOG_D(MAC,
-			      "[TEST]Will only partially fill the bitmap\n");
-			while ((nb_rb_temp > 0)
-			       && (j < flexran_get_N_RBG(mod_id, CC_id))) {
-			    if (ue_sched_ctl->rballoc_sub_UE[CC_id][j] ==
-				1) {
-				UE_list->
-				    UE_template[CC_id]
-				    [UE_id].rballoc_subband[harq_pid][j] =
-				    ue_sched_ctl->rballoc_sub_UE[CC_id][j];
-				if ((j ==
-				     flexran_get_N_RBG(mod_id, CC_id) - 1)
-				    &&
-				    ((flexran_get_N_RB_DL(mod_id, CC_id) ==
-				      25)
-				     || (flexran_get_N_RB_DL(mod_id, CC_id)
-					 == 50))) {
-				    nb_rb_temp =
-					nb_rb_temp - min_rb_unit[CC_id] +
-					1;
-				} else {
-				    nb_rb_temp =
-					nb_rb_temp - min_rb_unit[CC_id];
-				}
-			    }
-			    j = j + 1;
-			}
-		    }
-
-		    PHY_vars_eNB_g[mod_id][CC_id]->
-			mu_mimo_mode[UE_id].pre_nb_available_rbs = nb_rb;
-		    PHY_vars_eNB_g[mod_id][CC_id]->
-			mu_mimo_mode[UE_id].dl_pow_off =
-			ue_sched_ctl->dl_pow_off[CC_id];
-
-		    for (j = 0; j < flexran_get_N_RBG(mod_id, CC_id); j++) {
-			PHY_vars_eNB_g[mod_id][CC_id]->
-			    mu_mimo_mode[UE_id].rballoc_sub[j] =
-			    UE_list->
-			    UE_template[CC_id][UE_id].rballoc_subband
-			    [harq_pid][j];
-		    }
-
-		    // decrease mcs until TBS falls below required length
-		    while ((TBS > (sdu_length_total + header_len + ta_len))
-			   && (mcs_tmp > 0)) {
-			mcs_tmp--;
-			TBS = mac_xface->get_TBS_DL(mcs_tmp, nb_rb);
-		    }
-
-		    // if we have decreased too much or we don't have enough RBs, increase MCS
-		    while ((TBS < (sdu_length_total + header_len + ta_len))
-			   && (((ue_sched_ctl->dl_pow_off[CC_id] > 0)
-				&& (mcs_tmp < 28))
-			       || ((ue_sched_ctl->dl_pow_off[CC_id] == 0)
-				   && (mcs_tmp <= 15)))) {
-			mcs_tmp++;
-			TBS = mac_xface->get_TBS_DL(mcs_tmp, nb_rb);
-		    }
-
-		    dci_tbs = TBS;
-		    mcs = mcs_tmp;
-		    LOG_D(FLEXRAN_AGENT, "Final mcs was %d\n", mcs);
-
-		    dl_dci->has_aggr_level = 1;
-		    dl_dci->aggr_level = aggregation;
-
-		    UE_list->UE_template[CC_id][UE_id].nb_rb[harq_pid] =
-			nb_rb;
-
-		    if (flexran_get_duplex_mode(mod_id, CC_id) ==
-			PROTOCOL__FLEX_DUPLEX_MODE__FLDM_TDD) {
-			UE_list->UE_template[CC_id][UE_id].DAI++;
-			//  printf("DAI update: subframeP %d: UE %d, DAI %d\n",subframeP,UE_id,UE_list->UE_template[CC_id][UE_id].DAI);
-			//#warning only for 5MHz channel
-			update_ul_dci(mod_id, CC_id, rnti,
-				      UE_list->UE_template[CC_id][UE_id].
-				      DAI);
-		    }
-		    // do PUCCH power control
-		    // this is the normalized RX power
-		    normalized_rx_power = flexran_get_p0_pucch_dbm(mod_id, UE_id, CC_id);	//eNB_UE_stats->Po_PUCCH_dBm; 
-		    target_rx_power = flexran_get_p0_nominal_pucch(mod_id, CC_id) + 20;	//mac_xface->get_target_pucch_rx_power(mod_id, CC_id) + 20;
-		    // this assumes accumulated tpc
-		    // make sure that we are only sending a tpc update once a frame, otherwise the control loop will freak out
-		    int32_t framex10psubframe =
-			UE_list->UE_template[CC_id][UE_id].
-			pucch_tpc_tx_frame * 10 +
-			UE_list->UE_template[CC_id][UE_id].
-			pucch_tpc_tx_subframe;
-
-		    if (((framex10psubframe + 10) <= (frame * 10 + subframe)) ||	//normal case
-			((framex10psubframe > (frame * 10 + subframe)) && (((10240 - framex10psubframe + frame * 10 + subframe) >= 10))))	//frame wrap-around
-			if (flexran_get_p0_pucch_status
-			    (mod_id, UE_id, CC_id) == 1) {
-			    flexran_update_p0_pucch(mod_id, UE_id, CC_id);
-
-			    UE_list->
-				UE_template[CC_id]
-				[UE_id].pucch_tpc_tx_frame = frame;
-			    UE_list->
-				UE_template[CC_id]
-				[UE_id].pucch_tpc_tx_subframe = subframe;
-			    if (normalized_rx_power >
-				(target_rx_power + 1)) {
-				tpc = 0;	//-1
-				tpc_accumulated--;
-			    } else if (normalized_rx_power <
-				       (target_rx_power - 1)) {
-				tpc = 2;	//+1
-				tpc_accumulated++;
-			    } else {
-				tpc = 1;	//0
-			    }
-			    LOG_D(MAC,
-				  "[eNB %d] DLSCH scheduler: frame %d, subframe %d, harq_pid %d, tpc %d, accumulated %d, normalized/target rx power %d/%d\n",
-				  mod_id, frame, subframe, harq_pid, tpc,
-				  tpc_accumulated, normalized_rx_power,
-				  target_rx_power);
-			}	// Po_PUCCH has been updated 
-			else {
-			    tpc = 1;	//0
-			}	// time to do TPC update 
-		    else {
-			tpc = 1;	//0
-		    }
-
-		    for (i = 0;
-			 i <
-			 PHY_vars_eNB_g[mod_id][CC_id]->frame_parms.N_RBG;
-			 i++) {
-			rballoc_sub[i] =
-			    UE_list->
-			    UE_template[CC_id][UE_id].rballoc_subband
-			    [harq_pid][i];
-		    }
-
-		    // Toggle NDI
-		    LOG_D(MAC,
-			  "CC_id %d Frame %d, subframeP %d: Toggling Format1 NDI for UE %d (rnti %x/%d) oldNDI %d\n",
-			  CC_id, frame, subframe, UE_id,
-			  UE_list->UE_template[CC_id][UE_id].rnti,
-			  harq_pid,
-			  UE_list->UE_template[CC_id][UE_id].
-			  oldNDI[harq_pid]);
-		    UE_list->UE_template[CC_id][UE_id].oldNDI[harq_pid] =
-			1 -
-			UE_list->UE_template[CC_id][UE_id].
-			oldNDI[harq_pid];
-		    ndi =
-			UE_list->UE_template[CC_id][UE_id].
-			oldNDI[harq_pid];
-
-		    UE_list->UE_template[CC_id][UE_id].mcs[harq_pid] = mcs;
-		    UE_list->UE_template[CC_id][UE_id].oldTPC[harq_pid] =
-			tpc;
-
-		    // Increase the pointer for the number of scheduled UEs
-		    num_ues_added++;
-		    ue_has_transmission = 1;
-		} else {	// There is no data from RLC or MAC header, so don't schedule
-		    ue_has_transmission = 0;
-		}
-	    }			// End of new scheduling
-
-	    // If we has transmission or retransmission
-	    if (ue_has_transmission) {
-		switch (mac_xface->
-			get_transmission_mode(mod_id, CC_id, rnti)) {
-		case 1:
-		case 2:
-		default:
-		    dl_dci->has_res_alloc = 1;
-		    dl_dci->res_alloc = 0;
-		    dl_dci->has_vrb_format = 1;
-		    dl_dci->vrb_format =
-			PROTOCOL__FLEX_VRB_FORMAT__FLVRBF_LOCALIZED;
-		    dl_dci->has_format = 1;
-		    dl_dci->format = PROTOCOL__FLEX_DCI_FORMAT__FLDCIF_1;
-		    dl_dci->has_rb_bitmap = 1;
-		    dl_dci->rb_bitmap =
-			allocate_prbs_sub(nb_rb, rballoc_sub);
-		    dl_dci->has_rb_shift = 1;
-		    dl_dci->rb_shift = 0;
-		    dl_dci->n_ndi = 1;
-		    dl_dci->ndi =
-			(uint32_t *) malloc(sizeof(uint32_t) *
-					    dl_dci->n_ndi);
-		    dl_dci->ndi[0] = ndi;
-		    dl_dci->n_rv = 1;
-		    dl_dci->rv =
-			(uint32_t *) malloc(sizeof(uint32_t) *
-					    dl_dci->n_rv);
-		    dl_dci->rv[0] = round & 3;
-		    dl_dci->has_tpc = 1;
-		    dl_dci->tpc = tpc;
-		    dl_dci->n_mcs = 1;
-		    dl_dci->mcs =
-			(uint32_t *) malloc(sizeof(uint32_t) *
-					    dl_dci->n_mcs);
-		    dl_dci->mcs[0] = mcs;
-		    dl_dci->n_tbs_size = 1;
-		    dl_dci->tbs_size =
-			(uint32_t *) malloc(sizeof(uint32_t) *
-					    dl_dci->n_tbs_size);
-		    dl_dci->tbs_size[0] = dci_tbs;
-		    if (flexran_get_duplex_mode(mod_id, CC_id) ==
-			PROTOCOL__FLEX_DUPLEX_MODE__FLDM_TDD) {
-			dl_dci->has_dai = 1;
-			dl_dci->dai =
-			    (UE_list->UE_template[CC_id][UE_id].DAI -
-			     1) & 3;
-		    }
-		    break;
-		case 3:
-		    dl_dci->has_res_alloc = 1;
-		    dl_dci->res_alloc = 0;
-		    dl_dci->has_vrb_format = 1;
-		    dl_dci->vrb_format =
-			PROTOCOL__FLEX_VRB_FORMAT__FLVRBF_LOCALIZED;
-		    dl_dci->has_format = 1;
-		    dl_dci->format = PROTOCOL__FLEX_DCI_FORMAT__FLDCIF_2A;
-		    dl_dci->has_rb_bitmap = 1;
-		    dl_dci->rb_bitmap =
-			allocate_prbs_sub(nb_rb, rballoc_sub);
-		    dl_dci->has_rb_shift = 1;
-		    dl_dci->rb_shift = 0;
-		    dl_dci->n_ndi = 2;
-		    dl_dci->ndi =
-			(uint32_t *) malloc(sizeof(uint32_t) *
-					    dl_dci->n_ndi);
-		    dl_dci->ndi[0] = ndi;
-		    dl_dci->ndi[1] = ndi;
-		    dl_dci->n_rv = 2;
-		    dl_dci->rv =
-			(uint32_t *) malloc(sizeof(uint32_t) *
-					    dl_dci->n_rv);
-		    dl_dci->rv[0] = round & 3;
-		    dl_dci->rv[1] = round & 3;
-		    dl_dci->has_tpc = 1;
-		    dl_dci->tpc = tpc;
-		    dl_dci->n_mcs = 2;
-		    dl_dci->mcs =
-			(uint32_t *) malloc(sizeof(uint32_t) *
-					    dl_dci->n_mcs);
-		    dl_dci->mcs[0] = mcs;
-		    dl_dci->mcs[1] = mcs;
-		    dl_dci->n_tbs_size = 2;
-		    dl_dci->tbs_size =
-			(uint32_t *) malloc(sizeof(uint32_t) *
-					    dl_dci->n_tbs_size);
-		    dl_dci->tbs_size[0] = dci_tbs;
-		    dl_dci->tbs_size[1] = dci_tbs;
-		    if (flexran_get_duplex_mode(mod_id, CC_id) ==
-			PROTOCOL__FLEX_DUPLEX_MODE__FLDM_TDD) {
-			dl_dci->has_dai = 1;
-			dl_dci->dai =
-			    (UE_list->UE_template[CC_id][UE_id].DAI -
-			     1) & 3;
-		    }
-		    break;
-		case 4:
-		    dl_dci->has_res_alloc = 1;
-		    dl_dci->res_alloc = 0;
-		    dl_dci->has_vrb_format = 1;
-		    dl_dci->vrb_format =
-			PROTOCOL__FLEX_VRB_FORMAT__FLVRBF_LOCALIZED;
-		    dl_dci->has_format = 1;
-		    dl_dci->format = PROTOCOL__FLEX_DCI_FORMAT__FLDCIF_2A;
-		    dl_dci->has_rb_bitmap = 1;
-		    dl_dci->rb_bitmap =
-			allocate_prbs_sub(nb_rb, rballoc_sub);
-		    dl_dci->has_rb_shift = 1;
-		    dl_dci->rb_shift = 0;
-		    dl_dci->n_ndi = 2;
-		    dl_dci->ndi =
-			(uint32_t *) malloc(sizeof(uint32_t) *
-					    dl_dci->n_ndi);
-		    dl_dci->ndi[0] = ndi;
-		    dl_dci->ndi[1] = ndi;
-		    dl_dci->n_rv = 2;
-		    dl_dci->rv =
-			(uint32_t *) malloc(sizeof(uint32_t) *
-					    dl_dci->n_rv);
-		    dl_dci->rv[0] = round & 3;
-		    dl_dci->rv[1] = round & 3;
-		    dl_dci->has_tpc = 1;
-		    dl_dci->tpc = tpc;
-		    dl_dci->n_mcs = 2;
-		    dl_dci->mcs =
-			(uint32_t *) malloc(sizeof(uint32_t) *
-					    dl_dci->n_mcs);
-		    dl_dci->mcs[0] = mcs;
-		    dl_dci->mcs[1] = mcs;
-		    dl_dci->n_tbs_size = 2;
-		    dl_dci->tbs_size =
-			(uint32_t *) malloc(sizeof(uint32_t) *
-					    dl_dci->n_tbs_size);
-		    dl_dci->tbs_size[0] = dci_tbs;
-		    dl_dci->tbs_size[1] = dci_tbs;
-		    if (flexran_get_duplex_mode(mod_id, CC_id) ==
-			PROTOCOL__FLEX_DUPLEX_MODE__FLDM_TDD) {
-			dl_dci->has_dai = 1;
-			dl_dci->dai =
-			    (UE_list->UE_template[CC_id][UE_id].DAI -
-			     1) & 3;
-		    }
-		    break;
-		case 5:
-		    dl_dci->has_res_alloc = 1;
-		    dl_dci->res_alloc = 0;
-		    dl_dci->has_vrb_format = 1;
-		    dl_dci->vrb_format =
-			PROTOCOL__FLEX_VRB_FORMAT__FLVRBF_LOCALIZED;
-		    dl_dci->has_format = 1;
-		    dl_dci->format = PROTOCOL__FLEX_DCI_FORMAT__FLDCIF_1D;
-		    dl_dci->has_rb_bitmap = 1;
-		    dl_dci->rb_bitmap =
-			allocate_prbs_sub(nb_rb, rballoc_sub);
-		    dl_dci->has_rb_shift = 1;
-		    dl_dci->rb_shift = 0;
-		    dl_dci->n_ndi = 1;
-		    dl_dci->ndi[0] = ndi;
-		    dl_dci->n_rv = 1;
-		    dl_dci->rv =
-			(uint32_t *) malloc(sizeof(uint32_t) *
-					    dl_dci->n_rv);
-		    dl_dci->rv[0] = round & 3;
-		    dl_dci->has_tpc = 1;
-		    dl_dci->tpc = tpc;
-		    dl_dci->n_mcs = 1;
-		    dl_dci->mcs =
-			(uint32_t *) malloc(sizeof(uint32_t) *
-					    dl_dci->n_mcs);
-		    dl_dci->mcs[0] = mcs;
-		    dl_dci->n_tbs_size = 1;
-		    dl_dci->tbs_size =
-			(uint32_t *) malloc(sizeof(uint32_t) *
-					    dl_dci->n_tbs_size);
-		    dl_dci->tbs_size[0] = dci_tbs;
-		    if (flexran_get_duplex_mode(mod_id, CC_id) ==
-			PROTOCOL__FLEX_DUPLEX_MODE__FLDM_TDD) {
-			dl_dci->has_dai = 1;
-			dl_dci->dai =
-			    (UE_list->UE_template[CC_id][UE_id].DAI -
-			     1) & 3;
-		    }
-
-		    if (ue_sched_ctl->dl_pow_off[CC_id] == 2) {
-			ue_sched_ctl->dl_pow_off[CC_id] = 1;
-		    }
-
-		    dl_dci->has_dl_power_offset = 1;
-		    dl_dci->dl_power_offset =
-			ue_sched_ctl->dl_pow_off[CC_id];
-		    dl_dci->has_precoding_info = 1;
-		    dl_dci->precoding_info = 5;	// Is this right??
-
-		    break;
-		case 6:
-		    dl_dci->has_res_alloc = 1;
-		    dl_dci->res_alloc = 0;
-		    dl_dci->has_vrb_format = 1;
-		    dl_dci->vrb_format =
-			PROTOCOL__FLEX_VRB_FORMAT__FLVRBF_LOCALIZED;
-		    dl_dci->has_format = 1;
-		    dl_dci->format = PROTOCOL__FLEX_DCI_FORMAT__FLDCIF_1D;
-		    dl_dci->has_rb_bitmap = 1;
-		    dl_dci->rb_bitmap =
-			allocate_prbs_sub(nb_rb, rballoc_sub);
-		    dl_dci->has_rb_shift = 1;
-		    dl_dci->rb_shift = 0;
-		    dl_dci->n_ndi = 1;
-		    dl_dci->ndi =
-			(uint32_t *) malloc(sizeof(uint32_t) *
-					    dl_dci->n_ndi);
-		    dl_dci->ndi[0] = ndi;
-		    dl_dci->n_rv = 1;
-		    dl_dci->rv =
-			(uint32_t *) malloc(sizeof(uint32_t) *
-					    dl_dci->n_rv);
-		    dl_dci->rv[0] = round & 3;
-		    dl_dci->has_tpc = 1;
-		    dl_dci->tpc = tpc;
-		    dl_dci->n_mcs = 1;
-		    dl_dci->mcs =
-			(uint32_t *) malloc(sizeof(uint32_t) *
-					    dl_dci->n_mcs);
-		    dl_dci->mcs[0] = mcs;
-		    if (flexran_get_duplex_mode(mod_id, CC_id) ==
-			PROTOCOL__FLEX_DUPLEX_MODE__FLDM_TDD) {
-			dl_dci->has_dai = 1;
-			dl_dci->dai =
-			    (UE_list->UE_template[CC_id][UE_id].DAI -
-			     1) & 3;
-		    }
-
-		    dl_dci->has_dl_power_offset = 1;
-		    dl_dci->dl_power_offset =
-			ue_sched_ctl->dl_pow_off[CC_id];
-		    dl_dci->has_precoding_info = 1;
-		    dl_dci->precoding_info = 5;	// Is this right??
-		    break;
-		}
-	    }
-
-	    if (flexran_get_duplex_mode(mod_id, CC_id) ==
-		PROTOCOL__FLEX_DUPLEX_MODE__FLDM_TDD) {
+  start_meas(&eNB->schedule_dlsch);
+  VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_SCHEDULE_DLSCH,VCD_FUNCTION_IN);
+
+  //weight = get_ue_weight(module_idP,UE_id);
+  aggregation = 1; // set to the maximum aggregation level
+
+  for (CC_id=0; CC_id<MAX_NUM_CCs; CC_id++) {
+    min_rb_unit[CC_id] = get_min_rb_unit(mod_id, CC_id);
+    // get number of PRBs less those used by common channels
+    total_nb_available_rb[CC_id] = flexran_get_N_RB_DL(mod_id, CC_id);
+    for (i=0;i < flexran_get_N_RB_DL(mod_id, CC_id); i++)
+      if (eNB->common_channels[CC_id].vrb_map[i] != 0)
+	total_nb_available_rb[CC_id]--;
+    
+    N_RBG[CC_id] = flexran_get_N_RBG(mod_id, CC_id);
+
+    // store the global enb stats:
+    eNB->eNB_stats[CC_id].num_dlactive_UEs =  UE_list->num_UEs;
+    eNB->eNB_stats[CC_id].available_prbs =  total_nb_available_rb[CC_id];
+    eNB->eNB_stats[CC_id].total_available_prbs +=  total_nb_available_rb[CC_id];
+    eNB->eNB_stats[CC_id].dlsch_bytes_tx=0;
+    eNB->eNB_stats[CC_id].dlsch_pdus_tx=0;
+  }
+
+   VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_DLSCH_PREPROCESSOR,VCD_FUNCTION_IN);
+
+   start_meas(&eNB->schedule_dlsch_preprocessor);
+   _dlsch_scheduler_pre_processor(mod_id,
+				  slice_id,
+				  frame,
+				  subframe,
+				  N_RBG,
+				  mbsfn_flag);
+   stop_meas(&eNB->schedule_dlsch_preprocessor);
+   VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_DLSCH_PREPROCESSOR,VCD_FUNCTION_OUT);
+
+   for (CC_id=0; CC_id<MAX_NUM_CCs; CC_id++) {
+    LOG_D(MAC, "doing schedule_ue_spec for CC_id %d\n",CC_id);
+
+    if (mbsfn_flag[CC_id]>0)
+      continue;
+    
+    for (UE_id=UE_list->head; UE_id>=0; UE_id=UE_list->next[UE_id]) {
+  
+      rnti = flexran_get_ue_crnti(mod_id, UE_id);
+      eNB_UE_stats = mac_xface->get_eNB_UE_stats(mod_id,CC_id,rnti);
+      ue_sched_ctl = &UE_list->UE_sched_ctrl[UE_id];
+      
+      if (eNB_UE_stats==NULL) {
+
+        	LOG_D(MAC,"[eNB] Cannot find eNB_UE_stats\n");
+                //  mac_xface->macphy_exit("[MAC][eNB] Cannot find eNB_UE_stats\n");
+        	continue;
+      }
+      
+      if (flexran_slice_member(UE_id, slice_id) == 0)
+      	continue;
+      
+      if (rnti==NOT_A_RNTI) {
+        LOG_D(MAC,"Cannot find rnti for UE_id %d (num_UEs %d)\n", UE_id,UE_list->num_UEs);
+        // mac_xface->macphy_exit("Cannot find rnti for UE_id");
+        continue;
+      }
+
+      switch(mac_xface->get_transmission_mode(mod_id,CC_id,rnti)){
+      case 1:
+      case 2:
+      case 7:
+        	aggregation = get_aggregation(get_bw_index(mod_id,CC_id), 
+				      eNB_UE_stats->DL_cqi[0],
+				      format1);
+      	break;
+      case 3:
+        	aggregation = get_aggregation(get_bw_index(mod_id,CC_id), 
+				      eNB_UE_stats->DL_cqi[0],
+				      format2A);
+      	break;
+      default:
+        	LOG_W(MAC,"Unsupported transmission mode %d\n", mac_xface->get_transmission_mode(mod_id,CC_id,rnti));
+        	aggregation = 2;
+      }
+     
+      if ((ue_sched_ctl->pre_nb_available_rbs[CC_id] == 0) ||  // no RBs allocated 
+	  CCE_allocation_infeasible(mod_id, CC_id, 0, subframe, aggregation, rnti)) {
+
+            LOG_D(MAC,"[eNB %d] Frame %d : no RB allocated for UE %d on CC_id %d: continue \n",
+                  mod_id, frame, UE_id, CC_id);
+            //if(mac_xface->get_transmission_mode(module_idP,rnti)==5)
+            continue; //to next user (there might be rbs availiable for other UEs in TM5
+            // else
+            //  break;
+      }
+
+      if (flexran_get_duplex_mode(mod_id, CC_id) == PROTOCOL__FLEX_DUPLEX_MODE__FLDM_TDD)  {
+        set_ue_dai (subframe,
+                    flexran_get_subframe_assignment(mod_id, CC_id),
+                    UE_id,
+                    CC_id,
+                    UE_list);
+        //TODO: update UL DAI after DLSCH scheduling
+        //set_ul_DAI(mod_id, UE_id, CC_id, frame, subframe,frame_parms);
+      }
+
+      channels_added = 0;
+
+      // After this point all the UEs will be scheduled
+      dl_data[num_ues_added] = (Protocol__FlexDlData *) malloc(sizeof(Protocol__FlexDlData));
+      protocol__flex_dl_data__init(dl_data[num_ues_added]);
+      dl_data[num_ues_added]->has_rnti = 1;
+      dl_data[num_ues_added]->rnti = rnti;
+      dl_data[num_ues_added]->n_rlc_pdu = 0;
+      dl_data[num_ues_added]->has_serv_cell_index = 1;
+      dl_data[num_ues_added]->serv_cell_index = CC_id;
+            
+      flexran_get_harq(mod_id, CC_id, UE_id, frame, subframe, &harq_pid, &round, openair_harq_DL);
+      sdu_length_total=0;
+      mcs = cqi_to_mcs[flexran_get_ue_wcqi(mod_id, UE_id)];
+      //      LOG_I(FLEXRAN_AGENT, "The MCS is %d\n", mcs);
+      mcs = cmin(mcs,flexran_slice_maxmcs(slice_id));
+// #ifdef EXMIMO
+
+//        if (mac_xface->get_transmission_mode(mod_id, CC_id, rnti) == 5) {
+// 	  mcs = cqi_to_mcs[flexran_get_ue_wcqi(mod_id, UE_id)];
+// 	  mcs =  cmin(mcs,16);
+//        }
+
+// #endif
+
+      /*Get pre available resource blocks based on buffers*/ 
+      nb_available_rb = ue_sched_ctl->pre_nb_available_rbs[CC_id];
+      // initializing the rb allocation indicator for each UE
+       for(j = 0; j < flexran_get_N_RBG(mod_id, CC_id); j++) {
+
+          UE_list->UE_template[CC_id][UE_id].rballoc_subband[harq_pid][j] = 0;
+        	rballoc_sub[j] = 0;
+      }
+
+      /* LOG_D(MAC,"[eNB %d] Frame %d: Scheduling UE %d on CC_id %d (rnti %x, harq_pid %d, round %d, rb %d, cqi %d, mcs %d, rrc %d)\n", */
+      /*       mod_id, frame, UE_id, CC_id, rnti, harq_pid, round, nb_available_rb, */
+      /*       eNB_UE_stats->DL_cqi[0], mcs, */
+      /*       UE_list->eNB_UE_stats[CC_id][UE_id].rrc_status); */
+
+      dl_dci = (Protocol__FlexDlDci*) malloc(sizeof(Protocol__FlexDlDci));
+      protocol__flex_dl_dci__init(dl_dci);
+      dl_data[num_ues_added]->dl_dci = dl_dci;
+
+      
+      dl_dci->has_rnti = 1;
+      dl_dci->rnti = rnti;
+      dl_dci->has_harq_process = 1;
+      dl_dci->harq_process = harq_pid;
+      
+      /* process retransmission  */
+      if (round > 0) {
+
+      	LOG_D(FLEXRAN_AGENT, "There was a retransmission just now and the round was %d\n", round);
+
+      	if (flexran_get_duplex_mode(mod_id, CC_id) == PROTOCOL__FLEX_DUPLEX_MODE__FLDM_TDD) {
+      	  UE_list->UE_template[CC_id][UE_id].DAI++;
+      	  update_ul_dci(mod_id, CC_id, rnti, UE_list->UE_template[CC_id][UE_id].DAI);
+      	  LOG_D(MAC,"DAI update: CC_id %d subframeP %d: UE %d, DAI %d\n",
+      		CC_id, subframe,UE_id,UE_list->UE_template[CC_id][UE_id].DAI);
+      	}
+
+      	mcs = UE_list->UE_template[CC_id][UE_id].mcs[harq_pid];
+
+      	  // get freq_allocation
+      	nb_rb = UE_list->UE_template[CC_id][UE_id].nb_rb[harq_pid];
+      	  
+      	/*TODO: Must add this to FlexRAN agent API */
+      	dci_tbs = mac_xface->get_TBS_DL(mcs, nb_rb);
+
+      	if (nb_rb <= nb_available_rb) {
+      	  
+      	  if(nb_rb == ue_sched_ctl->pre_nb_available_rbs[CC_id]) {
+      	    for(j = 0; j < flexran_get_N_RBG(mod_id, CC_id); j++) { // for indicating the rballoc for each sub-band
+      	      UE_list->UE_template[CC_id][UE_id].rballoc_subband[harq_pid][j] = ue_sched_ctl->rballoc_sub_UE[CC_id][j];
+                  }
+      	  } else {
+      	    nb_rb_temp = nb_rb;
+      	    j = 0;
+
+      	    while((nb_rb_temp > 0) && (j < flexran_get_N_RBG(mod_id, CC_id))) {
+      	      if(ue_sched_ctl->rballoc_sub_UE[CC_id][j] == 1) {
+      		UE_list->UE_template[CC_id][UE_id].rballoc_subband[harq_pid][j] = ue_sched_ctl->rballoc_sub_UE[CC_id][j];
+      		
+      		if((j == flexran_get_N_RBG(mod_id, CC_id) - 1) &&
+      		   ((flexran_get_N_RB_DL(mod_id, CC_id) == 25)||
+      		    (flexran_get_N_RB_DL(mod_id, CC_id) == 50))) {
+      		  nb_rb_temp = nb_rb_temp - min_rb_unit[CC_id]+1;
+      		} else {
+      		  nb_rb_temp = nb_rb_temp - min_rb_unit[CC_id];
+      		}
+      	      }
+      	      j = j + 1;
+      	    }
+      	  }
+
+      	  nb_available_rb -= nb_rb;
+      	  PHY_vars_eNB_g[mod_id][CC_id]->mu_mimo_mode[UE_id].pre_nb_available_rbs = nb_rb;
+      	  PHY_vars_eNB_g[mod_id][CC_id]->mu_mimo_mode[UE_id].dl_pow_off = ue_sched_ctl->dl_pow_off[CC_id];
+      	  
+      	  for(j=0; j < flexran_get_N_RBG(mod_id, CC_id); j++) {
+      	    PHY_vars_eNB_g[mod_id][CC_id]->mu_mimo_mode[UE_id].rballoc_sub[j] = UE_list->UE_template[CC_id][UE_id].rballoc_subband[harq_pid][j];
+      	    rballoc_sub[j] = UE_list->UE_template[CC_id][UE_id].rballoc_subband[harq_pid][j];
+      	  }
+
+      	  // Keep the old NDI, do not toggle
+      	  ndi = UE_list->UE_template[CC_id][UE_id].oldNDI[harq_pid];
+      	  tpc = UE_list->UE_template[CC_id][UE_id].oldTPC[harq_pid];
+      	  UE_list->UE_template[CC_id][UE_id].mcs[harq_pid] = mcs;
+
+      	  ue_has_transmission = 1;
+      	  num_ues_added++;
+      	} else {
+      	  LOG_D(MAC,"[eNB %d] Frame %d CC_id %d : don't schedule UE %d, its retransmission takes more resources than we have\n",
+                      mod_id, frame, CC_id, UE_id);
+      	  ue_has_transmission = 0;
+      	}
+      	//End of retransmission
+      }
+
+       else { /* This is a potentially new SDU opportunity */
+	rlc_status.bytes_in_buffer = 0;
+        // Now check RLC information to compute number of required RBs
+        // get maximum TBS size for RLC request
+        //TBS = mac_xface->get_TBS(eNB_UE_stats->DL_cqi[0]<<1,nb_available_rb);
+        TBS = mac_xface->get_TBS_DL(mcs, nb_available_rb);
+	dci_tbs = TBS;
+	LOG_D(FLEXRAN_AGENT, "TBS is %d\n", TBS);
+	
+        // check first for RLC data on DCCH
+        // add the length for  all the control elements (timing adv, drx, etc) : header + payload
+
+	ta_len = (ue_sched_ctl->ta_update != 0) ? 2 : 0;
+	
+	dl_data[num_ues_added]->n_ce_bitmap = 2;
+	dl_data[num_ues_added]->ce_bitmap = (uint32_t *) calloc(2, sizeof(uint32_t));
+
+	if (ta_len > 0) {
+	  ce_flags |= PROTOCOL__FLEX_CE_TYPE__FLPCET_TA;
+	}
 
-		/* TODO */
-		//set_ul_DAI(mod_id, UE_id, CC_id, frame, subframe, frame_parms);
-	    }
-	}			// UE_id loop
-    }				// CC_id loop
-
-    // Add all the dl_data elements to the flexran message
-    int offset = (*dl_info)->dl_mac_config_msg->n_dl_ue_data;
-    (*dl_info)->dl_mac_config_msg->n_dl_ue_data += num_ues_added;
-    if (num_ues_added > 0) {
-	(*dl_info)->dl_mac_config_msg->dl_ue_data =
-	    (Protocol__FlexDlData **)
-	    realloc((*dl_info)->dl_mac_config_msg->dl_ue_data,
-		    sizeof(Protocol__FlexDlData *) *
-		    ((*dl_info)->dl_mac_config_msg->n_dl_ue_data));
-	if ((*dl_info)->dl_mac_config_msg->dl_ue_data == NULL) {
-	    LOG_E(MAC, "Request for memory reallocation failed\n");
-	    return;
+	/*TODO: Add other flags if DRX and other CE are required*/
+	
+	// Add the control element flags to the flexran message
+	dl_data[num_ues_added]->ce_bitmap[0] = ce_flags;
+	dl_data[num_ues_added]->ce_bitmap[1] = ce_flags;
+
+	// TODO : Need to prioritize DRBs
+	// Loop through the UE logical channels (DCCH, DCCH1, DTCH for now)
+	header_len = 0;
+	header_len_last = 0;
+	sdu_length_total = 0;
+	for (j = 1; j < NB_RB_MAX; j++) {
+	  header_len += 3;
+	  // Need to see if we have space for data from this channel
+	  if (dci_tbs - ta_len - header_len - sdu_length_total > 0) {
+	     LOG_D(MAC, "[TEST]Requested %d bytes from RLC buffer on channel %d during first call\n", dci_tbs-ta_len-header_len, j);
+	     //If we have space, we need to see how much data we can request at most (if any available)
+	     rlc_status = mac_rlc_status_ind(mod_id,
+					     rnti,
+					     mod_id,
+					     frame,
+						 subframe,
+					     ENB_FLAG_YES,
+					     MBMS_FLAG_NO,
+					     j,
+					     (dci_tbs - ta_len - header_len - sdu_length_total)); // transport block set size
+
+	     //If data are available in channel j
+	     if (rlc_status.bytes_in_buffer > 0) {
+	       LOG_D(MAC, "[TEST]Have %d bytes in DCCH buffer during first call\n", rlc_status.bytes_in_buffer);
+	       //Fill in as much as possible
+	       data_to_request = cmin(dci_tbs - ta_len - header_len - sdu_length_total, rlc_status.bytes_in_buffer);
+	       LOG_D(FLEXRAN_AGENT, "Will request %d bytes from channel %d\n", data_to_request, j);
+
+	       if (data_to_request < 128) { //The header will be one byte less
+        		 header_len--;
+        		 header_len_last = 2;
+	       }
+          else {
+
+        		 header_len_last = 3;
+	       }
+	       /* if (j == 1 || j == 2) {
+		  data_to_request+=0; 
+		  } */
+	       LOG_D(MAC, "[TEST]Will request %d from channel %d\n", data_to_request, j);
+	       rlc_pdus[channels_added] = (Protocol__FlexRlcPdu *) malloc(sizeof(Protocol__FlexRlcPdu));
+	       protocol__flex_rlc_pdu__init(rlc_pdus[channels_added]);
+	       rlc_pdus[channels_added]->n_rlc_pdu_tb = 2;
+	       rlc_pdus[channels_added]->rlc_pdu_tb = (Protocol__FlexRlcPduTb **) malloc(sizeof(Protocol__FlexRlcPduTb *) * 2);
+	       rlc_pdus[channels_added]->rlc_pdu_tb[0] = (Protocol__FlexRlcPduTb *) malloc(sizeof(Protocol__FlexRlcPduTb));
+	       protocol__flex_rlc_pdu_tb__init(rlc_pdus[channels_added]->rlc_pdu_tb[0]);
+	       rlc_pdus[channels_added]->rlc_pdu_tb[0]->has_logical_channel_id = 1;
+	       rlc_pdus[channels_added]->rlc_pdu_tb[0]->logical_channel_id = j;
+	       rlc_pdus[channels_added]->rlc_pdu_tb[0]->has_size = 1;
+	       rlc_pdus[channels_added]->rlc_pdu_tb[0]->size = data_to_request;
+	       rlc_pdus[channels_added]->rlc_pdu_tb[1] = (Protocol__FlexRlcPduTb *) malloc(sizeof(Protocol__FlexRlcPduTb));
+	       protocol__flex_rlc_pdu_tb__init(rlc_pdus[channels_added]->rlc_pdu_tb[1]);
+	       rlc_pdus[channels_added]->rlc_pdu_tb[1]->has_logical_channel_id = 1;
+	       rlc_pdus[channels_added]->rlc_pdu_tb[1]->logical_channel_id = j;
+	       rlc_pdus[channels_added]->rlc_pdu_tb[1]->has_size = 1;
+	       rlc_pdus[channels_added]->rlc_pdu_tb[1]->size = data_to_request;
+	       dl_data[num_ues_added]->n_rlc_pdu++;
+	       channels_added++;
+	       //Set this to the max value that we might request
+	       sdu_length_total += data_to_request;
+	     } else {
+	       //Take back the assumption of a header for this channel
+	       header_len -= 3;
+	     } //End rlc_status.bytes_in_buffer <= 0
+	  } //end of if dci_tbs - ta_len - header_len > 0
+	} // End of iterating the logical channels
+	
+	// Add rlc_pdus to the dl_data message
+	dl_data[num_ues_added]->rlc_pdu = (Protocol__FlexRlcPdu **) malloc(sizeof(Protocol__FlexRlcPdu *) *
+									  dl_data[num_ues_added]->n_rlc_pdu);
+	for (i = 0; i < dl_data[num_ues_added]->n_rlc_pdu; i++) {
+	  dl_data[num_ues_added]->rlc_pdu[i] = rlc_pdus[i];
 	}
-	for (i = 0; i < num_ues_added; i++) {
-	    (*dl_info)->dl_mac_config_msg->dl_ue_data[offset + i] =
-		dl_data[i];
+	
+	if (header_len == 0) {
+	  LOG_D(FLEXRAN_AGENT, "Header was empty\n");
+	  header_len_last = 0;
+	} 
+	
+	// there is a payload
+        if ((dl_data[num_ues_added]->n_rlc_pdu > 0)) {
+	  // Now compute number of required RBs for total sdu length
+          // Assume RAH format 2
+          // adjust  header lengths
+	  LOG_D(FLEXRAN_AGENT, "We have %d bytes to transfer\n", sdu_length_total);
+	  if (header_len != 0) {
+	    LOG_D(FLEXRAN_AGENT, "Header length was %d ", header_len);
+	    header_len_last--;
+	    header_len -= header_len_last;
+	    LOG_D(FLEXRAN_AGENT, "so we resized it to %d\n", header_len);
+	  }
+	  
+	  /* if (header_len == 2 || header_len == 3) { //Only one SDU, remove length field */
+	  /*   header_len = 1; */
+	  /* } else { //Remove length field from the last SDU */
+	  /*   header_len--; */
+	  /* } */
+
+	  mcs_tmp = mcs;
+	  if (mcs_tmp == 0) {
+            nb_rb = 4;  // don't let the TBS get too small
+          } else {
+            nb_rb=min_rb_unit[CC_id];
+          }
+
+	  LOG_D(MAC,"[TEST]The initial number of resource blocks was %d\n", nb_rb);
+	  LOG_D(MAC,"[TEST] The initial mcs was %d\n", mcs_tmp);
+
+	  TBS = mac_xface->get_TBS_DL(mcs_tmp, nb_rb);
+	  LOG_D(MAC,"[TEST]The TBS during rate matching was %d\n", TBS);
+
+	  while (TBS < (sdu_length_total + header_len + ta_len))  {
+            nb_rb += min_rb_unit[CC_id];  //
+	    LOG_D(MAC, "[TEST]Had to increase the number of RBs\n");
+            if (nb_rb > nb_available_rb) { // if we've gone beyond the maximum number of RBs
+              // (can happen if N_RB_DL is odd)
+              TBS = mac_xface->get_TBS_DL(mcs_tmp, nb_available_rb);
+              nb_rb = nb_available_rb;
+              break;
+            }
+
+            TBS = mac_xface->get_TBS_DL(mcs_tmp, nb_rb);
+          }
+
+	  if(nb_rb == ue_sched_ctl->pre_nb_available_rbs[CC_id]) {
+	    LOG_D(MAC, "[TEST]We had the exact number of rbs. Time to fill the rballoc subband\n");
+            for(j = 0; j < flexran_get_N_RBG(mod_id, CC_id); j++) { // for indicating the rballoc for each sub-band
+              UE_list->UE_template[CC_id][UE_id].rballoc_subband[harq_pid][j] = ue_sched_ctl->rballoc_sub_UE[CC_id][j];
+            }
+          }
+           else {
+	    nb_rb_temp = nb_rb;
+            j = 0;
+	    LOG_D(MAC, "[TEST]Will only partially fill the bitmap\n");
+	    while((nb_rb_temp > 0) && (j < flexran_get_N_RBG(mod_id, CC_id))) {
+              if(ue_sched_ctl->rballoc_sub_UE[CC_id][j] == 1) {
+                UE_list->UE_template[CC_id][UE_id].rballoc_subband[harq_pid][j] = ue_sched_ctl->rballoc_sub_UE[CC_id][j];
+                if ((j == flexran_get_N_RBG(mod_id, CC_id) - 1) &&
+                    ((flexran_get_N_RB_DL(mod_id, CC_id) == 25)||
+                     (flexran_get_N_RB_DL(mod_id, CC_id) == 50))) {
+                  nb_rb_temp = nb_rb_temp - min_rb_unit[CC_id] + 1;
+                } else {
+                  nb_rb_temp = nb_rb_temp - min_rb_unit[CC_id];
+                }
+              }
+              j = j+1;
+            }
+	  }
+	  
+	  PHY_vars_eNB_g[mod_id][CC_id]->mu_mimo_mode[UE_id].pre_nb_available_rbs = nb_rb;
+          PHY_vars_eNB_g[mod_id][CC_id]->mu_mimo_mode[UE_id].dl_pow_off = ue_sched_ctl->dl_pow_off[CC_id];
+
+	  for(j = 0; j < flexran_get_N_RBG(mod_id, CC_id); j++) {
+            PHY_vars_eNB_g[mod_id][CC_id]->mu_mimo_mode[UE_id].rballoc_sub[j] = UE_list->UE_template[CC_id][UE_id].rballoc_subband[harq_pid][j];
+          }
+
+	  // decrease mcs until TBS falls below required length
+          while ((TBS > (sdu_length_total + header_len + ta_len)) && (mcs_tmp > 0)) {
+            mcs_tmp--;
+            TBS = mac_xface->get_TBS_DL(mcs_tmp, nb_rb);
+          }
+
+	  // if we have decreased too much or we don't have enough RBs, increase MCS
+          while ((TBS < (sdu_length_total + header_len + ta_len)) &&
+		 ((( ue_sched_ctl->dl_pow_off[CC_id] > 0) && (mcs_tmp < 28))											     || ( (ue_sched_ctl->dl_pow_off[CC_id]==0) && (mcs_tmp <= 15)))) {
+            mcs_tmp++;
+            TBS = mac_xface->get_TBS_DL(mcs_tmp, nb_rb);
+          }
+
+	  dci_tbs = TBS;
+	  mcs = mcs_tmp;
+	  LOG_D(FLEXRAN_AGENT, "Final mcs was %d\n", mcs); 
+	  
+	  dl_dci->has_aggr_level = 1;
+	  dl_dci->aggr_level = aggregation;
+	  
+          UE_list->UE_template[CC_id][UE_id].nb_rb[harq_pid] = nb_rb;
+
+	  // if (flexran_get_duplex_mode(mod_id, CC_id) == PROTOCOL__FLEX_DUPLEX_MODE__FLDM_TDD) {
+   //          UE_list->UE_template[CC_id][UE_id].DAI++;
+   //          //  printf("DAI update: subframeP %d: UE %d, DAI %d\n",subframeP,UE_id,UE_list->UE_template[CC_id][UE_id].DAI);
+	    //#warning only for 5MHz channel
+          //   update_ul_dci(mod_id, CC_id, rnti, UE_list->UE_template[CC_id][UE_id].DAI);
+          // }
+
+	  // do PUCCH power control
+          // this is the normalized RX power
+	  normalized_rx_power = flexran_get_p0_pucch_dbm(mod_id,UE_id, CC_id); //eNB_UE_stats->Po_PUCCH_dBm; 
+	  target_rx_power = flexran_get_p0_nominal_pucch(mod_id, CC_id) + 20; //mac_xface->get_target_pucch_rx_power(mod_id, CC_id) + 20;
+	  // this assumes accumulated tpc
+	  // make sure that we are only sending a tpc update once a frame, otherwise the control loop will freak out
+	  int32_t framex10psubframe = UE_list->UE_template[CC_id][UE_id].pucch_tpc_tx_frame*10+UE_list->UE_template[CC_id][UE_id].pucch_tpc_tx_subframe;
+
+	  if (((framex10psubframe+10)<=(frame*10+subframe)) || //normal case
+	      ((framex10psubframe>(frame*10+subframe)) && (((10240-framex10psubframe+frame*10+subframe)>=10)))) //frame wrap-around
+	    if (flexran_get_p0_pucch_status(mod_id, UE_id, CC_id) == 1) {
+  	      flexran_update_p0_pucch(mod_id, UE_id, CC_id);
+
+	      UE_list->UE_template[CC_id][UE_id].pucch_tpc_tx_frame = frame;
+	      UE_list->UE_template[CC_id][UE_id].pucch_tpc_tx_subframe = subframe;
+	      if (normalized_rx_power>(target_rx_power+1)) {
+		tpc = 0; //-1
+		tpc_accumulated--;
+	      } else if (normalized_rx_power<(target_rx_power-1)) {
+		tpc = 2; //+1
+		tpc_accumulated++;
+	      } else {
+		tpc = 1; //0
+	      }
+	      LOG_D(MAC,"[eNB %d] DLSCH scheduler: frame %d, subframe %d, harq_pid %d, tpc %d, accumulated %d, normalized/target rx power %d/%d\n",
+		    mod_id, frame, subframe, harq_pid, tpc,
+		    tpc_accumulated, normalized_rx_power, target_rx_power);
+	    } // Po_PUCCH has been updated 
+	    else {
+	      tpc = 1; //0
+	    } // time to do TPC update 
+	  else {
+	    tpc = 1; //0
+	  }
+
+	  for(i=0; i<PHY_vars_eNB_g[mod_id][CC_id]->frame_parms.N_RBG; i++) {
+	    rballoc_sub[i] = UE_list->UE_template[CC_id][UE_id].rballoc_subband[harq_pid][i];
+          }	
+
+	   // Toggle NDI
+          LOG_D(MAC,"CC_id %d Frame %d, subframeP %d: Toggling Format1 NDI for UE %d (rnti %x/%d) oldNDI %d\n",
+                CC_id, frame, subframe, UE_id,
+                UE_list->UE_template[CC_id][UE_id].rnti,harq_pid, UE_list->UE_template[CC_id][UE_id].oldNDI[harq_pid]);
+          UE_list->UE_template[CC_id][UE_id].oldNDI[harq_pid]= 1 - UE_list->UE_template[CC_id][UE_id].oldNDI[harq_pid];
+	  ndi =  UE_list->UE_template[CC_id][UE_id].oldNDI[harq_pid];
+	  
+	  UE_list->UE_template[CC_id][UE_id].mcs[harq_pid] = mcs;
+	  UE_list->UE_template[CC_id][UE_id].oldTPC[harq_pid] = tpc;
+
+	  // Increase the pointer for the number of scheduled UEs
+	  num_ues_added++;
+	  ue_has_transmission = 1;
+	}  else { // There is no data from RLC or MAC header, so don't schedule
+	  ue_has_transmission = 0;
 	}
-    }
-
-    stop_meas(&eNB->schedule_dlsch);
-    VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME
-	(VCD_SIGNAL_DUMPER_FUNCTIONS_SCHEDULE_DLSCH, VCD_FUNCTION_OUT);
+      } // End of new scheduling
+        
+      // If we has transmission or retransmission
+      if (ue_has_transmission) {
+        	switch (mac_xface->get_transmission_mode(mod_id, CC_id, rnti)) {
+        	case 1:
+        	case 2:
+        	default:
+        	  dl_dci->has_res_alloc = 1;
+        	  dl_dci->res_alloc = 0;
+        	  dl_dci->has_vrb_format = 1;
+        	  dl_dci->vrb_format = PROTOCOL__FLEX_VRB_FORMAT__FLVRBF_LOCALIZED;
+        	  dl_dci->has_format = 1;
+        	  dl_dci->format = PROTOCOL__FLEX_DCI_FORMAT__FLDCIF_1;
+        	  dl_dci->has_rb_bitmap = 1;
+        	  dl_dci->rb_bitmap = allocate_prbs_sub(nb_rb, rballoc_sub);
+        	  dl_dci->has_rb_shift = 1;
+        	  dl_dci->rb_shift = 0;
+        	  dl_dci->n_ndi = 1;
+        	  dl_dci->ndi = (uint32_t *) malloc(sizeof(uint32_t) * dl_dci->n_ndi);
+        	  dl_dci->ndi[0] = ndi;
+        	  dl_dci->n_rv = 1;
+        	  dl_dci->rv = (uint32_t *) malloc(sizeof(uint32_t) * dl_dci->n_rv);
+        	  dl_dci->rv[0] = round & 3;
+        	  dl_dci->has_tpc = 1;
+        	  dl_dci->tpc = tpc;
+        	  dl_dci->n_mcs = 1;
+        	  dl_dci->mcs = (uint32_t *) malloc(sizeof(uint32_t) * dl_dci->n_mcs);
+        	  dl_dci->mcs[0] = mcs;
+        	  dl_dci->n_tbs_size = 1;
+        	  dl_dci->tbs_size = (uint32_t *) malloc(sizeof(uint32_t) * dl_dci->n_tbs_size);
+        	  dl_dci->tbs_size[0] = dci_tbs;
+        	  if (flexran_get_duplex_mode(mod_id, CC_id) == PROTOCOL__FLEX_DUPLEX_MODE__FLDM_TDD) {
+        	    dl_dci->has_dai = 1;
+        	    dl_dci->dai = (UE_list->UE_template[CC_id][UE_id].DAI-1)&3;
+        	  }
+        	  break;
+        	case 3:
+        	  dl_dci->has_res_alloc = 1;
+        	  dl_dci->res_alloc = 0;
+        	  dl_dci->has_vrb_format = 1;
+        	  dl_dci->vrb_format = PROTOCOL__FLEX_VRB_FORMAT__FLVRBF_LOCALIZED;
+        	  dl_dci->has_format = 1;
+        	  dl_dci->format = PROTOCOL__FLEX_DCI_FORMAT__FLDCIF_2A;
+        	  dl_dci->has_rb_bitmap = 1;
+        	  dl_dci->rb_bitmap = allocate_prbs_sub(nb_rb, rballoc_sub);
+        	  dl_dci->has_rb_shift = 1;
+        	  dl_dci->rb_shift = 0;
+        	  dl_dci->n_ndi = 2;
+        	  dl_dci->ndi = (uint32_t *) malloc(sizeof(uint32_t) * dl_dci->n_ndi);
+        	  dl_dci->ndi[0] = ndi;
+        	  dl_dci->ndi[1] = ndi;
+        	  dl_dci->n_rv = 2;
+        	  dl_dci->rv = (uint32_t *) malloc(sizeof(uint32_t) * dl_dci->n_rv);
+        	  dl_dci->rv[0] = round & 3;
+        	  dl_dci->rv[1] = round & 3;
+        	  dl_dci->has_tpc = 1;
+        	  dl_dci->tpc = tpc;
+        	  dl_dci->n_mcs = 2;
+        	  dl_dci->mcs = (uint32_t *) malloc(sizeof(uint32_t) * dl_dci->n_mcs);
+        	  dl_dci->mcs[0] = mcs;
+        	  dl_dci->mcs[1] = mcs;
+        	  dl_dci->n_tbs_size = 2;
+        	  dl_dci->tbs_size = (uint32_t *) malloc(sizeof(uint32_t) * dl_dci->n_tbs_size);
+        	  dl_dci->tbs_size[0] = dci_tbs;
+        	  dl_dci->tbs_size[1] = dci_tbs;
+        	  if (flexran_get_duplex_mode(mod_id, CC_id) == PROTOCOL__FLEX_DUPLEX_MODE__FLDM_TDD) {
+        	    dl_dci->has_dai = 1;
+        	    dl_dci->dai = (UE_list->UE_template[CC_id][UE_id].DAI-1)&3;
+        	  }
+        	  break;
+        	case 4:
+        	  dl_dci->has_res_alloc = 1;
+        	  dl_dci->res_alloc = 0;
+        	  dl_dci->has_vrb_format = 1;
+        	  dl_dci->vrb_format = PROTOCOL__FLEX_VRB_FORMAT__FLVRBF_LOCALIZED;
+        	  dl_dci->has_format = 1;
+        	  dl_dci->format = PROTOCOL__FLEX_DCI_FORMAT__FLDCIF_2A;
+        	  dl_dci->has_rb_bitmap = 1;
+        	  dl_dci->rb_bitmap = allocate_prbs_sub(nb_rb, rballoc_sub);
+        	  dl_dci->has_rb_shift = 1;
+        	  dl_dci->rb_shift = 0;
+        	  dl_dci->n_ndi = 2;
+        	  dl_dci->ndi = (uint32_t *) malloc(sizeof(uint32_t) * dl_dci->n_ndi);
+        	  dl_dci->ndi[0] = ndi;
+        	  dl_dci->ndi[1] = ndi;
+        	  dl_dci->n_rv = 2;
+        	  dl_dci->rv = (uint32_t *) malloc(sizeof(uint32_t) * dl_dci->n_rv);
+        	  dl_dci->rv[0] = round & 3;
+        	  dl_dci->rv[1] = round & 3;
+        	  dl_dci->has_tpc = 1;
+        	  dl_dci->tpc = tpc;
+        	  dl_dci->n_mcs = 2;
+        	  dl_dci->mcs = (uint32_t *) malloc(sizeof(uint32_t) * dl_dci->n_mcs);
+        	  dl_dci->mcs[0] = mcs;
+        	  dl_dci->mcs[1] = mcs;
+        	  dl_dci->n_tbs_size = 2;
+        	  dl_dci->tbs_size = (uint32_t *) malloc(sizeof(uint32_t) * dl_dci->n_tbs_size);
+        	  dl_dci->tbs_size[0] = dci_tbs;
+        	  dl_dci->tbs_size[1] = dci_tbs;
+        	  if (flexran_get_duplex_mode(mod_id, CC_id) == PROTOCOL__FLEX_DUPLEX_MODE__FLDM_TDD) {
+        	    dl_dci->has_dai = 1;
+        	    dl_dci->dai = (UE_list->UE_template[CC_id][UE_id].DAI-1)&3;
+        	  }
+        	  break;
+        	case 5:
+        	  dl_dci->has_res_alloc = 1;
+        	  dl_dci->res_alloc = 0;
+        	  dl_dci->has_vrb_format = 1;
+        	  dl_dci->vrb_format = PROTOCOL__FLEX_VRB_FORMAT__FLVRBF_LOCALIZED;
+        	  dl_dci->has_format = 1;
+        	  dl_dci->format = PROTOCOL__FLEX_DCI_FORMAT__FLDCIF_1D;
+        	  dl_dci->has_rb_bitmap = 1;
+        	  dl_dci->rb_bitmap = allocate_prbs_sub(nb_rb, rballoc_sub);
+        	  dl_dci->has_rb_shift = 1;
+        	  dl_dci->rb_shift = 0;
+        	  dl_dci->n_ndi = 1;
+        	  dl_dci->ndi[0] = ndi;
+        	  dl_dci->n_rv = 1;
+        	  dl_dci->rv = (uint32_t *) malloc(sizeof(uint32_t) * dl_dci->n_rv);
+        	  dl_dci->rv[0] = round & 3;
+        	  dl_dci->has_tpc = 1;
+        	  dl_dci->tpc = tpc;
+        	  dl_dci->n_mcs = 1;
+        	  dl_dci->mcs = (uint32_t *) malloc(sizeof(uint32_t) * dl_dci->n_mcs);
+        	  dl_dci->mcs[0] = mcs;
+        	  dl_dci->n_tbs_size = 1;
+        	  dl_dci->tbs_size = (uint32_t *) malloc(sizeof(uint32_t) * dl_dci->n_tbs_size);
+        	  dl_dci->tbs_size[0] = dci_tbs;
+        	  if (flexran_get_duplex_mode(mod_id, CC_id) == PROTOCOL__FLEX_DUPLEX_MODE__FLDM_TDD) {
+        	    dl_dci->has_dai = 1;
+        	    dl_dci->dai = (UE_list->UE_template[CC_id][UE_id].DAI-1)&3;
+        	  }
+        	  
+        	  if(ue_sched_ctl->dl_pow_off[CC_id] == 2) {
+        	    ue_sched_ctl->dl_pow_off[CC_id] = 1;
+        	  }
+        	  
+        	  dl_dci->has_dl_power_offset = 1;
+        	  dl_dci->dl_power_offset = ue_sched_ctl->dl_pow_off[CC_id];
+        	  dl_dci->has_precoding_info = 1;
+        	  dl_dci->precoding_info = 5; // Is this right??
+        	  
+        	  break;
+        	case 6:
+        	  dl_dci->has_res_alloc = 1;
+        	  dl_dci->res_alloc = 0;
+        	  dl_dci->has_vrb_format = 1;
+        	  dl_dci->vrb_format = PROTOCOL__FLEX_VRB_FORMAT__FLVRBF_LOCALIZED;
+        	  dl_dci->has_format = 1;
+        	  dl_dci->format = PROTOCOL__FLEX_DCI_FORMAT__FLDCIF_1D;
+        	  dl_dci->has_rb_bitmap = 1;
+        	  dl_dci->rb_bitmap = allocate_prbs_sub(nb_rb, rballoc_sub);
+        	  dl_dci->has_rb_shift = 1;
+        	  dl_dci->rb_shift = 0;
+        	  dl_dci->n_ndi = 1;
+        	  dl_dci->ndi = (uint32_t *) malloc(sizeof(uint32_t) * dl_dci->n_ndi);
+        	  dl_dci->ndi[0] = ndi;
+        	  dl_dci->n_rv = 1;
+        	  dl_dci->rv = (uint32_t *) malloc(sizeof(uint32_t) * dl_dci->n_rv);
+        	  dl_dci->rv[0] = round & 3;
+        	  dl_dci->has_tpc = 1;
+        	  dl_dci->tpc = tpc;
+        	  dl_dci->n_mcs = 1;
+        	  dl_dci->mcs = (uint32_t *) malloc(sizeof(uint32_t) * dl_dci->n_mcs);
+        	  dl_dci->mcs[0] = mcs;
+        	  if (flexran_get_duplex_mode(mod_id, CC_id) == PROTOCOL__FLEX_DUPLEX_MODE__FLDM_TDD) {
+        	    dl_dci->has_dai = 1;
+        	    dl_dci->dai = (UE_list->UE_template[CC_id][UE_id].DAI-1)&3;
+        	  }
+
+        	  dl_dci->has_dl_power_offset = 1;
+        	  dl_dci->dl_power_offset = ue_sched_ctl->dl_pow_off[CC_id];
+        	  dl_dci->has_precoding_info = 1;
+        	  dl_dci->precoding_info = 5; // Is this right??
+        	  break;
+        	}
+      }
+      
+      // if (flexran_get_duplex_mode(mod_id, CC_id) == PROTOCOL__FLEX_DUPLEX_MODE__FLDM_TDD) {
+        
+	/* TODO */
+	//set_ul_DAI(mod_id, UE_id, CC_id, frame, subframe, frame_parms);
+      // }
+    } // UE_id loop
+   } // CC_id loop
+
+   // Add all the dl_data elements to the flexran message
+   int offset = (*dl_info)->dl_mac_config_msg->n_dl_ue_data;
+   (*dl_info)->dl_mac_config_msg->n_dl_ue_data += num_ues_added;
+   if ( num_ues_added > 0 ){
+     (*dl_info)->dl_mac_config_msg->dl_ue_data = (Protocol__FlexDlData **) realloc( (*dl_info)->dl_mac_config_msg->dl_ue_data,
+										    sizeof(Protocol__FlexDlData *) * ((*dl_info)->dl_mac_config_msg->n_dl_ue_data));
+     if ((*dl_info)->dl_mac_config_msg->dl_ue_data == NULL ){
+       LOG_E(MAC, "Request for memory reallocation failed\n");
+       return;
+     }
+     for (i = 0; i < num_ues_added; i++) {
+       (*dl_info)->dl_mac_config_msg->dl_ue_data[offset+i] = dl_data[i];
+     }
+   }
+      
+   stop_meas(&eNB->schedule_dlsch);
+   VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_SCHEDULE_DLSCH,VCD_FUNCTION_OUT);
 }
diff --git a/openair2/LAYER2/MAC/flexran_agent_scheduler_dlsch_ue_remote.c b/openair2/LAYER2/MAC/flexran_agent_scheduler_dlsch_ue_remote.c
index 68c86f1da54671e4110c5bb6bb8a610be210725a..2b0bf72015f9463a2b48a6d2985f526a9bdff112 100644
--- a/openair2/LAYER2/MAC/flexran_agent_scheduler_dlsch_ue_remote.c
+++ b/openair2/LAYER2/MAC/flexran_agent_scheduler_dlsch_ue_remote.c
@@ -30,7 +30,7 @@
  */
 
 #include "flexran_agent_common_internal.h"
-
+#include "flexran_agent_ran_api.h"
 #include "flexran_agent_scheduler_dlsch_ue_remote.h"
 
 #include "LAYER2/MAC/defs.h"
diff --git a/openair2/LAYER2/MAC/flexran_agent_scheduler_ulsch_ue.c b/openair2/LAYER2/MAC/flexran_agent_scheduler_ulsch_ue.c
new file mode 100644
index 0000000000000000000000000000000000000000..86ea61d943ff120fd6f24e11ca9aab0aaea6ca58
--- /dev/null
+++ b/openair2/LAYER2/MAC/flexran_agent_scheduler_ulsch_ue.c
@@ -0,0 +1,1112 @@
+/*
+ * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The OpenAirInterface Software Alliance licenses this file to You under
+ * the OAI Public License, Version 1.0  (the "License"); you may not use this file
+ * except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.openairinterface.org/?page_id=698
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *-------------------------------------------------------------------------------
+ * For more information about the OpenAirInterface (OAI) Software Alliance:
+ *      contact@openairinterface.org
+ */
+
+/*! \file eNB_scheduler_ulsch.c
+ * \brief FlexRAN eNB procedures for the ULSCH transport channel
+ * \author Navid Nikaein and shahab SHARIAT BAGHERI
+ * \date 2017
+ * \version 1.0
+ * @ingroup _mac
+
+ */
+
+#include "assertions.h"
+#include "PHY/defs.h"
+#include "PHY/extern.h"
+
+#include "SCHED/defs.h"
+#include "SCHED/extern.h"
+
+#include "LAYER2/MAC/flexran_agent_mac_proto.h"
+#include "LAYER2/MAC/defs.h"
+#include "LAYER2/MAC/proto.h"
+#include "LAYER2/MAC/extern.h"
+#include "UTIL/LOG/log.h"
+#include "UTIL/LOG/vcd_signal_dumper.h"
+#include "UTIL/OPT/opt.h"
+#include "OCG.h"
+#include "OCG_extern.h"
+
+#include "RRC/LITE/extern.h"
+#include "RRC/L2_INTERFACE/openair_rrc_L2_interface.h"
+
+//#include "LAYER2/MAC/pre_processor.c"
+#include "ENB_APP/flexran_agent_defs.h"
+#include "flexran_agent_ran_api.h"
+#include "pdcp.h"
+
+#include "header.pb-c.h"
+#include "flexran.pb-c.h"
+#include "flexran_agent_mac.h"
+
+#if defined(ENABLE_ITTI)
+# include "intertask_interface.h"
+#endif
+
+#include "T.h"
+
+#include <dlfcn.h>
+
+/* number of active slices for  past and current time*/
+int n_active_slices_uplink = 1;
+int n_active_slices_current_uplink = 1;
+
+/* RB share for each slice for past and current time*/
+float avg_slice_percentage_uplink=0.25;
+float slice_percentage_uplink[MAX_NUM_SLICES] = {1.0, 0.0, 0.0, 0.0};
+float slice_percentage_current_uplink[MAX_NUM_SLICES] = {1.0, 0.0, 0.0, 0.0};
+float total_slice_percentage_uplink = 0;
+float total_slice_percentage_current_uplink = 0;
+
+// MAX MCS for each slice for past and current time
+int slice_maxmcs_uplink[MAX_NUM_SLICES] = {16, 16, 16, 16};
+int slice_maxmcs_current_uplink[MAX_NUM_SLICES] = {16,16,16,16};
+
+/*resource blocks allowed*/
+uint16_t         nb_rbs_allowed_slice_uplink[MAX_NUM_CCs][MAX_NUM_SLICES];      
+/*Slice Update */
+int update_ul_scheduler[MAX_NUM_SLICES] = {1, 1, 1, 1};
+int update_ul_scheduler_current[MAX_NUM_SLICES] = {1, 1, 1, 1};
+
+ /* Slice Function Pointer */
+slice_scheduler_ul slice_sched_ul[MAX_NUM_SLICES] = {0};
+
+/* name of available scheduler*/
+char *ul_scheduler_type[MAX_NUM_SLICES] = {"flexran_schedule_ue_ul_spec_embb",
+					   "flexran_schedule_ue_ul_spec_embb",
+					   "flexran_schedule_ue_ul_spec_embb",
+					   "flexran_schedule_ue_ul_spec_embb"      // best effort 
+};
+
+
+uint16_t flexran_nb_rbs_allowed_slice_uplink(float rb_percentage, int total_rbs){
+  return  (uint16_t) floor(rb_percentage * total_rbs); 
+}
+
+
+void _assign_max_mcs_min_rb(module_id_t module_idP, int slice_id, int frameP, sub_frame_t subframeP, uint16_t *first_rb)
+{
+
+  int                i;
+  uint16_t           n,UE_id;
+  uint8_t            CC_id;
+  rnti_t             rnti           = -1;
+  int                mcs;
+  int                rb_table_index=0,tbs,tx_power;
+  eNB_MAC_INST       *eNB = &eNB_mac_inst[module_idP];
+  UE_list_t          *UE_list = &eNB->UE_list;
+
+  UE_TEMPLATE       *UE_template;
+  LTE_DL_FRAME_PARMS   *frame_parms;
+
+   
+  for (i = 0; i < NUMBER_OF_UE_MAX; i++) {
+    if (UE_list->active[i] != TRUE) continue;
+
+    rnti = UE_RNTI(module_idP,i);
+
+    if (rnti==NOT_A_RNTI)
+      continue;
+    if (UE_list->UE_sched_ctrl[i].ul_out_of_sync == 1)
+      continue;
+    if (!phy_stats_exist(module_idP, rnti))
+      continue;
+
+    if (UE_list->UE_sched_ctrl[i].phr_received == 1)
+      mcs = 20; // if we've received the power headroom information the UE, we can go to maximum mcs
+    else
+      mcs = 10; // otherwise, limit to QPSK PUSCH
+
+    UE_id = i;
+
+    for (n=0; n<UE_list->numactiveULCCs[UE_id]; n++) {
+      // This is the actual CC_id in the list
+      CC_id = UE_list->ordered_ULCCids[n][UE_id];
+
+      if (CC_id >= MAX_NUM_CCs) {
+        LOG_E( MAC, "CC_id %u should be < %u, loop n=%u < numactiveULCCs[%u]=%u",
+               CC_id,
+               MAX_NUM_CCs,
+               n,
+               UE_id,
+               UE_list->numactiveULCCs[UE_id]);
+      }
+
+      AssertFatal( CC_id < MAX_NUM_CCs, "CC_id %u should be < %u, loop n=%u < numactiveULCCs[%u]=%u",
+                   CC_id,
+                   MAX_NUM_CCs,
+                   n,
+                   UE_id,
+                   UE_list->numactiveULCCs[UE_id]);
+      frame_parms=mac_xface->get_lte_frame_parms(module_idP,CC_id);
+      UE_template = &UE_list->UE_template[CC_id][UE_id];
+      nb_rbs_allowed_slice_uplink[CC_id][UE_id] = flexran_nb_rbs_allowed_slice_uplink(slice_percentage_uplink[UE_id], flexran_get_N_RB_UL(module_idP, CC_id));
+      // if this UE has UL traffic
+      if (UE_template->ul_total_buffer > 0 ) {
+
+        tbs = mac_xface->get_TBS_UL(mcs,3);  // 1 or 2 PRB with cqi enabled does not work well!
+        // fixme: set use_srs flag
+        tx_power= mac_xface->estimate_ue_tx_power(tbs,rb_table[rb_table_index],0,frame_parms->Ncp,0);
+
+        while ((((UE_template->phr_info - tx_power) < 0 ) || (tbs > UE_template->ul_total_buffer))&&
+               (mcs > 3)) {
+          // LOG_I(MAC,"UE_template->phr_info %d tx_power %d mcs %d\n", UE_template->phr_info,tx_power, mcs);
+          mcs--;
+          tbs = mac_xface->get_TBS_UL(mcs,rb_table[rb_table_index]);
+          tx_power = mac_xface->estimate_ue_tx_power(tbs,rb_table[rb_table_index],0,frame_parms->Ncp,0); // fixme: set use_srs
+        }
+
+        while ((tbs < UE_template->ul_total_buffer) &&
+               (rb_table[rb_table_index]<(nb_rbs_allowed_slice_uplink[CC_id][UE_id]-first_rb[CC_id])) &&
+               ((UE_template->phr_info - tx_power) > 0) &&
+               (rb_table_index < 32 )) {
+          //  LOG_I(MAC,"tbs %d ul buffer %d rb table %d max ul rb %d\n", tbs, UE_template->ul_total_buffer, rb_table[rb_table_index], frame_parms->N_RB_UL-first_rb[CC_id]);
+          rb_table_index++;
+          tbs = mac_xface->get_TBS_UL(mcs,rb_table[rb_table_index]);
+          tx_power = mac_xface->estimate_ue_tx_power(tbs,rb_table[rb_table_index],0,frame_parms->Ncp,0);
+        }
+
+        UE_template->ue_tx_power = tx_power;
+
+        if (rb_table[rb_table_index]>(nb_rbs_allowed_slice_uplink[CC_id][UE_id]-first_rb[CC_id]-1)) {
+          rb_table_index--;
+        }
+
+        // 1 or 2 PRB with cqi enabled does not work well!
+  if (rb_table[rb_table_index]<3) {
+          rb_table_index=2; //3PRB
+        }
+
+        UE_template->pre_assigned_mcs_ul=mcs;
+        UE_template->pre_allocated_rb_table_index_ul=rb_table_index;
+        UE_template->pre_allocated_nb_rb_ul= rb_table[rb_table_index];
+        LOG_D(MAC,"[eNB %d] frame %d subframe %d: for UE %d CC %d: pre-assigned mcs %d, pre-allocated rb_table[%d]=%d RBs (phr %d, tx power %d)\n",
+              module_idP, frameP, subframeP, UE_id, CC_id,
+              UE_template->pre_assigned_mcs_ul,
+              UE_template->pre_allocated_rb_table_index_ul,
+              UE_template->pre_allocated_nb_rb_ul,
+              UE_template->phr_info,tx_power);
+      } else {
+        UE_template->pre_allocated_rb_table_index_ul=-1;
+        UE_template->pre_allocated_nb_rb_ul=0;
+      }
+    }
+  }
+}
+
+
+
+
+void _ulsch_scheduler_pre_processor(module_id_t module_idP,
+                                   int slice_id,                                                     
+                                   int frameP,
+                                   sub_frame_t subframeP,
+                                   uint16_t *first_rb)
+{
+
+  int16_t            i;
+  uint16_t           UE_id,n,r;
+  uint8_t            CC_id, round, harq_pid;
+  uint16_t           nb_allocated_rbs[MAX_NUM_CCs][NUMBER_OF_UE_MAX],total_allocated_rbs[MAX_NUM_CCs],average_rbs_per_user[MAX_NUM_CCs];
+  uint16_t          nb_rbs_allowed_slice_uplink[MAX_NUM_CCs][MAX_NUM_SLICES];
+  int16_t            total_remaining_rbs[MAX_NUM_CCs];
+  uint16_t           max_num_ue_to_be_scheduled=0,total_ue_count=0;
+  rnti_t             rnti= -1;
+  UE_list_t          *UE_list = &eNB_mac_inst[module_idP].UE_list;
+  UE_TEMPLATE        *UE_template = 0;
+  // LTE_DL_FRAME_PARMS   *frame_parms; //Not used yet
+  UE_sched_ctrl *ue_sched_ctl;
+  
+
+  //LOG_I(MAC,"assign max mcs min rb\n");
+  // maximize MCS and then allocate required RB according to the buffer occupancy with the limit of max available UL RB
+  _assign_max_mcs_min_rb(module_idP, slice_id, frameP, subframeP, first_rb);
+
+  //LOG_I(MAC,"sort ue \n");
+  // sort ues
+  sort_ue_ul (module_idP,frameP, subframeP);
+
+
+  // we need to distribute RBs among UEs
+  // step1:  reset the vars
+  for (CC_id=0; CC_id<MAX_NUM_CCs; CC_id++) {
+    total_allocated_rbs[CC_id]=0;
+    total_remaining_rbs[CC_id]=0;
+    average_rbs_per_user[CC_id]=0;
+
+    for (i=UE_list->head_ul; i>=0; i=UE_list->next_ul[i]) {
+      nb_allocated_rbs[CC_id][i]=0;
+    }
+  }
+
+  //LOG_I(MAC,"step2 \n");
+  // step 2: calculate the average rb per UE
+  total_ue_count =0;
+  max_num_ue_to_be_scheduled=0;
+
+  for (i=UE_list->head_ul; i>=0; i=UE_list->next_ul[i]) {
+
+    rnti = UE_RNTI(module_idP,i);
+
+    if (rnti==NOT_A_RNTI)
+      continue;
+
+    if (UE_list->UE_sched_ctrl[i].ul_out_of_sync == 1)
+      continue;
+
+    if (!phy_stats_exist(module_idP, rnti))
+      continue;
+
+    UE_id = i;
+
+    for (n=0; n<UE_list->numactiveULCCs[UE_id]; n++) {
+      // This is the actual CC_id in the list
+      CC_id = UE_list->ordered_ULCCids[n][UE_id];
+      UE_template = &UE_list->UE_template[CC_id][UE_id];
+      average_rbs_per_user[CC_id]=0;
+      // frame_parms = mac_xface->get_lte_frame_parms(module_idP,CC_id);
+
+      if (UE_template->pre_allocated_nb_rb_ul > 0) {
+        total_ue_count+=1;
+      }
+      /*
+      if((mac_xface->get_nCCE_max(module_idP,CC_id,3,subframeP) - nCCE_to_be_used[CC_id])  > (1<<aggregation)) {
+        nCCE_to_be_used[CC_id] = nCCE_to_be_used[CC_id] + (1<<aggregation);
+        max_num_ue_to_be_scheduled+=1;
+  }*/
+
+      max_num_ue_to_be_scheduled+=1;
+
+     nb_rbs_allowed_slice_uplink[CC_id][UE_id] = flexran_nb_rbs_allowed_slice_uplink(slice_percentage_uplink[UE_id], flexran_get_N_RB_UL(module_idP, CC_id));
+
+      if (total_ue_count == 0) {
+        average_rbs_per_user[CC_id] = 0;
+      } else if (total_ue_count == 1 ) { // increase the available RBs, special case,
+        average_rbs_per_user[CC_id] = nb_rbs_allowed_slice_uplink[CC_id][i]-first_rb[CC_id]+1;
+      } else if( (total_ue_count <= (nb_rbs_allowed_slice_uplink[CC_id][i]-first_rb[CC_id])) &&
+                 (total_ue_count <= max_num_ue_to_be_scheduled)) {
+        average_rbs_per_user[CC_id] = (uint16_t) floor((nb_rbs_allowed_slice_uplink[CC_id][i]-first_rb[CC_id])/total_ue_count);
+      } else if (max_num_ue_to_be_scheduled > 0 ) {
+        average_rbs_per_user[CC_id] = (uint16_t) floor((nb_rbs_allowed_slice_uplink[CC_id][i]-first_rb[CC_id])/max_num_ue_to_be_scheduled);
+      } else {
+        average_rbs_per_user[CC_id]=1;
+        LOG_W(MAC,"[eNB %d] frame %d subframe %d: UE %d CC %d: can't get average rb per user (should not be here)\n",
+              module_idP,frameP,subframeP,UE_id,CC_id);
+      }
+    }
+  }
+  if (total_ue_count > 0)
+    LOG_D(MAC,"[eNB %d] Frame %d subframe %d: total ue to be scheduled %d/%d\n",
+    module_idP, frameP, subframeP,total_ue_count, max_num_ue_to_be_scheduled);
+
+  //LOG_D(MAC,"step3\n");
+
+  // step 3: assigne RBS
+  for (i=UE_list->head_ul; i>=0; i=UE_list->next_ul[i]) {
+    rnti = UE_RNTI(module_idP,i);
+
+    if (rnti==NOT_A_RNTI)
+      continue;
+    if (UE_list->UE_sched_ctrl[i].ul_out_of_sync == 1)
+      continue;
+    if (!phy_stats_exist(module_idP, rnti))
+      continue;
+
+    UE_id = i;
+
+    for (n=0; n<UE_list->numactiveULCCs[UE_id]; n++) {
+      // This is the actual CC_id in the list
+      CC_id = UE_list->ordered_ULCCids[n][UE_id];
+      ue_sched_ctl = &UE_list->UE_sched_ctrl[UE_id];      
+      ue_sched_ctl->max_allowed_rbs[CC_id]=nb_rbs_allowed_slice_uplink[CC_id][UE_id];
+      // mac_xface->get_ue_active_harq_pid(module_idP,CC_id,rnti,frameP,subframeP,&harq_pid,&round,openair_harq_UL);
+      flexran_get_harq(module_idP, CC_id, UE_id, frameP, subframeP, &harq_pid, &round, openair_harq_UL);
+      if(round>0) {
+        nb_allocated_rbs[CC_id][UE_id] = UE_list->UE_template[CC_id][UE_id].nb_rb_ul[harq_pid];
+      } else {
+        nb_allocated_rbs[CC_id][UE_id] = cmin(UE_list->UE_template[CC_id][UE_id].pre_allocated_nb_rb_ul, average_rbs_per_user[CC_id]);
+      }
+
+      total_allocated_rbs[CC_id]+= nb_allocated_rbs[CC_id][UE_id];
+
+    }
+  }
+
+  // step 4: assigne the remaining RBs and set the pre_allocated rbs accordingly
+  for(r=0; r<2; r++) {
+
+    for (i=UE_list->head_ul; i>=0; i=UE_list->next_ul[i]) {
+      rnti = UE_RNTI(module_idP,i);
+
+      if (rnti==NOT_A_RNTI)
+        continue;
+      if (UE_list->UE_sched_ctrl[i].ul_out_of_sync == 1)
+  continue;
+      if (!phy_stats_exist(module_idP, rnti))
+        continue;
+
+      UE_id = i;
+
+      for (n=0; n<UE_list->numactiveULCCs[UE_id]; n++) {
+        // This is the actual CC_id in the list
+        CC_id = UE_list->ordered_ULCCids[n][UE_id];
+        UE_template = &UE_list->UE_template[CC_id][UE_id];        
+        // frame_parms = mac_xface->get_lte_frame_parms(module_idP,CC_id);
+        total_remaining_rbs[CC_id]=nb_rbs_allowed_slice_uplink[CC_id][UE_id] - first_rb[CC_id] - total_allocated_rbs[CC_id];
+
+        if (total_ue_count == 1 ) {
+          total_remaining_rbs[CC_id]+=1;
+        }
+
+        if ( r == 0 ) {
+          while ( (UE_template->pre_allocated_nb_rb_ul > 0 ) &&
+                  (nb_allocated_rbs[CC_id][UE_id] < UE_template->pre_allocated_nb_rb_ul) &&
+                  (total_remaining_rbs[CC_id] > 0)) {
+            nb_allocated_rbs[CC_id][UE_id] = cmin(nb_allocated_rbs[CC_id][UE_id]+1,UE_template->pre_allocated_nb_rb_ul);
+            total_remaining_rbs[CC_id]--;
+            total_allocated_rbs[CC_id]++;
+          }
+        } else {
+          UE_template->pre_allocated_nb_rb_ul= nb_allocated_rbs[CC_id][UE_id];
+          LOG_D(MAC,"******************UL Scheduling Information for UE%d CC_id %d ************************\n",UE_id, CC_id);
+          LOG_D(MAC,"[eNB %d] total RB allocated for UE%d CC_id %d  = %d\n", module_idP, UE_id, CC_id, UE_template->pre_allocated_nb_rb_ul);
+        }
+      }
+    }
+  }
+
+  for (CC_id=0; CC_id<MAX_NUM_CCs; CC_id++) {
+    // frame_parms= mac_xface->get_lte_frame_parms(module_idP,CC_id);
+
+    if (total_allocated_rbs[CC_id]>0) {
+      LOG_D(MAC,"[eNB %d] total RB allocated for all UEs = %d/%d\n", module_idP, total_allocated_rbs[CC_id], nb_rbs_allowed_slice_uplink[CC_id][slice_id] - first_rb[CC_id]);
+    }
+  }
+}
+
+/*
+ * Main Uplink Slicing 
+ *
+ */
+
+void
+flexran_schedule_ue_ul_spec_default(mid_t   mod_id,
+				 uint32_t      frame,
+				 uint32_t      cooperation_flag,
+				 int           subframe,
+				 unsigned char sched_subframe,
+				 Protocol__FlexranMessage **ul_info)
+//------------------------------------------------------------------------------
+{
+  int i=0;
+  
+  flexran_agent_mac_create_empty_ul_config(mod_id, ul_info);
+   
+  total_slice_percentage_uplink=0;
+  avg_slice_percentage_uplink=1.0/n_active_slices_uplink;
+  
+  // reset the slice percentage for inactive slices
+  for (i = n_active_slices_uplink; i< MAX_NUM_SLICES; i++) {
+    slice_percentage_uplink[i]=0;
+  }
+  for (i = 0; i < n_active_slices_uplink; i++) {
+    if (slice_percentage_uplink[i] < 0 ){
+      LOG_W(MAC, "[eNB %d] frame %d subframe %d:invalid slice %d percentage %f. resetting to zero",
+	    mod_id, frame, subframe, i, slice_percentage_uplink[i]);
+      slice_percentage_uplink[i]=0;
+    }
+    total_slice_percentage_uplink+=slice_percentage_uplink[i];
+  }
+ 
+  for (i = 0; i < n_active_slices_uplink; i++) {
+    
+    // Load any updated functions
+    if (update_ul_scheduler[i] > 0 ) {
+      slice_sched_ul[i] = dlsym(NULL, ul_scheduler_type[i]); 
+      update_ul_scheduler[i] = 0;
+      update_ul_scheduler_current[i] = 0;
+      //slice_percentage_current_uplink[i]= slice_percentage_uplink[i];
+      //total_slice_percentage_current_uplink+=slice_percentage_uplink[i];
+      //if (total_slice_percentage_current_uplink> 1) 
+      //	total_slice_percentage_current_uplink=1;
+      LOG_N(MAC,"update ul scheduler slice %d\n", i);
+    }
+    // the new total RB share is within the range
+    if (total_slice_percentage_uplink <= 1.0){
+
+      // check if the number of slices has changed, and log 
+      if (n_active_slices_current_uplink != n_active_slices_uplink ){
+	if ((n_active_slices_uplink > 0) && (n_active_slices_uplink <= MAX_NUM_SLICES)) {
+	  LOG_N(MAC,"[eNB %d]frame %d subframe %d: number of active UL slices has changed: %d-->%d\n",
+		mod_id, frame, subframe, n_active_slices_current_uplink, n_active_slices_uplink);
+	  
+	  n_active_slices_current_uplink = n_active_slices_uplink;
+	  
+	} else {
+	  LOG_W(MAC,"invalid number of UL slices %d, revert to the previous value %d\n",n_active_slices_uplink, n_active_slices_current_uplink);
+	  n_active_slices_uplink = n_active_slices_current_uplink;
+	}
+      }
+    
+    // check if the slice rb share has changed, and log the console
+      if (slice_percentage_current_uplink[i] != slice_percentage_uplink[i]){ 
+      LOG_N(MAC,"[eNB %d][SLICE %d][UL] frame %d subframe %d: total percentage %f-->%f, slice RB percentage has changed: %f-->%f\n",
+	      mod_id, i, frame, subframe, total_slice_percentage_current_uplink, total_slice_percentage_uplink, slice_percentage_current_uplink[i], slice_percentage_uplink[i]);
+	total_slice_percentage_current_uplink= total_slice_percentage_uplink;
+	slice_percentage_current_uplink[i] = slice_percentage_uplink[i];	
+	
+      } 
+      
+      // check if the slice max MCS, and log the console
+      if (slice_maxmcs_current_uplink[i] != slice_maxmcs_uplink[i]){
+	if ((slice_maxmcs_uplink[i] >= 0) && (slice_maxmcs_uplink[i] <= 16)){
+	  LOG_N(MAC,"[eNB %d][SLICE %d][UL] frame %d subframe %d: slice MAX MCS has changed: %d-->%d\n",
+		mod_id, i, frame, subframe, slice_maxmcs_current_uplink[i], slice_maxmcs_uplink[i]);
+	  slice_maxmcs_current_uplink[i] = slice_maxmcs_uplink[i];
+	} else {
+	  LOG_W(MAC,"[eNB %d][SLICE %d][UL] invalid slice max mcs %d, revert the previous value %d\n",mod_id, i, slice_maxmcs_uplink[i],slice_maxmcs_current_uplink[i]);
+	  slice_maxmcs_uplink[i]= slice_maxmcs_current_uplink[i];
+	  
+	}
+      }
+      
+      // check if a new scheduler, and log the console
+      if (update_ul_scheduler_current[i] != update_ul_scheduler[i]){
+	LOG_N(MAC,"[eNB %d][SLICE %d][UL] frame %d subframe %d: UL scheduler for this slice is updated: %s \n",
+	      mod_id, i, frame, subframe, ul_scheduler_type[i]);
+	
+	update_ul_scheduler_current[i] = update_ul_scheduler[i];
+      }
+    }
+      else {
+	
+	if (n_active_slices_uplink == n_active_slices_current_uplink){
+	  LOG_W(MAC,"[eNB %d][SLICE %d][UL] invalid total RB share (%f->%f), reduce proportionally the RB share by 0.1\n",
+		mod_id,i,  
+		total_slice_percentage_current_uplink, total_slice_percentage_uplink);
+	  if (slice_percentage_uplink[i] > avg_slice_percentage_uplink){
+	    slice_percentage_uplink[i]-=0.1;
+	    total_slice_percentage_uplink-=0.1;
+	  }
+	} else {
+	  // here we can correct the values, e.g. reduce proportionally 
+	  LOG_W(MAC,"[eNB %d][SLICE %d][UL] invalid total RB share (%f->%f), revert the  number of slice to its previous value (%d->%d)\n",
+		mod_id,i,  
+		total_slice_percentage_current_uplink, total_slice_percentage_uplink,
+		n_active_slices_uplink, n_active_slices_current_uplink);
+	  n_active_slices_uplink = n_active_slices_current_uplink;
+	  slice_percentage_uplink[i] = slice_percentage_current_uplink[i];
+	}
+      }
+     
+    // Run each enabled slice-specific schedulers one by one
+    slice_sched_ul[i](mod_id, frame, cooperation_flag, subframe, sched_subframe,ul_info);
+  }
+}
+
+void
+flexran_schedule_ue_ul_spec_embb(mid_t  mod_id,
+				 frame_t frame, 
+				 unsigned char cooperation_flag,
+				 uint32_t      subframe,
+				 unsigned char sched_subframe,
+				 Protocol__FlexranMessage **ul_info)
+  
+{
+  flexran_agent_schedule_ulsch_ue_spec(mod_id,
+				       frame,
+				       cooperation_flag,
+				       subframe,
+				       sched_subframe,
+				       ul_info);
+  
+}
+
+
+void flexran_agent_schedule_ulsch_ue_spec(mid_t module_idP, 
+		    frame_t frameP,
+		    unsigned char cooperation_flag,
+		    sub_frame_t subframeP, 
+		    unsigned char sched_subframe,
+        Protocol__FlexranMessage **ul_info) {
+
+
+  uint16_t first_rb[MAX_NUM_CCs],i;
+  int CC_id;
+  eNB_MAC_INST *eNB=&eNB_mac_inst[module_idP];
+
+  start_meas(&eNB->schedule_ulsch);
+
+
+  for (CC_id=0; CC_id<MAX_NUM_CCs; CC_id++) {
+
+    //leave out first RB for PUCCH
+    first_rb[CC_id] = 1;
+
+    // UE data info;
+    // check which UE has data to transmit
+    // function to decide the scheduling
+    // e.g. scheduling_rslt = Greedy(granted_UEs, nb_RB)
+
+    // default function for default scheduling
+    //
+
+    // output of scheduling, the UE numbers in RBs, where it is in the code???
+    // check if RA (Msg3) is active in this subframeP, if so skip the PRBs used for Msg3
+    // Msg3 is using 1 PRB so we need to increase first_rb accordingly
+    // not sure about the break (can there be more than 1 active RA procedure?)
+
+    for (i=0; i<NB_RA_PROC_MAX; i++) {
+      if ((eNB->common_channels[CC_id].RA_template[i].RA_active == TRUE) &&
+          (eNB->common_channels[CC_id].RA_template[i].generate_rar == 0) &&
+          (eNB->common_channels[CC_id].RA_template[i].generate_Msg4 == 0) &&
+          (eNB->common_channels[CC_id].RA_template[i].wait_ack_Msg4 == 0) &&
+          (eNB->common_channels[CC_id].RA_template[i].Msg3_subframe == sched_subframe)) {
+        first_rb[CC_id]++;
+        eNB->common_channels[CC_id].RA_template[i].Msg3_subframe = -1;
+        break;
+      }
+    }
+
+    /*
+    if (mac_xface->is_prach_subframe(&(mac_xface->lte_frame_parms),frameP,subframeP)) {
+      first_rb[CC_id] = (mac_xface->get_prach_prb_offset(&(mac_xface->lte_frame_parms),
+    */
+
+  }
+
+  flexran_agent_schedule_ulsch_rnti(module_idP, cooperation_flag, frameP, subframeP, sched_subframe,first_rb);
+
+  stop_meas(&eNB->schedule_ulsch);
+
+}
+
+
+
+void flexran_agent_schedule_ulsch_rnti(module_id_t   module_idP,
+                         unsigned char cooperation_flag,
+                         frame_t       frameP,
+                         sub_frame_t   subframeP,
+                         unsigned char sched_subframe,
+                         uint16_t     *first_rb)
+{
+
+  int                UE_id;
+  uint8_t            aggregation    = 2;
+  rnti_t             rnti           = -1;
+  uint8_t            round          = 0;
+  uint8_t            harq_pid       = 0;
+  void              *ULSCH_dci      = NULL;
+  LTE_eNB_UE_stats  *eNB_UE_stats   = NULL;
+  DCI_PDU           *DCI_pdu;
+  uint8_t                 status         = 0;
+  uint8_t                 rb_table_index = -1;
+  uint16_t                TBS = 0;
+  //  int32_t                buffer_occupancy=0;
+  uint32_t                cqi_req,cshift,ndi,mcs=0,rballoc,tpc;
+  int32_t                 normalized_rx_power, target_rx_power=-90;
+  static int32_t          tpc_accumulated=0;
+
+  int n,CC_id = 0;
+  eNB_MAC_INST      *eNB=&eNB_mac_inst[module_idP];
+  UE_list_t         *UE_list=&eNB->UE_list;
+  UE_TEMPLATE       *UE_template;
+  UE_sched_ctrl     *UE_sched_ctrl;
+
+  //  int                rvidx_tab[4] = {0,2,3,1};
+  LTE_DL_FRAME_PARMS   *frame_parms;
+  int drop_ue=0;
+
+  //  LOG_I(MAC,"entering ulsch preprocesor\n");
+
+
+  /*TODO*/
+  int slice_id = 0;
+
+  
+  _ulsch_scheduler_pre_processor(module_idP,
+                                slice_id,  
+                                frameP,
+                                subframeP,
+                                first_rb);
+
+  //  LOG_I(MAC,"exiting ulsch preprocesor\n");
+
+  // loop over all active UEs
+  for (UE_id=UE_list->head_ul; UE_id>=0; UE_id=UE_list->next_ul[UE_id]) {
+
+    // don't schedule if Msg4 is not received yet
+    if (UE_list->UE_template[UE_PCCID(module_idP,UE_id)][UE_id].configured==FALSE) {
+      LOG_I(MAC,"[eNB %d] frame %d subfarme %d, UE %d: not configured, skipping UE scheduling \n", 
+	    module_idP,frameP,subframeP,UE_id);
+      continue;
+    }
+
+    rnti = flexran_get_ue_crnti(module_idP, UE_id);
+
+    if (rnti==NOT_A_RNTI) {
+      LOG_W(MAC,"[eNB %d] frame %d subfarme %d, UE %d: no RNTI \n", module_idP,frameP,subframeP,UE_id);
+      continue;
+    }
+
+    /* let's drop the UE if get_eNB_UE_stats returns NULL when calling it with any of the UE's active UL CCs */
+    /* TODO: refine? */
+    drop_ue = 0;
+    for (n=0; n<UE_list->numactiveULCCs[UE_id]; n++) {
+      CC_id = UE_list->ordered_ULCCids[n][UE_id];
+      if (mac_xface->get_eNB_UE_stats(module_idP,CC_id,rnti) == NULL) {
+        LOG_W(MAC,"[eNB %d] frame %d subframe %d, UE %d/%x CC %d: no PHY context\n", module_idP,frameP,subframeP,UE_id,rnti,CC_id);
+        drop_ue = 1;
+        break;
+      }
+    }
+    if (drop_ue == 1) {
+/* we can't come here, ulsch_scheduler_pre_processor won't put in the list a UE with no PHY context */
+abort();
+      /* TODO: this is a hack. Sometimes the UE has no PHY context but
+       * is still present in the MAC with 'ul_failure_timer' = 0 and
+       * 'ul_out_of_sync' = 0. It seems wrong and the UE stays there forever. Let's
+       * start an UL out of sync procedure in this case.
+       * The root cause of this problem has to be found and corrected.
+       * In the meantime, this hack...
+       */
+      if (UE_list->UE_sched_ctrl[UE_id].ul_failure_timer == 0 &&
+          UE_list->UE_sched_ctrl[UE_id].ul_out_of_sync == 0) {
+        LOG_W(MAC,"[eNB %d] frame %d subframe %d, UE %d/%x CC %d: UE in weird state, let's put it 'out of sync'\n",
+              module_idP,frameP,subframeP,UE_id,rnti,CC_id);
+        // inform RRC of failure and clear timer
+        mac_eNB_rrc_ul_failure(module_idP,CC_id,frameP,subframeP,rnti);
+        UE_list->UE_sched_ctrl[UE_id].ul_failure_timer=0;
+        UE_list->UE_sched_ctrl[UE_id].ul_out_of_sync=1;
+      }
+      continue;
+    }
+
+    // loop over all active UL CC_ids for this UE
+    for (n=0; n<UE_list->numactiveULCCs[UE_id]; n++) {
+      // This is the actual CC_id in the list
+      CC_id = UE_list->ordered_ULCCids[n][UE_id];
+      frame_parms = mac_xface->get_lte_frame_parms(module_idP,CC_id);
+      eNB_UE_stats = mac_xface->get_eNB_UE_stats(module_idP,CC_id,rnti);
+
+      aggregation=get_aggregation(get_bw_index(module_idP,CC_id), 
+				  eNB_UE_stats->DL_cqi[0],
+				  format0);
+      
+      if (CCE_allocation_infeasible(module_idP,CC_id,0,subframeP,aggregation,rnti)) {
+        LOG_W(MAC,"[eNB %d] frame %d subframe %d, UE %d/%x CC %d: not enough nCCE\n", module_idP,frameP,subframeP,UE_id,rnti,CC_id);
+        continue; // break;
+      } else{
+	LOG_D(MAC,"[eNB %d] frame %d subframe %d, UE %d/%x CC %d mode %s: aggregation level %d\n", 
+	      module_idP,frameP,subframeP,UE_id,rnti,CC_id, mode_string[eNB_UE_stats->mode], 1<<aggregation);
+      }
+
+
+      if (eNB_UE_stats->mode == PUSCH) { // ue has a ulsch channel
+
+        DCI_pdu = &eNB->common_channels[CC_id].DCI_pdu;
+        UE_template   = &UE_list->UE_template[CC_id][UE_id];
+        UE_sched_ctrl = &UE_list->UE_sched_ctrl[UE_id];
+
+        if (flexran_get_harq(module_idP, CC_id, UE_id, frameP, subframeP, &harq_pid, &round, openair_harq_UL) == -1 ) {
+          LOG_W(MAC,"[eNB %d] Scheduler Frame %d, subframeP %d: candidate harq_pid from PHY for UE %d CC %d RNTI %x\n",
+                module_idP,frameP,subframeP, UE_id, CC_id, rnti);
+          continue;
+        } else
+          LOG_T(MAC,"[eNB %d] Frame %d, subframeP %d, UE %d CC %d : got harq pid %d  round %d (rnti %x,mode %s)\n",
+                module_idP,frameP,subframeP,UE_id,CC_id, harq_pid, round,rnti,mode_string[eNB_UE_stats->mode]);
+
+	PHY_vars_eNB_g[module_idP][CC_id]->pusch_stats_BO[UE_id][(frameP*10)+subframeP] = UE_template->ul_total_buffer;
+	VCD_SIGNAL_DUMPER_DUMP_VARIABLE_BY_NAME(VCD_SIGNAL_DUMPER_VARIABLES_UE0_BO,PHY_vars_eNB_g[module_idP][CC_id]->pusch_stats_BO[UE_id][(frameP*10)+subframeP]);	
+        if (((UE_is_to_be_scheduled(module_idP,CC_id,UE_id)>0)) || (round>0))// || ((frameP%10)==0))
+          // if there is information on bsr of DCCH, DTCH or if there is UL_SR, or if there is a packet to retransmit, or we want to schedule a periodic feedback every 10 frames
+        {
+	  LOG_D(MAC,"[eNB %d][PUSCH] Frame %d subframe %d Scheduling UE %d/%x in round %d(SR %d,UL_inactivity timer %d,UL_failure timer %d)\n",
+		module_idP,frameP,subframeP,UE_id,rnti,round,UE_template->ul_SR,
+		UE_sched_ctrl->ul_inactivity_timer,
+		UE_sched_ctrl->ul_failure_timer);
+          // reset the scheduling request
+          UE_template->ul_SR = 0;
+          // status = mac_eNB_get_rrc_status(module_idP,rnti);
+          status = flexran_get_rrc_status(module_idP, rnti);
+
+	  if (status < RRC_CONNECTED)
+	    cqi_req = 0;
+	  else if (UE_sched_ctrl->cqi_req_timer>30) {
+	    cqi_req = 1;
+	    UE_sched_ctrl->cqi_req_timer=0;
+	  }
+	  else
+	    cqi_req = 0;
+
+          //power control
+          //compute the expected ULSCH RX power (for the stats)
+
+          // this is the normalized RX power and this should be constant (regardless of mcs
+          normalized_rx_power = eNB_UE_stats->UL_rssi[0];
+          target_rx_power = mac_xface->get_target_pusch_rx_power(module_idP,CC_id);
+
+          // this assumes accumulated tpc
+	  // make sure that we are only sending a tpc update once a frame, otherwise the control loop will freak out
+	  int32_t framex10psubframe = UE_template->pusch_tpc_tx_frame*10+UE_template->pusch_tpc_tx_subframe;
+          if (((framex10psubframe+10)<=(frameP*10+subframeP)) || //normal case
+	      ((framex10psubframe>(frameP*10+subframeP)) && (((10240-framex10psubframe+frameP*10+subframeP)>=10)))) //frame wrap-around
+	    {
+	    UE_template->pusch_tpc_tx_frame=frameP;
+	    UE_template->pusch_tpc_tx_subframe=subframeP;
+            if (normalized_rx_power>(target_rx_power+1)) {
+              tpc = 0; //-1
+              tpc_accumulated--;
+            } else if (normalized_rx_power<(target_rx_power-1)) {
+              tpc = 2; //+1
+              tpc_accumulated++;
+            } else {
+              tpc = 1; //0
+            }
+          } else {
+            tpc = 1; //0
+          }
+
+	  if (tpc!=1) {
+	    LOG_D(MAC,"[eNB %d] ULSCH scheduler: frame %d, subframe %d, harq_pid %d, tpc %d, accumulated %d, normalized/target rx power %d/%d\n",
+		  module_idP,frameP,subframeP,harq_pid,tpc,
+		  tpc_accumulated,normalized_rx_power,target_rx_power);
+	  }
+
+          // new transmission
+          if (round==0) {
+
+            ndi = 1-UE_template->oldNDI_UL[harq_pid];
+            UE_template->oldNDI_UL[harq_pid]=ndi;
+	    UE_list->eNB_UE_stats[CC_id][UE_id].normalized_rx_power=normalized_rx_power;
+	    UE_list->eNB_UE_stats[CC_id][UE_id].target_rx_power=target_rx_power;
+	    UE_list->eNB_UE_stats[CC_id][UE_id].ulsch_mcs1=UE_template->pre_assigned_mcs_ul;
+            mcs = UE_template->pre_assigned_mcs_ul;//cmin (UE_template->pre_assigned_mcs_ul, openair_daq_vars.target_ue_ul_mcs); // adjust, based on user-defined MCS
+            if (UE_template->pre_allocated_rb_table_index_ul >=0) {
+              rb_table_index=UE_template->pre_allocated_rb_table_index_ul;
+            } else {
+	      mcs=10;//cmin (10, openair_daq_vars.target_ue_ul_mcs);
+              rb_table_index=5; // for PHR
+	    }
+
+            UE_list->eNB_UE_stats[CC_id][UE_id].ulsch_mcs2=mcs;
+	    //            buffer_occupancy = UE_template->ul_total_buffer;
+
+            while (((rb_table[rb_table_index]>(nb_rbs_allowed_slice_uplink[CC_id][UE_id]-1-first_rb[CC_id])) ||
+		    (rb_table[rb_table_index]>45)) &&
+                   (rb_table_index>0)) {
+              rb_table_index--;
+            }
+
+            TBS = mac_xface->get_TBS_UL(mcs,rb_table[rb_table_index]);
+	    UE_list->eNB_UE_stats[CC_id][UE_id].total_rbs_used_rx+=rb_table[rb_table_index];
+	    UE_list->eNB_UE_stats[CC_id][UE_id].ulsch_TBS=TBS;
+	    //            buffer_occupancy -= TBS;
+            rballoc = mac_xface->computeRIV(frame_parms->N_RB_UL,
+                                            first_rb[CC_id],
+                                            rb_table[rb_table_index]);
+
+            T(T_ENB_MAC_UE_UL_SCHEDULE, T_INT(module_idP), T_INT(CC_id), T_INT(rnti), T_INT(frameP),
+              T_INT(subframeP), T_INT(harq_pid), T_INT(mcs), T_INT(first_rb[CC_id]), T_INT(rb_table[rb_table_index]),
+              T_INT(TBS), T_INT(ndi));
+
+	    if (mac_eNB_get_rrc_status(module_idP,rnti) < RRC_CONNECTED)
+	      LOG_I(MAC,"[eNB %d][PUSCH %d/%x] CC_id %d Frame %d subframeP %d Scheduled UE %d (mcs %d, first rb %d, nb_rb %d, rb_table_index %d, TBS %d, harq_pid %d)\n",
+		    module_idP,harq_pid,rnti,CC_id,frameP,subframeP,UE_id,mcs,
+		    first_rb[CC_id],rb_table[rb_table_index],
+		    rb_table_index,TBS,harq_pid);
+
+	    // bad indices : 20 (40 PRB), 21 (45 PRB), 22 (48 PRB)
+            // increment for next UE allocation
+            first_rb[CC_id]+=rb_table[rb_table_index];
+            //store for possible retransmission
+            UE_template->nb_rb_ul[harq_pid] = rb_table[rb_table_index];
+	    UE_sched_ctrl->ul_scheduled |= (1<<harq_pid);
+	    if (UE_id == UE_list->head)
+	      VCD_SIGNAL_DUMPER_DUMP_VARIABLE_BY_NAME(VCD_SIGNAL_DUMPER_VARIABLES_UE0_SCHEDULED,UE_sched_ctrl->ul_scheduled);
+
+	    // adjust total UL buffer status by TBS, wait for UL sdus to do final update
+	    LOG_D(MAC,"[eNB %d] CC_id %d UE %d/%x : adjusting ul_total_buffer, old %d, TBS %d\n", module_idP,CC_id,UE_id,rnti,UE_template->ul_total_buffer,TBS);
+	    if (UE_template->ul_total_buffer > TBS)
+	      UE_template->ul_total_buffer -= TBS;
+	    else
+	      UE_template->ul_total_buffer = 0;
+	    LOG_D(MAC,"ul_total_buffer, new %d\n", UE_template->ul_total_buffer);
+	    // Cyclic shift for DM RS
+	    cshift = 0;// values from 0 to 7 can be used for mapping the cyclic shift (36.211 , Table 5.5.2.1.1-1)
+	    	    
+	    if (frame_parms->frame_type == TDD) {
+	      switch (frame_parms->N_RB_UL) {
+	      case 6:
+		ULSCH_dci = UE_template->ULSCH_DCI[harq_pid];
+		
+		((DCI0_1_5MHz_TDD_1_6_t *)ULSCH_dci)->type     = 0;
+		((DCI0_1_5MHz_TDD_1_6_t *)ULSCH_dci)->hopping  = 0;
+		((DCI0_1_5MHz_TDD_1_6_t *)ULSCH_dci)->rballoc  = rballoc;
+		((DCI0_1_5MHz_TDD_1_6_t *)ULSCH_dci)->mcs      = mcs;
+		((DCI0_1_5MHz_TDD_1_6_t *)ULSCH_dci)->ndi      = ndi;
+		((DCI0_1_5MHz_TDD_1_6_t *)ULSCH_dci)->TPC      = tpc;
+		((DCI0_1_5MHz_TDD_1_6_t *)ULSCH_dci)->cshift   = cshift;
+		((DCI0_1_5MHz_TDD_1_6_t *)ULSCH_dci)->padding  = 0;
+		((DCI0_1_5MHz_TDD_1_6_t *)ULSCH_dci)->dai      = UE_template->DAI_ul[sched_subframe];
+		((DCI0_1_5MHz_TDD_1_6_t *)ULSCH_dci)->cqi_req  = cqi_req;
+		
+		add_ue_spec_dci(DCI_pdu,
+				ULSCH_dci,
+				rnti,
+				sizeof(DCI0_1_5MHz_TDD_1_6_t),
+				aggregation,
+				sizeof_DCI0_1_5MHz_TDD_1_6_t,
+				format0,
+				0);
+		break;
+		
+	      default:
+	      case 25:
+		ULSCH_dci = UE_template->ULSCH_DCI[harq_pid];
+		
+		((DCI0_5MHz_TDD_1_6_t *)ULSCH_dci)->type     = 0;
+		((DCI0_5MHz_TDD_1_6_t *)ULSCH_dci)->hopping  = 0;
+		((DCI0_5MHz_TDD_1_6_t *)ULSCH_dci)->rballoc  = rballoc;
+		((DCI0_5MHz_TDD_1_6_t *)ULSCH_dci)->mcs      = mcs;
+		((DCI0_5MHz_TDD_1_6_t *)ULSCH_dci)->ndi      = ndi;
+		((DCI0_5MHz_TDD_1_6_t *)ULSCH_dci)->TPC      = tpc;
+		((DCI0_5MHz_TDD_1_6_t *)ULSCH_dci)->cshift   = cshift;
+		((DCI0_5MHz_TDD_1_6_t *)ULSCH_dci)->padding  = 0;
+		((DCI0_5MHz_TDD_1_6_t *)ULSCH_dci)->dai      = UE_template->DAI_ul[sched_subframe];
+		((DCI0_5MHz_TDD_1_6_t *)ULSCH_dci)->cqi_req  = cqi_req;
+		
+		add_ue_spec_dci(DCI_pdu,
+				ULSCH_dci,
+				rnti,
+				sizeof(DCI0_5MHz_TDD_1_6_t),
+				aggregation,
+				sizeof_DCI0_5MHz_TDD_1_6_t,
+				format0,
+				0);
+		break;
+		
+	      case 50:
+		ULSCH_dci = UE_template->ULSCH_DCI[harq_pid];
+		
+		((DCI0_10MHz_TDD_1_6_t *)ULSCH_dci)->type     = 0;
+		((DCI0_10MHz_TDD_1_6_t *)ULSCH_dci)->hopping  = 0;
+		((DCI0_10MHz_TDD_1_6_t *)ULSCH_dci)->rballoc  = rballoc;
+		((DCI0_10MHz_TDD_1_6_t *)ULSCH_dci)->mcs      = mcs;
+		((DCI0_10MHz_TDD_1_6_t *)ULSCH_dci)->ndi      = ndi;
+		((DCI0_10MHz_TDD_1_6_t *)ULSCH_dci)->TPC      = tpc;
+		((DCI0_10MHz_TDD_1_6_t *)ULSCH_dci)->cshift   = cshift;
+		((DCI0_10MHz_TDD_1_6_t *)ULSCH_dci)->padding  = 0;
+		((DCI0_10MHz_TDD_1_6_t *)ULSCH_dci)->dai      = UE_template->DAI_ul[sched_subframe];
+		((DCI0_10MHz_TDD_1_6_t *)ULSCH_dci)->cqi_req  = cqi_req;
+		
+		add_ue_spec_dci(DCI_pdu,
+				ULSCH_dci,
+				rnti,
+				sizeof(DCI0_10MHz_TDD_1_6_t),
+				aggregation,
+				sizeof_DCI0_10MHz_TDD_1_6_t,
+				format0,
+				0);
+		break;
+		
+	      case 100:
+		ULSCH_dci = UE_template->ULSCH_DCI[harq_pid];
+		
+		((DCI0_20MHz_TDD_1_6_t *)ULSCH_dci)->type     = 0;
+		((DCI0_20MHz_TDD_1_6_t *)ULSCH_dci)->hopping  = 0;
+		((DCI0_20MHz_TDD_1_6_t *)ULSCH_dci)->rballoc  = rballoc;
+		((DCI0_20MHz_TDD_1_6_t *)ULSCH_dci)->mcs      = mcs;
+		((DCI0_20MHz_TDD_1_6_t *)ULSCH_dci)->ndi      = ndi;
+		((DCI0_20MHz_TDD_1_6_t *)ULSCH_dci)->TPC      = tpc;
+		((DCI0_20MHz_TDD_1_6_t *)ULSCH_dci)->cshift   = cshift;
+		((DCI0_20MHz_TDD_1_6_t *)ULSCH_dci)->padding  = 0;
+		((DCI0_20MHz_TDD_1_6_t *)ULSCH_dci)->dai      = UE_template->DAI_ul[sched_subframe];
+		((DCI0_20MHz_TDD_1_6_t *)ULSCH_dci)->cqi_req  = cqi_req;
+		
+		add_ue_spec_dci(DCI_pdu,
+				ULSCH_dci,
+				rnti,
+				sizeof(DCI0_20MHz_TDD_1_6_t),
+				aggregation,
+				sizeof_DCI0_20MHz_TDD_1_6_t,
+				format0,
+				0);
+		break;
+	      }
+	    } // TDD
+	    else { //FDD
+	      switch (frame_parms->N_RB_UL) {
+	      case 25:
+	      default:
+		
+		ULSCH_dci          = UE_template->ULSCH_DCI[harq_pid];
+		
+		((DCI0_5MHz_FDD_t *)ULSCH_dci)->type     = 0;
+		((DCI0_5MHz_FDD_t *)ULSCH_dci)->hopping  = 0;
+		((DCI0_5MHz_FDD_t *)ULSCH_dci)->rballoc  = rballoc;
+		((DCI0_5MHz_FDD_t *)ULSCH_dci)->mcs      = mcs;
+		((DCI0_5MHz_FDD_t *)ULSCH_dci)->ndi      = ndi;
+		((DCI0_5MHz_FDD_t *)ULSCH_dci)->TPC      = tpc;
+		((DCI0_5MHz_FDD_t *)ULSCH_dci)->cshift   = cshift;
+		((DCI0_5MHz_FDD_t *)ULSCH_dci)->padding  = 0;
+		((DCI0_5MHz_FDD_t *)ULSCH_dci)->cqi_req  = cqi_req;
+		
+		add_ue_spec_dci(DCI_pdu,
+				ULSCH_dci,
+				rnti,
+				sizeof(DCI0_5MHz_FDD_t),
+				aggregation,
+				sizeof_DCI0_5MHz_FDD_t,
+				format0,
+				0);
+		break;
+		
+	      case 6:
+		ULSCH_dci          = UE_template->ULSCH_DCI[harq_pid];
+		
+		((DCI0_1_5MHz_FDD_t *)ULSCH_dci)->type     = 0;
+		((DCI0_1_5MHz_FDD_t *)ULSCH_dci)->hopping  = 0;
+		((DCI0_1_5MHz_FDD_t *)ULSCH_dci)->rballoc  = rballoc;
+		((DCI0_1_5MHz_FDD_t *)ULSCH_dci)->mcs      = mcs;
+		((DCI0_1_5MHz_FDD_t *)ULSCH_dci)->ndi      = ndi;
+		((DCI0_1_5MHz_FDD_t *)ULSCH_dci)->TPC      = tpc;
+		((DCI0_1_5MHz_FDD_t *)ULSCH_dci)->cshift   = cshift;
+		((DCI0_1_5MHz_FDD_t *)ULSCH_dci)->padding  = 0;
+		((DCI0_1_5MHz_FDD_t *)ULSCH_dci)->cqi_req  = cqi_req;
+		
+		add_ue_spec_dci(DCI_pdu,
+				ULSCH_dci,
+				rnti,
+				sizeof(DCI0_1_5MHz_FDD_t),
+				aggregation,
+				sizeof_DCI0_1_5MHz_FDD_t,
+				format0,
+				0);
+		break;
+		
+	      case 50:
+		ULSCH_dci          = UE_template->ULSCH_DCI[harq_pid];
+		
+		((DCI0_10MHz_FDD_t *)ULSCH_dci)->type     = 0;
+		((DCI0_10MHz_FDD_t *)ULSCH_dci)->hopping  = 0;
+		((DCI0_10MHz_FDD_t *)ULSCH_dci)->rballoc  = rballoc;
+		((DCI0_10MHz_FDD_t *)ULSCH_dci)->mcs      = mcs;
+		((DCI0_10MHz_FDD_t *)ULSCH_dci)->ndi      = ndi;
+		((DCI0_10MHz_FDD_t *)ULSCH_dci)->TPC      = tpc;
+		((DCI0_10MHz_FDD_t *)ULSCH_dci)->padding  = 0;
+		((DCI0_10MHz_FDD_t *)ULSCH_dci)->cshift   = cshift;
+		((DCI0_10MHz_FDD_t *)ULSCH_dci)->cqi_req  = cqi_req;
+		
+		add_ue_spec_dci(DCI_pdu,
+				ULSCH_dci,
+				rnti,
+				sizeof(DCI0_10MHz_FDD_t),
+				aggregation,
+				sizeof_DCI0_10MHz_FDD_t,
+				format0,
+				0);
+		break;
+		
+	      case 100:
+		ULSCH_dci          = UE_template->ULSCH_DCI[harq_pid];
+		
+		((DCI0_20MHz_FDD_t *)ULSCH_dci)->type     = 0;
+		((DCI0_20MHz_FDD_t *)ULSCH_dci)->hopping  = 0;
+		((DCI0_20MHz_FDD_t *)ULSCH_dci)->rballoc  = rballoc;
+		((DCI0_20MHz_FDD_t *)ULSCH_dci)->mcs      = mcs;
+		((DCI0_20MHz_FDD_t *)ULSCH_dci)->ndi      = ndi;
+		((DCI0_20MHz_FDD_t *)ULSCH_dci)->TPC      = tpc;
+		((DCI0_20MHz_FDD_t *)ULSCH_dci)->padding  = 0;
+		((DCI0_20MHz_FDD_t *)ULSCH_dci)->cshift   = cshift;
+		((DCI0_20MHz_FDD_t *)ULSCH_dci)->cqi_req  = cqi_req;
+		
+		add_ue_spec_dci(DCI_pdu,
+				ULSCH_dci,
+				rnti,
+				sizeof(DCI0_20MHz_FDD_t),
+				aggregation,
+				sizeof_DCI0_20MHz_FDD_t,
+				format0,
+				0);
+		break;
+		
+	      }
+	    }
+
+
+	    add_ue_ulsch_info(module_idP,
+			      CC_id,
+			      UE_id,
+			      subframeP,
+			      S_UL_SCHEDULED);
+	    
+	    LOG_D(MAC,"[eNB %d] CC_id %d Frame %d, subframeP %d: Generated ULSCH DCI for next UE_id %d, format 0\n", module_idP,CC_id,frameP,subframeP,UE_id);
+#ifdef DEBUG
+	    dump_dci(frame_parms, &DCI_pdu->dci_alloc[DCI_pdu->Num_common_dci+DCI_pdu->Num_ue_spec_dci-1]);
+#endif
+	    
+          }
+	  else {
+            T(T_ENB_MAC_UE_UL_SCHEDULE_RETRANSMISSION, T_INT(module_idP), T_INT(CC_id), T_INT(rnti), T_INT(frameP),
+              T_INT(subframeP), T_INT(harq_pid), T_INT(mcs), T_INT(first_rb[CC_id]), T_INT(rb_table[rb_table_index]),
+              T_INT(round));
+
+            LOG_D(MAC,"[eNB %d][PUSCH %d/%x] CC_id %d Frame %d subframeP %d Scheduled (PHICH) UE %d (mcs %d, first rb %d, nb_rb %d, rb_table_index %d, TBS %d, harq_pid %d,round %d)\n",
+                  module_idP,harq_pid,rnti,CC_id,frameP,subframeP,UE_id,mcs,
+                  first_rb[CC_id],rb_table[rb_table_index],
+                  rb_table_index,TBS,harq_pid,round);
+	  }/* 
+	  else if (round > 0) { //we schedule a retransmission
+
+            ndi = UE_template->oldNDI_UL[harq_pid];
+
+            if ((round&3)==0) {
+              mcs = openair_daq_vars.target_ue_ul_mcs;
+            } else {
+              mcs = rvidx_tab[round&3] + 28; //not correct for round==4!
+
+            }
+
+            LOG_I(MAC,"[eNB %d][PUSCH %d/%x] CC_id %d Frame %d subframeP %d Scheduled UE retransmission (mcs %d, first rb %d, nb_rb %d, harq_pid %d, round %d)\n",
+                  module_idP,UE_id,rnti,CC_id,frameP,subframeP,mcs,
+                  first_rb[CC_id],UE_template->nb_rb_ul[harq_pid],
+		  harq_pid, round);
+
+            rballoc = mac_xface->computeRIV(frame_parms->N_RB_UL,
+                                            first_rb[CC_id],
+                                            UE_template->nb_rb_ul[harq_pid]);
+            first_rb[CC_id]+=UE_template->nb_rb_ul[harq_pid];  // increment for next UE allocation
+         
+	    UE_list->eNB_UE_stats[CC_id][UE_id].num_retransmission_rx+=1;
+	    UE_list->eNB_UE_stats[CC_id][UE_id].rbs_used_retx_rx=UE_template->nb_rb_ul[harq_pid];
+	    UE_list->eNB_UE_stats[CC_id][UE_id].total_rbs_used_rx+=UE_template->nb_rb_ul[harq_pid];
+	    UE_list->eNB_UE_stats[CC_id][UE_id].ulsch_mcs1=mcs;
+	    UE_list->eNB_UE_stats[CC_id][UE_id].ulsch_mcs2=mcs;
+	  }
+	   */
+
+        } // UE_is_to_be_scheduled
+      } // UE is in PUSCH
+    } // loop over UE_id
+  } // loop of CC_id
+}
+
diff --git a/openair2/LAYER2/MAC/proto.h b/openair2/LAYER2/MAC/proto.h
index bbd6d6a36d84d365e6a63bc8b2222303a3a9bf02..9f3af1b053c2bb1a24feee5306e33edc8bf813cd 100644
--- a/openair2/LAYER2/MAC/proto.h
+++ b/openair2/LAYER2/MAC/proto.h
@@ -644,6 +644,7 @@ void assign_max_mcs_min_rb(module_id_t module_idP, int frameP,
 void adjust_bsr_info(int buffer_occupancy, uint16_t TBS,
 		     UE_TEMPLATE * UE_template);
 int phy_stats_exist(module_id_t Mod_id, int rnti);
+void sort_UEs (module_id_t Mod_idP, int frameP, sub_frame_t subframeP);
 
 /*! \fn  UE_L2_state_t ue_scheduler(const module_id_t module_idP,const frame_t frameP, const sub_frame_t subframe, const lte_subframe_t direction,const uint8_t eNB_index)
    \brief UE scheduler where all the ue background tasks are done.  This function performs the following:  1) Trigger PDCP every 5ms 2) Call RRC for link status return to PHY3) Perform SR/BSR procedures for scheduling feedback 4) Perform PHR procedures.
diff --git a/openair2/LAYER2/PDCP_v10.1.0/pdcp.c b/openair2/LAYER2/PDCP_v10.1.0/pdcp.c
index b362e8887a08066b969d160d7d86222cbff06e2e..cdbb2a6e93600a9c59b516db440d983ddeb0b3a2 100644
--- a/openair2/LAYER2/PDCP_v10.1.0/pdcp.c
+++ b/openair2/LAYER2/PDCP_v10.1.0/pdcp.c
@@ -102,6 +102,8 @@ boolean_t pdcp_data_req(
 
   hash_key_t         key             = HASHTABLE_NOT_A_KEY_VALUE;
   hashtable_rc_t     h_rc;
+  uint8_t            rb_offset= (srb_flagP == 0) ? DTCH -1 : 0;
+  uint16_t           pdcp_uid=0;
   VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_PDCP_DATA_REQ,VCD_FUNCTION_IN);
   CHECK_CTXT_ARGS(ctxt_pP);
 
@@ -147,7 +149,7 @@ boolean_t pdcp_data_req(
     ctxt_pP->configured=TRUE;
   }
     
-  if (ctxt_pP->enb_flag == ENB_FLAG_NO) {
+  if (ctxt_pP->enb_flag == ENB_FLAG_YES) {
     start_meas(&eNB_pdcp_stats[ctxt_pP->module_id].data_req);
   } else {
     start_meas(&UE_pdcp_stats[ctxt_pP->module_id].data_req);
@@ -218,7 +220,7 @@ boolean_t pdcp_data_req(
           LOG_E(PDCP, PROTOCOL_PDCP_CTXT_FMT" Cannot fill PDU buffer with relevant header fields!\n",
                 PROTOCOL_PDCP_CTXT_ARGS(ctxt_pP,pdcp_p));
 
-          if (ctxt_pP->enb_flag == ENB_FLAG_NO) {
+          if (ctxt_pP->enb_flag == ENB_FLAG_YES) {
             stop_meas(&eNB_pdcp_stats[ctxt_pP->module_id].data_req);
           } else {
             stop_meas(&UE_pdcp_stats[ctxt_pP->module_id].data_req);
@@ -236,8 +238,9 @@ boolean_t pdcp_data_req(
         if (pdcp_serialize_user_plane_data_pdu_with_long_sn_buffer((unsigned char*)pdcp_pdu_p->data, &pdu_header) == FALSE) {
           LOG_E(PDCP, PROTOCOL_PDCP_CTXT_FMT" Cannot fill PDU buffer with relevant header fields!\n",
                 PROTOCOL_PDCP_CTXT_ARGS(ctxt_pP,pdcp_p));
+         
+          if (ctxt_pP->enb_flag == ENB_FLAG_YES) {
 
-          if (ctxt_pP->enb_flag == ENB_FLAG_NO) {
             stop_meas(&eNB_pdcp_stats[ctxt_pP->module_id].data_req);
           } else {
             stop_meas(&UE_pdcp_stats[ctxt_pP->module_id].data_req);
@@ -259,7 +262,7 @@ boolean_t pdcp_data_req(
 
         free_mem_block(pdcp_pdu_p, __func__);
 
-        if (ctxt_pP->enb_flag == ENB_FLAG_NO) {
+        if (ctxt_pP->enb_flag == ENB_FLAG_YES) {
           stop_meas(&eNB_pdcp_stats[ctxt_pP->module_id].data_req);
         } else {
           stop_meas(&UE_pdcp_stats[ctxt_pP->module_id].data_req);
@@ -287,7 +290,7 @@ boolean_t pdcp_data_req(
           (((pdcp_p->cipheringAlgorithm) != 0) ||
            ((pdcp_p->integrityProtAlgorithm) != 0))) {
 
-        if (ctxt_pP->enb_flag == ENB_FLAG_NO) {
+        if (ctxt_pP->enb_flag == ENB_FLAG_YES) {
           start_meas(&eNB_pdcp_stats[ctxt_pP->module_id].apply_security);
         } else {
           start_meas(&UE_pdcp_stats[ctxt_pP->module_id].apply_security);
@@ -382,7 +385,7 @@ boolean_t pdcp_data_req(
     break;
   }
 
-  if (ctxt_pP->enb_flag == ENB_FLAG_NO) {
+  if (ctxt_pP->enb_flag == ENB_FLAG_YES) {
     stop_meas(&eNB_pdcp_stats[ctxt_pP->module_id].data_req);
   } else {
     stop_meas(&UE_pdcp_stats[ctxt_pP->module_id].data_req);
@@ -392,16 +395,23 @@ boolean_t pdcp_data_req(
    * Control arrives here only if rlc_data_req() returns RLC_OP_STATUS_OK
    * so we return TRUE afterwards
    */
-  /*
-   if (rb_id>=DTCH) {
-    if (ctxt_pP->enb_flag == 1) {
-      Pdcp_stats_tx[module_id][(rb_id & RAB_OFFSET2 )>> RAB_SHIFT2][(rb_id & RAB_OFFSET)-DTCH]++;
-      Pdcp_stats_tx_bytes[module_id][(rb_id & RAB_OFFSET2 )>> RAB_SHIFT2][(rb_id & RAB_OFFSET)-DTCH] += sdu_buffer_size;
-    } else {
-      Pdcp_stats_tx[module_id][(rb_id & RAB_OFFSET2 )>> RAB_SHIFT2][(rb_id & RAB_OFFSET)-DTCH]++;
-      Pdcp_stats_tx_bytes[module_id][(rb_id & RAB_OFFSET2 )>> RAB_SHIFT2][(rb_id & RAB_OFFSET)-DTCH] += sdu_buffer_size;
-    }
-    }*/
+  
+  for (pdcp_uid=0; pdcp_uid< NUMBER_OF_UE_MAX;pdcp_uid++){
+    if (pdcp_enb[ctxt_pP->module_id].rnti[pdcp_uid] == ctxt_pP->rnti ) 
+      break;
+  }
+
+  //LOG_I(PDCP,"ueid %d lcid %d tx seq num %d\n", pdcp_uid, rb_idP+rb_offset, current_sn);
+  Pdcp_stats_tx[ctxt_pP->module_id][pdcp_uid][rb_idP+rb_offset]++;
+  Pdcp_stats_tx_tmp_w[ctxt_pP->module_id][pdcp_uid][rb_idP+rb_offset]++;
+  Pdcp_stats_tx_bytes[ctxt_pP->module_id][pdcp_uid][rb_idP+rb_offset]+=sdu_buffer_sizeP;
+  Pdcp_stats_tx_bytes_tmp_w[ctxt_pP->module_id][pdcp_uid][rb_idP+rb_offset]+=sdu_buffer_sizeP;
+  Pdcp_stats_tx_sn[ctxt_pP->module_id][pdcp_uid][rb_idP+rb_offset]=current_sn;
+
+  Pdcp_stats_tx_aiat[ctxt_pP->module_id][pdcp_uid][rb_idP+rb_offset]+= (pdcp_enb[ctxt_pP->module_id].sfn - Pdcp_stats_tx_iat[ctxt_pP->module_id][pdcp_uid][rb_idP+rb_offset]);
+  Pdcp_stats_tx_aiat_tmp_w[ctxt_pP->module_id][pdcp_uid][rb_idP+rb_offset]+= (pdcp_enb[ctxt_pP->module_id].sfn - Pdcp_stats_tx_iat[ctxt_pP->module_id][pdcp_uid][rb_idP+rb_offset]); 
+  Pdcp_stats_tx_iat[ctxt_pP->module_id][pdcp_uid][rb_idP+rb_offset]=pdcp_enb[ctxt_pP->module_id].sfn;
+    
   VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_PDCP_DATA_REQ,VCD_FUNCTION_OUT);
   return ret;
 
@@ -431,6 +441,9 @@ pdcp_data_ind(
   boolean_t    packet_forwarded = FALSE;
   hash_key_t      key             = HASHTABLE_NOT_A_KEY_VALUE;
   hashtable_rc_t  h_rc;
+  uint8_t      rb_offset= (srb_flagP == 0) ? DTCH -1 :0;
+  uint16_t     pdcp_uid=0;      
+  uint8_t      oo_flag=0;
 #if defined(LINK_ENB_PDCP_TO_GTPV1U)
   MessageDef  *message_p        = NULL;
   uint8_t     *gtpu_buffer_p    = NULL;
@@ -585,6 +598,7 @@ pdcp_data_ind(
       else
       LOG_D(PDCP, "Passing piggybacked SDU to RRC ...\n");*/
     } else {
+      oo_flag=1;
       LOG_W(PDCP,
             PROTOCOL_PDCP_CTXT_FMT"Incoming PDU has an unexpected sequence number (%d), RX window synchronisation have probably been lost!\n",
             PROTOCOL_PDCP_CTXT_ARGS(ctxt_pP, pdcp_p),
@@ -783,9 +797,9 @@ pdcp_data_ind(
     GTPV1U_ENB_TUNNEL_DATA_REQ(message_p).rnti         = ctxt_pP->rnti;
     GTPV1U_ENB_TUNNEL_DATA_REQ(message_p).rab_id       = rb_id + 4;
     itti_send_msg_to_task(TASK_GTPV1_U, INSTANCE_DEFAULT, message_p);
-    packet_forwarded = TRUE;
+    packet_forwarded = TRUE;    
   }
-
+  
 #else
   packet_forwarded = FALSE;
 #endif
@@ -837,28 +851,44 @@ pdcp_data_ind(
              sdu_buffer_sizeP - payload_offset);
       list_add_tail_eurecom (new_sdu_p, sdu_list_p);
 
-      /* Print octets of incoming data in hexadecimal form */
-      LOG_D(PDCP, "Following content has been received from RLC (%d,%d)(PDCP header has already been removed):\n",
-            sdu_buffer_sizeP  - payload_offset + (int)sizeof(pdcp_data_ind_header_t),
-            sdu_buffer_sizeP  - payload_offset);
-      //util_print_hex_octets(PDCP, &new_sdu_p->data[sizeof (pdcp_data_ind_header_t)], sdu_buffer_sizeP - payload_offset);
-      //util_flush_hex_octets(PDCP, &new_sdu_p->data[sizeof (pdcp_data_ind_header_t)], sdu_buffer_sizeP - payload_offset);
-
-      /*
-       * Update PDCP statistics
-       * XXX Following two actions are identical, is there a merge error?
-       */
-
-      /*if (ctxt_pP->enb_flag == 1) {
-          Pdcp_stats_rx[module_id][(rb_idP & RAB_OFFSET2) >> RAB_SHIFT2][(rb_idP & RAB_OFFSET) - DTCH]++;
-          Pdcp_stats_rx_bytes[module_id][(rb_idP & RAB_OFFSET2) >> RAB_SHIFT2][(rb_idP & RAB_OFFSET) - DTCH] += sdu_buffer_sizeP;
-        } else {
-          Pdcp_stats_rx[module_id][(rb_idP & RAB_OFFSET2) >> RAB_SHIFT2][(rb_idP & RAB_OFFSET) - DTCH]++;
-          Pdcp_stats_rx_bytes[module_id][(rb_idP & RAB_OFFSET2) >> RAB_SHIFT2][(rb_idP & RAB_OFFSET) - DTCH] += sdu_buffer_sizeP;
-        }*/
+      
+      
     }
   }
 
+  /* Print octets of incoming data in hexadecimal form */
+  LOG_D(PDCP, "Following content has been received from RLC (%d,%d)(PDCP header has already been removed):\n",
+	sdu_buffer_sizeP  - payload_offset + (int)sizeof(pdcp_data_ind_header_t),
+	sdu_buffer_sizeP  - payload_offset);
+  //util_print_hex_octets(PDCP, &new_sdu_p->data[sizeof (pdcp_data_ind_header_t)], sdu_buffer_sizeP - payload_offset);
+  //util_flush_hex_octets(PDCP, &new_sdu_p->data[sizeof (pdcp_data_ind_header_t)], sdu_buffer_sizeP - payload_offset);
+  
+  /*
+     * Update PDCP statistics
+   * XXX Following two actions are identical, is there a merge error?
+   */
+  
+  for (pdcp_uid=0; pdcp_uid< NUMBER_OF_UE_MAX;pdcp_uid++){
+    if (pdcp_enb[ctxt_pP->module_id].rnti[pdcp_uid] == ctxt_pP->rnti ){
+      break;
+    }
+  }	
+  
+  Pdcp_stats_rx[ctxt_pP->module_id][pdcp_uid][rb_idP+rb_offset]++;
+  Pdcp_stats_rx_tmp_w[ctxt_pP->module_id][pdcp_uid][rb_idP+rb_offset]++;
+  Pdcp_stats_rx_bytes[ctxt_pP->module_id][pdcp_uid][rb_idP+rb_offset]+=(sdu_buffer_sizeP  - payload_offset);
+  Pdcp_stats_rx_bytes_tmp_w[ctxt_pP->module_id][pdcp_uid][rb_idP+rb_offset]+=(sdu_buffer_sizeP  - payload_offset);
+  
+  Pdcp_stats_rx_sn[ctxt_pP->module_id][pdcp_uid][rb_idP+rb_offset]=sequence_number;
+  
+  if (oo_flag == 1 )
+    Pdcp_stats_rx_outoforder[ctxt_pP->module_id][pdcp_uid][rb_idP+rb_offset]++;
+  
+  Pdcp_stats_rx_aiat[ctxt_pP->module_id][pdcp_uid][rb_idP+rb_offset]+= (pdcp_enb[ctxt_pP->module_id].sfn - Pdcp_stats_rx_iat[ctxt_pP->module_id][pdcp_uid][rb_idP+rb_offset]);
+  Pdcp_stats_rx_aiat_tmp_w[ctxt_pP->module_id][pdcp_uid][rb_idP+rb_offset]+=(pdcp_enb[ctxt_pP->module_id].sfn - Pdcp_stats_rx_iat[ctxt_pP->module_id][pdcp_uid][rb_idP+rb_offset]);
+  Pdcp_stats_rx_iat[ctxt_pP->module_id][pdcp_uid][rb_idP+rb_offset]=pdcp_enb[ctxt_pP->module_id].sfn;
+
+  
 #if defined(STOP_ON_IP_TRAFFIC_OVERLOAD)
   else {
     AssertFatal(0, PROTOCOL_PDCP_CTXT_FMT" PDCP_DATA_IND SDU DROPPED, OUT OF MEMORY \n",
@@ -879,6 +909,53 @@ pdcp_data_ind(
   return TRUE;
 }
 
+void pdcp_update_stats(const protocol_ctxt_t* const  ctxt_pP){
+
+  uint8_t            pdcp_uid = 0;
+  uint8_t            rb_id     = 0;
+  
+ // these stats are measured for both eNB and UE on per seond basis 
+  for (rb_id =0; rb_id < NB_RB_MAX; rb_id ++){
+    for (pdcp_uid=0; pdcp_uid< NUMBER_OF_UE_MAX;pdcp_uid++){
+      //printf("frame %d and subframe %d \n", pdcp_enb[ctxt_pP->module_id].frame, pdcp_enb[ctxt_pP->module_id].subframe);
+      // tx stats
+      if (pdcp_enb[ctxt_pP->module_id].sfn % Pdcp_stats_tx_window_ms[ctxt_pP->module_id][pdcp_uid] == 0){
+	// unit: bit/s
+	Pdcp_stats_tx_throughput_w[ctxt_pP->module_id][pdcp_uid][rb_id]=Pdcp_stats_tx_bytes_tmp_w[ctxt_pP->module_id][pdcp_uid][rb_id]*8;
+	Pdcp_stats_tx_w[ctxt_pP->module_id][pdcp_uid][rb_id]= Pdcp_stats_tx_tmp_w[ctxt_pP->module_id][pdcp_uid][rb_id];
+	Pdcp_stats_tx_bytes_w[ctxt_pP->module_id][pdcp_uid][rb_id]= Pdcp_stats_tx_bytes_tmp_w[ctxt_pP->module_id][pdcp_uid][rb_id];
+	if (Pdcp_stats_tx_tmp_w[ctxt_pP->module_id][pdcp_uid][rb_id] > 0){
+	  Pdcp_stats_tx_aiat_w[ctxt_pP->module_id][pdcp_uid][rb_id]=(Pdcp_stats_tx_aiat_tmp_w[ctxt_pP->module_id][pdcp_uid][rb_id]/Pdcp_stats_tx_tmp_w[ctxt_pP->module_id][pdcp_uid][rb_id]);
+	}else {
+	  Pdcp_stats_tx_aiat_w[ctxt_pP->module_id][pdcp_uid][rb_id]=0;
+	}
+	// reset the tmp vars 
+	Pdcp_stats_tx_tmp_w[ctxt_pP->module_id][pdcp_uid][rb_id]=0;
+	Pdcp_stats_tx_bytes_tmp_w[ctxt_pP->module_id][pdcp_uid][rb_id]=0;
+	Pdcp_stats_tx_aiat_tmp_w[ctxt_pP->module_id][pdcp_uid][rb_id]=0;
+	
+      }
+      if (pdcp_enb[ctxt_pP->module_id].sfn % Pdcp_stats_rx_window_ms[ctxt_pP->module_id][pdcp_uid] == 0){
+	// rx stats
+	Pdcp_stats_rx_goodput_w[ctxt_pP->module_id][pdcp_uid][rb_id]=Pdcp_stats_rx_bytes_tmp_w[ctxt_pP->module_id][pdcp_uid][rb_id]*8;
+	Pdcp_stats_rx_w[ctxt_pP->module_id][pdcp_uid][rb_id]= 	Pdcp_stats_rx_tmp_w[ctxt_pP->module_id][pdcp_uid][rb_id];
+	Pdcp_stats_rx_bytes_w[ctxt_pP->module_id][pdcp_uid][rb_id]= Pdcp_stats_rx_bytes_tmp_w[ctxt_pP->module_id][pdcp_uid][rb_id];
+	
+	if(Pdcp_stats_rx_tmp_w[ctxt_pP->module_id][pdcp_uid][rb_id] > 0){
+	  Pdcp_stats_rx_aiat_w[ctxt_pP->module_id][pdcp_uid][rb_id]= (Pdcp_stats_rx_aiat_tmp_w[ctxt_pP->module_id][pdcp_uid][rb_id]/Pdcp_stats_rx_tmp_w[ctxt_pP->module_id][pdcp_uid][rb_id]);
+	} else {
+	  Pdcp_stats_rx_aiat_w[ctxt_pP->module_id][pdcp_uid][rb_id]=0;
+	}
+	
+	// reset the tmp vars 
+	Pdcp_stats_rx_tmp_w[ctxt_pP->module_id][pdcp_uid][rb_id]=0;
+	Pdcp_stats_rx_bytes_tmp_w[ctxt_pP->module_id][pdcp_uid][rb_id]=0;
+	Pdcp_stats_rx_aiat_tmp_w[ctxt_pP->module_id][pdcp_uid][rb_id]=0;
+      } 
+    }
+    
+  }
+}
 //-----------------------------------------------------------------------------
 void
 pdcp_run (
@@ -886,6 +963,7 @@ pdcp_run (
 )
 //-----------------------------------------------------------------------------
 {
+  
 #if defined(ENABLE_ITTI)
   MessageDef   *msg_p;
   const char   *msg_name;
@@ -894,12 +972,18 @@ pdcp_run (
   protocol_ctxt_t  ctxt;
 #endif
 
+  
   if (ctxt_pP->enb_flag) {
     start_meas(&eNB_pdcp_stats[ctxt_pP->module_id].pdcp_run);
   } else {
     start_meas(&UE_pdcp_stats[ctxt_pP->module_id].pdcp_run);
   }
 
+  pdcp_enb[ctxt_pP->module_id].sfn++; // range: 0 to 18,446,744,073,709,551,615
+  pdcp_enb[ctxt_pP->module_id].frame=ctxt_pP->frame; // 1023 
+  pdcp_enb[ctxt_pP->module_id].subframe= ctxt_pP->subframe;
+  pdcp_update_stats(ctxt_pP);
+   
   VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_PDCP_RUN, VCD_FUNCTION_IN);
 
 #if defined(ENABLE_ITTI)
@@ -1022,6 +1106,28 @@ pdcp_run (
   VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_PDCP_RUN, VCD_FUNCTION_OUT);
 }
 
+void pdcp_add_UE(const protocol_ctxt_t* const  ctxt_pP){
+  int i, ue_flag=1; //, ret=-1; to be decied later
+  for (i=0; i < NUMBER_OF_UE_MAX; i++){
+    if (pdcp_enb[ctxt_pP->module_id].rnti[i] == ctxt_pP->rnti) {
+      ue_flag=-1;
+      break;
+    }
+  }
+  if (ue_flag == 1 ){
+    for (i=0; i < NUMBER_OF_UE_MAX ; i++){
+      if (pdcp_enb[ctxt_pP->module_id].rnti[i] == 0 ){
+	pdcp_enb[ctxt_pP->module_id].rnti[i]=ctxt_pP->rnti;
+	pdcp_enb[ctxt_pP->module_id].uid[i]=i;
+	pdcp_enb[ctxt_pP->module_id].num_ues++;
+	printf("add new uid is %d %x\n\n", i, ctxt_pP->rnti);
+	// ret=1;
+	break;
+      }
+    }
+  }
+  //return ret;
+}
 
 //-----------------------------------------------------------------------------
 boolean_t
@@ -1034,8 +1140,8 @@ pdcp_remove_UE(
   DRB_Identity_t  drb_id         = 0;
   hash_key_t      key            = HASHTABLE_NOT_A_KEY_VALUE;
   hashtable_rc_t  h_rc;
-
-  // check and remove SRBs first
+  int i; 
+   // check and remove SRBs first
 
   for (srb_id=0; srb_id<2; srb_id++) {
     key = PDCP_COLL_KEY_VALUE(ctxt_pP->module_id, ctxt_pP->rnti, ctxt_pP->enb_flag, srb_id, SRB_FLAG_YES);
@@ -1050,6 +1156,19 @@ pdcp_remove_UE(
 
   (void)h_rc; /* remove gcc warning "set but not used" */
 
+  // remove ue for pdcp enb inst
+   for (i=0; i < NUMBER_OF_UE_MAX; i++) {
+    if (pdcp_enb[ctxt_pP->module_id].rnti[i] == ctxt_pP->rnti ) {
+      LOG_I(PDCP, "remove uid is %d/%d %x\n", i,
+	    pdcp_enb[ctxt_pP->module_id].uid[i],
+	    pdcp_enb[ctxt_pP->module_id].rnti[i]);
+      pdcp_enb[ctxt_pP->module_id].uid[i]=0;
+      pdcp_enb[ctxt_pP->module_id].rnti[i]=0;
+      pdcp_enb[ctxt_pP->module_id].num_ues--;
+      break;
+    }
+  }
+   
   return 1;
 }
 
@@ -1134,7 +1253,7 @@ rrc_pdcp_config_asn1_req (
           return TRUE;
 
       } else {
-          LOG_D(PDCP, PROTOCOL_PDCP_CTXT_FMT" CONFIG_ACTION_ADD key 0x%"PRIx64"\n",
+	  LOG_D(PDCP, PROTOCOL_PDCP_CTXT_FMT" CONFIG_ACTION_ADD key 0x%"PRIx64"\n",
                 PROTOCOL_PDCP_CTXT_ARGS(ctxt_pP, pdcp_p),
                 key);
         }
@@ -1444,7 +1563,6 @@ rrc_pdcp_config_asn1_req (
   return 0;
 }
 
-
 //-----------------------------------------------------------------------------
 boolean_t
 pdcp_config_req_asn1 (
@@ -1465,12 +1583,14 @@ pdcp_config_req_asn1 (
   uint8_t         *const        kUPenc_pP)
 //-----------------------------------------------------------------------------
 {
-
+  
   switch (actionP) {
   case CONFIG_ACTION_ADD:
     DevAssert(pdcp_pP != NULL);
     if (ctxt_pP->enb_flag == ENB_FLAG_YES) {
       pdcp_pP->is_ue = FALSE;
+      pdcp_add_UE(ctxt_pP);
+      
       //pdcp_eNB_UE_instance_to_rnti[ctxtP->module_id] = ctxt_pP->rnti;
       pdcp_eNB_UE_instance_to_rnti[pdcp_eNB_UE_instance_to_rnti_index] = ctxt_pP->rnti;
       //pdcp_eNB_UE_instance_to_rnti_index = (pdcp_eNB_UE_instance_to_rnti_index + 1) % NUMBER_OF_UE_MAX;
@@ -1570,6 +1690,10 @@ pdcp_config_req_asn1 (
           lc_idP,
           rb_idP);
 
+   if (ctxt_pP->enb_flag == ENB_FLAG_YES) {
+     // pdcp_remove_UE(ctxt_pP);
+   }
+
     /* Security keys */
     if (pdcp_pP->kUPenc != NULL) {
       free(pdcp_pP->kUPenc);
@@ -1821,13 +1945,14 @@ rrc_pdcp_config_req (
 
 
 //-----------------------------------------------------------------------------
-// TODO PDCP module initialization code might be removed
+ 
 int
 pdcp_module_init (
   void
 )
 //-----------------------------------------------------------------------------
 {
+ 
 #ifdef PDCP_USE_RT_FIFO
   int ret;
 
@@ -1903,6 +2028,7 @@ void pdcp_layer_init(void)
 {
 
   module_id_t       instance;
+  int i,j;
 #if defined(Rel10) || defined(Rel14)
   mbms_session_id_t session_id;
   mbms_service_id_t service_id;
@@ -1946,15 +2072,42 @@ void pdcp_layer_init(void)
   pdcp_output_header_bytes_to_write=0;
   pdcp_input_sdu_remaining_size_to_read=0;
 
+  memset(pdcp_enb, 0, sizeof(pdcp_enb_t));
+
+  
+  memset(Pdcp_stats_tx_window_ms, 0, sizeof(Pdcp_stats_tx_window_ms));
+  memset(Pdcp_stats_rx_window_ms, 0, sizeof(Pdcp_stats_rx_window_ms));
+  for (i =0; i< MAX_NUM_CCs ; i ++){
+    for (j=0; j< NUMBER_OF_UE_MAX;j++){
+      Pdcp_stats_tx_window_ms[i][j]=100;
+      Pdcp_stats_rx_window_ms[i][j]=100;
+    }
+  }
+  
   memset(Pdcp_stats_tx, 0, sizeof(Pdcp_stats_tx));
+  memset(Pdcp_stats_tx_w, 0, sizeof(Pdcp_stats_tx_w));
+  memset(Pdcp_stats_tx_tmp_w, 0, sizeof(Pdcp_stats_tx_tmp_w));
   memset(Pdcp_stats_tx_bytes, 0, sizeof(Pdcp_stats_tx_bytes));
-  memset(Pdcp_stats_tx_bytes_last, 0, sizeof(Pdcp_stats_tx_bytes_last));
-  memset(Pdcp_stats_tx_rate, 0, sizeof(Pdcp_stats_tx_rate));
+  memset(Pdcp_stats_tx_bytes_w, 0, sizeof(Pdcp_stats_tx_bytes_w));
+  memset(Pdcp_stats_tx_bytes_tmp_w, 0, sizeof(Pdcp_stats_tx_bytes_tmp_w));
+  memset(Pdcp_stats_tx_sn, 0, sizeof(Pdcp_stats_tx_sn));
+  memset(Pdcp_stats_tx_throughput_w, 0, sizeof(Pdcp_stats_tx_throughput_w));
+  memset(Pdcp_stats_tx_aiat, 0, sizeof(Pdcp_stats_tx_aiat));
+  memset(Pdcp_stats_tx_iat, 0, sizeof(Pdcp_stats_tx_iat));
+  
 
   memset(Pdcp_stats_rx, 0, sizeof(Pdcp_stats_rx));
+  memset(Pdcp_stats_rx_w, 0, sizeof(Pdcp_stats_rx_w));
+  memset(Pdcp_stats_rx_tmp_w, 0, sizeof(Pdcp_stats_rx_tmp_w));
   memset(Pdcp_stats_rx_bytes, 0, sizeof(Pdcp_stats_rx_bytes));
-  memset(Pdcp_stats_rx_bytes_last, 0, sizeof(Pdcp_stats_rx_bytes_last));
-  memset(Pdcp_stats_rx_rate, 0, sizeof(Pdcp_stats_rx_rate));
+  memset(Pdcp_stats_rx_bytes_w, 0, sizeof(Pdcp_stats_rx_bytes_w));
+  memset(Pdcp_stats_rx_bytes_tmp_w, 0, sizeof(Pdcp_stats_rx_bytes_tmp_w));
+  memset(Pdcp_stats_rx_sn, 0, sizeof(Pdcp_stats_rx_sn));
+  memset(Pdcp_stats_rx_goodput_w, 0, sizeof(Pdcp_stats_rx_goodput_w));
+  memset(Pdcp_stats_rx_aiat, 0, sizeof(Pdcp_stats_rx_aiat));
+  memset(Pdcp_stats_rx_iat, 0, sizeof(Pdcp_stats_rx_iat));
+  memset(Pdcp_stats_rx_outoforder, 0, sizeof(Pdcp_stats_rx_outoforder));
+    
 }
 
 //-----------------------------------------------------------------------------
diff --git a/openair2/LAYER2/PDCP_v10.1.0/pdcp.h b/openair2/LAYER2/PDCP_v10.1.0/pdcp.h
index 30a45acc72fc9d7183b156a4bd85f5e8112bf251..7c8f2dd033571f3faac8d484ea99be494b020a81 100644
--- a/openair2/LAYER2/PDCP_v10.1.0/pdcp.h
+++ b/openair2/LAYER2/PDCP_v10.1.0/pdcp.h
@@ -94,15 +94,54 @@ extern int             pdcp_instance_cnt;
 int init_pdcp_thread(void);
 void cleanup_pdcp_thread(void);
 
-
-public_pdcp(unsigned int Pdcp_stats_tx[NB_MODULES_MAX][NB_CNX_CH][NB_RAB_MAX]);
-public_pdcp(unsigned int Pdcp_stats_tx_bytes[NB_MODULES_MAX][NB_CNX_CH][NB_RAB_MAX]);
-public_pdcp(unsigned int Pdcp_stats_tx_bytes_last[NB_MODULES_MAX][NB_CNX_CH][NB_RAB_MAX]);
-public_pdcp(unsigned int Pdcp_stats_tx_rate[NB_MODULES_MAX][NB_CNX_CH][NB_RAB_MAX]);
-public_pdcp(unsigned int Pdcp_stats_rx[NB_MODULES_MAX][NB_CNX_CH][NB_RAB_MAX]);
-public_pdcp(unsigned int Pdcp_stats_rx_bytes[NB_MODULES_MAX][NB_CNX_CH][NB_RAB_MAX]);
-public_pdcp(unsigned int Pdcp_stats_rx_bytes_last[NB_MODULES_MAX][NB_CNX_CH][NB_RAB_MAX]);
-public_pdcp(unsigned int Pdcp_stats_rx_rate[NB_MODULES_MAX][NB_CNX_CH][NB_RAB_MAX]);
+public_pdcp(uint32_t Pdcp_stats_tx_window_ms[MAX_NUM_CCs][NUMBER_OF_UE_MAX]);
+public_pdcp(uint32_t Pdcp_stats_tx_bytes[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+public_pdcp(uint32_t Pdcp_stats_tx_bytes_w[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+public_pdcp(uint32_t Pdcp_stats_tx_bytes_tmp_w[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+public_pdcp(uint32_t Pdcp_stats_tx[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+public_pdcp(uint32_t Pdcp_stats_tx_w[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+public_pdcp(uint32_t Pdcp_stats_tx_tmp_w[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+public_pdcp(uint32_t Pdcp_stats_tx_sn[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+public_pdcp(uint32_t Pdcp_stats_tx_throughput_w[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+public_pdcp(uint32_t Pdcp_stats_tx_aiat[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+public_pdcp(uint32_t Pdcp_stats_tx_aiat_w[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+public_pdcp(uint32_t Pdcp_stats_tx_aiat_tmp_w[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+public_pdcp(uint32_t Pdcp_stats_tx_iat[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+
+public_pdcp(uint32_t Pdcp_stats_rx_window_ms[MAX_NUM_CCs][NUMBER_OF_UE_MAX]);
+public_pdcp(uint32_t Pdcp_stats_rx[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+public_pdcp(uint32_t Pdcp_stats_rx_w[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+public_pdcp(uint32_t Pdcp_stats_rx_tmp_w[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+public_pdcp(uint32_t Pdcp_stats_rx_bytes[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+public_pdcp(uint32_t Pdcp_stats_rx_bytes_w[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+public_pdcp(uint32_t Pdcp_stats_rx_bytes_tmp_w[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+public_pdcp(uint32_t Pdcp_stats_rx_sn[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+public_pdcp(uint32_t Pdcp_stats_rx_goodput_w[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+public_pdcp(uint32_t Pdcp_stats_rx_aiat[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+public_pdcp(uint32_t Pdcp_stats_rx_aiat_w[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+public_pdcp(uint32_t Pdcp_stats_rx_aiat_tmp_w[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+public_pdcp(uint32_t Pdcp_stats_rx_iat[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+public_pdcp(uint32_t Pdcp_stats_rx_outoforder[MAX_NUM_CCs][NUMBER_OF_UE_MAX][NB_RB_MAX]);
+
+public_pdcp(void pdcp_update_perioidical_stats(const protocol_ctxt_t* const  ctxt_pP));
+
+
+/*Packet Probing for agent PDCP*/
+//public_pdcp(uint64_t *pdcp_packet_counter);
+//public_pdcp(uint64_t *pdcp_size_packet);
+typedef struct pdcp_enb_s {
+  // used for eNB stats generation
+  uint16_t uid[NUMBER_OF_UE_MAX];
+  rnti_t rnti[NUMBER_OF_UE_MAX];
+  uint16_t num_ues;
+  
+  uint64_t sfn;
+  frame_t  frame;
+  sub_frame_t subframe;
+  
+} pdcp_enb_t; 
+
+public_pdcp(pdcp_enb_t pdcp_enb[MAX_NUM_CCs]);
 
 typedef struct pdcp_stats_s {
   time_stats_t pdcp_run;
@@ -125,7 +164,7 @@ typedef struct pdcp_s {
   boolean_t is_ue;
   boolean_t is_srb;
 
-  /* Configured security algorithms */
+   /* Configured security algorithms */
   uint8_t cipheringAlgorithm;
   uint8_t integrityProtAlgorithm;
 
@@ -327,9 +366,15 @@ public_pdcp(boolean_t pdcp_config_req_asn1 (
               uint8_t         *const kRRCint,
               uint8_t         *const kUPenc));
 
-
+/*! \fn void pdcp_add_UE(const protocol_ctxt_t* const  ctxt_pP)
+* \brief  Function (for RRC) to add a new UE in PDCP module
+* \param[in]  ctxt_pP           Running context.
+* \return     A status about the processing, OK or error code.
+*/
+public_pdcp(void pdcp_add_UE(const protocol_ctxt_t* const  ctxt_pP));
+  
 /*! \fn boolean_t pdcp_remove_UE(const protocol_ctxt_t* const  ctxt_pP)
-* \brief  Function for RRC to configure a Radio Bearer clear all PDCP resources for a particular UE
+* \brief  Function for RRC to remove UE from PDCP module hashtable 
 * \param[in]  ctxt_pP           Running context.
 * \return     A status about the processing, OK or error code.
 */
diff --git a/openair2/RRC/LITE/L2_interface.c b/openair2/RRC/LITE/L2_interface.c
index 504bf8ee9b9dd9f86852259927d331a59336ce52..0f667e493d5c009ba75e6fc1dcabd6c4879bf479 100644
--- a/openair2/RRC/LITE/L2_interface.c
+++ b/openair2/RRC/LITE/L2_interface.c
@@ -53,6 +53,10 @@ extern UE_MAC_INST *UE_mac_inst;
 # include "intertask_interface.h"
 #endif
 
+#if defined(FLEXRAN_AGENT_SB_IF)
+#include "flexran_agent_extern.h"
+#endif
+
 //#define RRC_DATA_REQ_DEBUG
 //#define DEBUG_RRC 1
 
@@ -635,10 +639,10 @@ rrc_data_ind(
   rb_id_t    DCCH_index = Srb_id;
 
   if (ctxt_pP->enb_flag == ENB_FLAG_NO) {
-    LOG_N(RRC, "[UE %x] Frame %d: received a DCCH %d message on SRB %d with Size %d from eNB %d\n",
+    LOG_D(RRC, "[UE %x] Frame %d: received a DCCH %d message on SRB %d with Size %d from eNB %d\n",
           ctxt_pP->module_id, ctxt_pP->frame, DCCH_index,Srb_id,sdu_sizeP,  ctxt_pP->eNB_index);
   } else {
-    LOG_N(RRC, "[eNB %d] Frame %d: received a DCCH %d message on SRB %d with Size %d from UE %x\n",
+    LOG_D(RRC, "[eNB %d] Frame %d: received a DCCH %d message on SRB %d with Size %d from UE %x\n",
           ctxt_pP->module_id,
           ctxt_pP->frame,
           DCCH_index,
@@ -776,6 +780,13 @@ void mac_eNB_rrc_ul_failure(const module_id_t Mod_instP,
   else {
     LOG_W(RRC,"Frame %d, Subframe %d: UL failure: UE %x unknown \n",frameP,subframeP,rntiP);
   }
+#if defined(FLEXRAN_AGENT_SB_IF)
+  if (rrc_agent_registered[Mod_instP]) {
+    agent_rrc_xface[Mod_instP]->flexran_agent_notify_ue_state_change(Mod_instP,
+								     rntiP,
+								     PROTOCOL__FLEX_UE_STATE_CHANGE_TYPE__FLUESC_DEACTIVATED);
+  }
+#endif
   rrc_mac_remove_ue(Mod_instP,rntiP);
 }
 
diff --git a/openair2/RRC/LITE/defs.h b/openair2/RRC/LITE/defs.h
index 9d7f7fdf2d169d4104de8c5ff5662d51aa2bfc85..9a346f7fb79685fb6f2458376ba4a60bd0c69eee 100644
--- a/openair2/RRC/LITE/defs.h
+++ b/openair2/RRC/LITE/defs.h
@@ -394,7 +394,8 @@ typedef struct eNB_RRC_UE_s {
   SRB_INFO_TABLE_ENTRY               Srb2;
   MeasConfig_t*                      measConfig;
   HANDOVER_INFO*                     handover_info;
-
+  MeasResults_t*                     measResults;
+  
 #if defined(ENABLE_SECURITY)
   /* KeNB as derived from KASME received from EPC */
   uint8_t kenb[32];
diff --git a/openair2/RRC/LITE/extern.h b/openair2/RRC/LITE/extern.h
index 77dcaac5e69492b9895d87434850adb42c923aec..9254881f8f28b06eb116248161b90ea5edca057e 100644
--- a/openair2/RRC/LITE/extern.h
+++ b/openair2/RRC/LITE/extern.h
@@ -74,8 +74,8 @@ extern uint16_t N310[8];
 extern uint16_t N311[8];
 extern uint32_t T304[8];
 extern uint32_t timeToTrigger_ms[16];
-extern float RSRP_meas_mapping[100];
-extern float RSRQ_meas_mapping[33];
+extern float RSRP_meas_mapping[98];
+extern float RSRQ_meas_mapping[35];
 
 #endif
 
diff --git a/openair2/RRC/LITE/proto.h b/openair2/RRC/LITE/proto.h
index b3d5beb2922f26316695a32c742a13eda1647908..ed537a4cb461a24baaa91c76c4828029b9a15ef4 100644
--- a/openair2/RRC/LITE/proto.h
+++ b/openair2/RRC/LITE/proto.h
@@ -33,6 +33,10 @@
 
 #include "RRC/LITE/defs.h"
 
+#if defined(FLEXRAN_AGENT_SB_IF)
+#include "flexran_agent_extern.h"
+#endif
+
 //main.c
 int rrc_init_global_param(void);
 int L3_xface_init(void);
@@ -254,6 +258,19 @@ rrc_eNB_generate_defaultRRCConnectionReconfiguration(
   const uint8_t                ho_state
 );
 
+
+#if defined(FLEXRAN_AGENT_SB_IF)
+
+void
+flexran_rrc_eNB_generate_defaultRRCConnectionReconfiguration(
+							     const protocol_ctxt_t* const ctxt_pP,
+							     rrc_eNB_ue_context_t* const ue_context_pP,
+							     const uint8_t ho_state,
+							     agent_reconf_rrc * trig_param
+							     );
+
+#endif
+
 void
 rrc_eNB_generate_dedeicatedRRCConnectionReconfiguration(
   const protocol_ctxt_t* const ctxt_pP,
@@ -408,7 +425,7 @@ rrc_eNB_generate_SecurityModeCommand(
 void
 rrc_eNB_process_MeasurementReport(
   const protocol_ctxt_t* const ctxt_pP,
-  rrc_eNB_ue_context_t*          const ue_context_pP,
+  rrc_eNB_ue_context_t*        ue_context_pP,
   const MeasResults_t*   const measResults2
 );
 
diff --git a/openair2/RRC/LITE/rrc_UE.c b/openair2/RRC/LITE/rrc_UE.c
index f0f495e8b77baffd9f39effdff25d383251e1d3b..201bd623df6301e3bb719df1bdde6d2edbecd419 100644
--- a/openair2/RRC/LITE/rrc_UE.c
+++ b/openair2/RRC/LITE/rrc_UE.c
@@ -4274,6 +4274,7 @@ void *rrc_ue_task( void *args_p )
 
     switch (ITTI_MSG_ID(msg_p)) {
     case TERMINATE_MESSAGE:
+      LOG_W(RRC, " *** Exiting RRC thread\n");
       itti_exit_task ();
       break;
 
diff --git a/openair2/RRC/LITE/rrc_eNB.c b/openair2/RRC/LITE/rrc_eNB.c
index c8b42d41b354160400dc7317cf58821ef4a95ef5..c946dcf8184aafd4dc1363de8289282a334b0e6e 100644
--- a/openair2/RRC/LITE/rrc_eNB.c
+++ b/openair2/RRC/LITE/rrc_eNB.c
@@ -95,9 +95,6 @@
 
 #include "SIMULATION/TOOLS/defs.h" // for taus
 
-#if defined(FLEXRAN_AGENT_SB_IF)
-#include "flexran_agent_extern.h"
-#endif
 //#define XER_PRINT
 
 extern RAN_CONTEXT_t RC;
@@ -808,6 +805,15 @@ rrc_eNB_free_UE(const module_id_t enb_mod_idP,const struct rrc_eNB_ue_context_s*
 #endif
 #endif
 
+#if defined(FLEXRAN_AGENT_SB_IF)
+    if (rrc_agent_registered[enb_mod_idP]) {
+      agent_rrc_xface[enb_mod_idP]->flexran_agent_notify_ue_state_change(enb_mod_idP,
+										rnti,
+										PROTOCOL__FLEX_UE_STATE_CHANGE_TYPE__FLUESC_DEACTIVATED);
+    }
+#endif
+
+
     rrc_mac_remove_ue(enb_mod_idP,rnti);
     rrc_rlc_remove_ue(&ctxt);
     pdcp_remove_UE(&ctxt);
@@ -1712,14 +1718,748 @@ rrc_eNB_generate_defaultRRCConnectionReconfiguration(const protocol_ctxt_t* cons
 	(*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm5.bits_unused=4;
       }
       else if (rrc_inst->configuration.ue_TransmissionMode[0]==AntennaInfoDedicated__transmissionMode_tm6) {
-	(*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction=     
-	  CALLOC(1,sizeof(AntennaInfoDedicated__codebookSubsetRestriction_PR));
-	(*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->present =
-	  AntennaInfoDedicated__codebookSubsetRestriction_PR_n2TxAntenna_tm6;
-	(*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm6.buf= MALLOC(1);
-	(*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm6.buf[0] = 0xf0;
-	(*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm6.size=1;
-	(*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm6.bits_unused=4;
+	(*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction=     
+	  CALLOC(1,sizeof(AntennaInfoDedicated__codebookSubsetRestriction_PR));
+	(*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->present =
+	  AntennaInfoDedicated__codebookSubsetRestriction_PR_n2TxAntenna_tm6;
+	(*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm6.buf= MALLOC(1);
+	(*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm6.buf[0] = 0xf0;
+	(*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm6.size=1;
+	(*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm6.bits_unused=4;
+      }
+    }
+    else {
+      LOG_E(RRC,"antenna_info not present in physical_config_dedicated. Not reconfiguring!\n");
+    }
+    if ((*physicalConfigDedicated)->cqi_ReportConfig) {
+      if ((rrc_inst->configuration.ue_TransmissionMode[0]==AntennaInfoDedicated__transmissionMode_tm4) ||
+	  (rrc_inst->configuration.ue_TransmissionMode[0]==AntennaInfoDedicated__transmissionMode_tm5) ||
+	  (rrc_inst->configuration.ue_TransmissionMode[0]==AntennaInfoDedicated__transmissionMode_tm6)) {
+	//feedback mode needs to be set as well
+	//TODO: I think this is taken into account in the PHY automatically based on the transmission mode variable
+	printf("setting cqi reporting mode to rm31\n");
+#if defined(Rel10) || defined(Rel14)
+	*((*physicalConfigDedicated)->cqi_ReportConfig->cqi_ReportModeAperiodic)=CQI_ReportModeAperiodic_rm31;
+#else
+	*((*physicalConfigDedicated)->cqi_ReportConfig->cqi_ReportModeAperiodic)=CQI_ReportConfig__cqi_ReportModeAperiodic_rm31; // HLC CQI, no PMI
+#endif
+      }
+    }
+    else {
+      LOG_E(RRC,"cqi_ReportConfig not present in physical_config_dedicated. Not reconfiguring!\n");
+    }
+  }
+  else {
+    LOG_E(RRC,"physical_config_dedicated not present in RRCConnectionReconfiguration. Not reconfiguring!\n");
+  }
+
+  // Measurement ID list
+  MeasId_list = CALLOC(1, sizeof(*MeasId_list));
+  memset((void *)MeasId_list, 0, sizeof(*MeasId_list));
+
+  MeasId0 = CALLOC(1, sizeof(*MeasId0));
+  MeasId0->measId = 1;
+  MeasId0->measObjectId = 1;
+  MeasId0->reportConfigId = 1;
+  ASN_SEQUENCE_ADD(&MeasId_list->list, MeasId0);
+
+  MeasId1 = CALLOC(1, sizeof(*MeasId1));
+  MeasId1->measId = 2;
+  MeasId1->measObjectId = 1;
+  MeasId1->reportConfigId = 2;
+  ASN_SEQUENCE_ADD(&MeasId_list->list, MeasId1);
+
+  MeasId2 = CALLOC(1, sizeof(*MeasId2));
+  MeasId2->measId = 3;
+  MeasId2->measObjectId = 1;
+  MeasId2->reportConfigId = 3;
+  ASN_SEQUENCE_ADD(&MeasId_list->list, MeasId2);
+
+  MeasId3 = CALLOC(1, sizeof(*MeasId3));
+  MeasId3->measId = 4;
+  MeasId3->measObjectId = 1;
+  MeasId3->reportConfigId = 4;
+  ASN_SEQUENCE_ADD(&MeasId_list->list, MeasId3);
+
+  MeasId4 = CALLOC(1, sizeof(*MeasId4));
+  MeasId4->measId = 5;
+  MeasId4->measObjectId = 1;
+  MeasId4->reportConfigId = 5;
+  ASN_SEQUENCE_ADD(&MeasId_list->list, MeasId4);
+
+  MeasId5 = CALLOC(1, sizeof(*MeasId5));
+  MeasId5->measId = 6;
+  MeasId5->measObjectId = 1;
+  MeasId5->reportConfigId = 6;
+  ASN_SEQUENCE_ADD(&MeasId_list->list, MeasId5);
+
+  //  rrcConnectionReconfiguration->criticalExtensions.choice.c1.choice.rrcConnectionReconfiguration_r8.measConfig->measIdToAddModList = MeasId_list;
+
+  // Add one EUTRA Measurement Object
+  MeasObj_list = CALLOC(1, sizeof(*MeasObj_list));
+  memset((void *)MeasObj_list, 0, sizeof(*MeasObj_list));
+
+  // Configure MeasObject
+
+  MeasObj = CALLOC(1, sizeof(*MeasObj));
+  memset((void *)MeasObj, 0, sizeof(*MeasObj));
+
+  MeasObj->measObjectId = 1;
+  MeasObj->measObject.present = MeasObjectToAddMod__measObject_PR_measObjectEUTRA;
+  MeasObj->measObject.choice.measObjectEUTRA.carrierFreq = 3350; //band 7, 2.68GHz
+  //MeasObj->measObject.choice.measObjectEUTRA.carrierFreq = 36090; //band 33, 1.909GHz
+  MeasObj->measObject.choice.measObjectEUTRA.allowedMeasBandwidth = AllowedMeasBandwidth_mbw25;
+  MeasObj->measObject.choice.measObjectEUTRA.presenceAntennaPort1 = 1;
+  MeasObj->measObject.choice.measObjectEUTRA.neighCellConfig.buf = CALLOC(1, sizeof(uint8_t));
+  MeasObj->measObject.choice.measObjectEUTRA.neighCellConfig.buf[0] = 0;
+  MeasObj->measObject.choice.measObjectEUTRA.neighCellConfig.size = 1;
+  MeasObj->measObject.choice.measObjectEUTRA.neighCellConfig.bits_unused = 6;
+  MeasObj->measObject.choice.measObjectEUTRA.offsetFreq = NULL;   // Default is 15 or 0dB
+
+  MeasObj->measObject.choice.measObjectEUTRA.cellsToAddModList =
+    (CellsToAddModList_t *) CALLOC(1, sizeof(*CellsToAddModList));
+
+  CellsToAddModList = MeasObj->measObject.choice.measObjectEUTRA.cellsToAddModList;
+
+  // Add adjacent cell lists (6 per eNB)
+  for (i = 0; i < 6; i++) {
+    CellToAdd = (CellsToAddMod_t *) CALLOC(1, sizeof(*CellToAdd));
+    CellToAdd->cellIndex = i + 1;
+    CellToAdd->physCellId = get_adjacent_cell_id(ctxt_pP->module_id, i);
+    CellToAdd->cellIndividualOffset = Q_OffsetRange_dB0;
+
+    ASN_SEQUENCE_ADD(&CellsToAddModList->list, CellToAdd);
+  }
+
+  ASN_SEQUENCE_ADD(&MeasObj_list->list, MeasObj);
+  //  rrcConnectionReconfiguration->criticalExtensions.choice.c1.choice.rrcConnectionReconfiguration_r8.measConfig->measObjectToAddModList = MeasObj_list;
+
+  // Report Configurations for periodical, A1-A5 events
+  ReportConfig_list = CALLOC(1, sizeof(*ReportConfig_list));
+
+  ReportConfig_per = CALLOC(1, sizeof(*ReportConfig_per));
+
+  ReportConfig_A1 = CALLOC(1, sizeof(*ReportConfig_A1));
+
+  ReportConfig_A2 = CALLOC(1, sizeof(*ReportConfig_A2));
+
+  ReportConfig_A3 = CALLOC(1, sizeof(*ReportConfig_A3));
+
+  ReportConfig_A4 = CALLOC(1, sizeof(*ReportConfig_A4));
+
+  ReportConfig_A5 = CALLOC(1, sizeof(*ReportConfig_A5));
+
+  ReportConfig_per->reportConfigId = 1;
+  ReportConfig_per->reportConfig.present = ReportConfigToAddMod__reportConfig_PR_reportConfigEUTRA;
+  ReportConfig_per->reportConfig.choice.reportConfigEUTRA.triggerType.present =
+    ReportConfigEUTRA__triggerType_PR_periodical;
+  ReportConfig_per->reportConfig.choice.reportConfigEUTRA.triggerType.choice.periodical.purpose =
+    ReportConfigEUTRA__triggerType__periodical__purpose_reportStrongestCells;
+  ReportConfig_per->reportConfig.choice.reportConfigEUTRA.triggerQuantity = ReportConfigEUTRA__triggerQuantity_rsrp;
+  ReportConfig_per->reportConfig.choice.reportConfigEUTRA.reportQuantity = ReportConfigEUTRA__reportQuantity_both;
+  ReportConfig_per->reportConfig.choice.reportConfigEUTRA.maxReportCells = 2;
+  ReportConfig_per->reportConfig.choice.reportConfigEUTRA.reportInterval = ReportInterval_ms120;
+  ReportConfig_per->reportConfig.choice.reportConfigEUTRA.reportAmount = ReportConfigEUTRA__reportAmount_infinity;
+
+  ASN_SEQUENCE_ADD(&ReportConfig_list->list, ReportConfig_per);
+
+  ReportConfig_A1->reportConfigId = 2;
+  ReportConfig_A1->reportConfig.present = ReportConfigToAddMod__reportConfig_PR_reportConfigEUTRA;
+  ReportConfig_A1->reportConfig.choice.reportConfigEUTRA.triggerType.present =
+    ReportConfigEUTRA__triggerType_PR_event;
+  ReportConfig_A1->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.present =
+    ReportConfigEUTRA__triggerType__event__eventId_PR_eventA1;
+  ReportConfig_A1->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.choice.eventA1.
+  a1_Threshold.present = ThresholdEUTRA_PR_threshold_RSRP;
+  ReportConfig_A1->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.choice.eventA1.
+  a1_Threshold.choice.threshold_RSRP = 10;
+
+  ReportConfig_A1->reportConfig.choice.reportConfigEUTRA.triggerQuantity = ReportConfigEUTRA__triggerQuantity_rsrp;
+  ReportConfig_A1->reportConfig.choice.reportConfigEUTRA.reportQuantity = ReportConfigEUTRA__reportQuantity_both;
+  ReportConfig_A1->reportConfig.choice.reportConfigEUTRA.maxReportCells = 2;
+  ReportConfig_A1->reportConfig.choice.reportConfigEUTRA.reportInterval = ReportInterval_ms120;
+  ReportConfig_A1->reportConfig.choice.reportConfigEUTRA.reportAmount = ReportConfigEUTRA__reportAmount_infinity;
+
+  ASN_SEQUENCE_ADD(&ReportConfig_list->list, ReportConfig_A1);
+  
+  if (ho_state == 1 /*HO_MEASURMENT */ ) {
+    LOG_I(RRC, "[eNB %d] frame %d: requesting A2, A3, A4, A5, and A6 event reporting\n",
+          ctxt_pP->module_id, ctxt_pP->frame);
+    ReportConfig_A2->reportConfigId = 3;
+    ReportConfig_A2->reportConfig.present = ReportConfigToAddMod__reportConfig_PR_reportConfigEUTRA;
+    ReportConfig_A2->reportConfig.choice.reportConfigEUTRA.triggerType.present =
+      ReportConfigEUTRA__triggerType_PR_event;
+    ReportConfig_A2->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.present =
+      ReportConfigEUTRA__triggerType__event__eventId_PR_eventA2;
+    ReportConfig_A2->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.choice.
+    eventA2.a2_Threshold.present = ThresholdEUTRA_PR_threshold_RSRP;
+    ReportConfig_A2->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.choice.
+    eventA2.a2_Threshold.choice.threshold_RSRP = 10;
+
+    ReportConfig_A2->reportConfig.choice.reportConfigEUTRA.triggerQuantity =
+      ReportConfigEUTRA__triggerQuantity_rsrp;
+    ReportConfig_A2->reportConfig.choice.reportConfigEUTRA.reportQuantity = ReportConfigEUTRA__reportQuantity_both;
+    ReportConfig_A2->reportConfig.choice.reportConfigEUTRA.maxReportCells = 2;
+    ReportConfig_A2->reportConfig.choice.reportConfigEUTRA.reportInterval = ReportInterval_ms120;
+    ReportConfig_A2->reportConfig.choice.reportConfigEUTRA.reportAmount = ReportConfigEUTRA__reportAmount_infinity;
+
+    ASN_SEQUENCE_ADD(&ReportConfig_list->list, ReportConfig_A2);
+
+    ReportConfig_A3->reportConfigId = 4;
+    ReportConfig_A3->reportConfig.present = ReportConfigToAddMod__reportConfig_PR_reportConfigEUTRA;
+    ReportConfig_A3->reportConfig.choice.reportConfigEUTRA.triggerType.present =
+      ReportConfigEUTRA__triggerType_PR_event;
+    ReportConfig_A3->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.present =
+      ReportConfigEUTRA__triggerType__event__eventId_PR_eventA3;
+
+    ReportConfig_A3->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.choice.eventA3.a3_Offset = 1;   //10;
+    ReportConfig_A3->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.choice.
+    eventA3.reportOnLeave = 1;
+
+    ReportConfig_A3->reportConfig.choice.reportConfigEUTRA.triggerQuantity =
+      ReportConfigEUTRA__triggerQuantity_rsrp;
+    ReportConfig_A3->reportConfig.choice.reportConfigEUTRA.reportQuantity = ReportConfigEUTRA__reportQuantity_both;
+    ReportConfig_A3->reportConfig.choice.reportConfigEUTRA.maxReportCells = 2;
+    ReportConfig_A3->reportConfig.choice.reportConfigEUTRA.reportInterval = ReportInterval_ms120;
+    ReportConfig_A3->reportConfig.choice.reportConfigEUTRA.reportAmount = ReportConfigEUTRA__reportAmount_infinity;
+
+    ReportConfig_A3->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.hysteresis = 0.5; // FIXME ...hysteresis is of type long!
+    ReportConfig_A3->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.timeToTrigger =
+      TimeToTrigger_ms40;
+    ASN_SEQUENCE_ADD(&ReportConfig_list->list, ReportConfig_A3);
+
+    ReportConfig_A4->reportConfigId = 5;
+    ReportConfig_A4->reportConfig.present = ReportConfigToAddMod__reportConfig_PR_reportConfigEUTRA;
+    ReportConfig_A4->reportConfig.choice.reportConfigEUTRA.triggerType.present =
+      ReportConfigEUTRA__triggerType_PR_event;
+    ReportConfig_A4->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.present =
+      ReportConfigEUTRA__triggerType__event__eventId_PR_eventA4;
+    ReportConfig_A4->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.choice.
+    eventA4.a4_Threshold.present = ThresholdEUTRA_PR_threshold_RSRP;
+    ReportConfig_A4->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.choice.
+    eventA4.a4_Threshold.choice.threshold_RSRP = 10;
+
+    ReportConfig_A4->reportConfig.choice.reportConfigEUTRA.triggerQuantity =
+      ReportConfigEUTRA__triggerQuantity_rsrp;
+    ReportConfig_A4->reportConfig.choice.reportConfigEUTRA.reportQuantity = ReportConfigEUTRA__reportQuantity_both;
+    ReportConfig_A4->reportConfig.choice.reportConfigEUTRA.maxReportCells = 2;
+    ReportConfig_A4->reportConfig.choice.reportConfigEUTRA.reportInterval = ReportInterval_ms120;
+    ReportConfig_A4->reportConfig.choice.reportConfigEUTRA.reportAmount = ReportConfigEUTRA__reportAmount_infinity;
+
+    ASN_SEQUENCE_ADD(&ReportConfig_list->list, ReportConfig_A4);
+
+    ReportConfig_A5->reportConfigId = 6;
+    ReportConfig_A5->reportConfig.present = ReportConfigToAddMod__reportConfig_PR_reportConfigEUTRA;
+    ReportConfig_A5->reportConfig.choice.reportConfigEUTRA.triggerType.present =
+      ReportConfigEUTRA__triggerType_PR_event;
+    ReportConfig_A5->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.present =
+      ReportConfigEUTRA__triggerType__event__eventId_PR_eventA5;
+    ReportConfig_A5->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.choice.
+    eventA5.a5_Threshold1.present = ThresholdEUTRA_PR_threshold_RSRP;
+    ReportConfig_A5->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.choice.
+    eventA5.a5_Threshold2.present = ThresholdEUTRA_PR_threshold_RSRP;
+    ReportConfig_A5->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.choice.
+    eventA5.a5_Threshold1.choice.threshold_RSRP = 10;
+    ReportConfig_A5->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.choice.
+    eventA5.a5_Threshold2.choice.threshold_RSRP = 10;
+
+    ReportConfig_A5->reportConfig.choice.reportConfigEUTRA.triggerQuantity =
+      ReportConfigEUTRA__triggerQuantity_rsrp;
+    ReportConfig_A5->reportConfig.choice.reportConfigEUTRA.reportQuantity = ReportConfigEUTRA__reportQuantity_both;
+    ReportConfig_A5->reportConfig.choice.reportConfigEUTRA.maxReportCells = 2;
+    ReportConfig_A5->reportConfig.choice.reportConfigEUTRA.reportInterval = ReportInterval_ms120;
+    ReportConfig_A5->reportConfig.choice.reportConfigEUTRA.reportAmount = ReportConfigEUTRA__reportAmount_infinity;
+
+    ASN_SEQUENCE_ADD(&ReportConfig_list->list, ReportConfig_A5);
+    //  rrcConnectionReconfiguration->criticalExtensions.choice.c1.choice.rrcConnectionReconfiguration_r8.measConfig->reportConfigToAddModList = ReportConfig_list;
+
+    rsrp = CALLOC(1, sizeof(RSRP_Range_t));
+    *rsrp = 20;
+
+    Sparams = CALLOC(1, sizeof(*Sparams));
+    Sparams->present = MeasConfig__speedStatePars_PR_setup;
+    Sparams->choice.setup.timeToTrigger_SF.sf_High = SpeedStateScaleFactors__sf_Medium_oDot75;
+    Sparams->choice.setup.timeToTrigger_SF.sf_Medium = SpeedStateScaleFactors__sf_High_oDot5;
+    Sparams->choice.setup.mobilityStateParameters.n_CellChangeHigh = 10;
+    Sparams->choice.setup.mobilityStateParameters.n_CellChangeMedium = 5;
+    Sparams->choice.setup.mobilityStateParameters.t_Evaluation = MobilityStateParameters__t_Evaluation_s60;
+    Sparams->choice.setup.mobilityStateParameters.t_HystNormal = MobilityStateParameters__t_HystNormal_s120;
+
+    quantityConfig = CALLOC(1, sizeof(*quantityConfig));
+    memset((void *)quantityConfig, 0, sizeof(*quantityConfig));
+    quantityConfig->quantityConfigEUTRA = CALLOC(1, sizeof(struct QuantityConfigEUTRA));
+    memset((void *)quantityConfig->quantityConfigEUTRA, 0, sizeof(*quantityConfig->quantityConfigEUTRA));
+    quantityConfig->quantityConfigCDMA2000 = NULL;
+    quantityConfig->quantityConfigGERAN = NULL;
+    quantityConfig->quantityConfigUTRA = NULL;
+    quantityConfig->quantityConfigEUTRA->filterCoefficientRSRP =
+      CALLOC(1, sizeof(*(quantityConfig->quantityConfigEUTRA->filterCoefficientRSRP)));
+    quantityConfig->quantityConfigEUTRA->filterCoefficientRSRQ =
+      CALLOC(1, sizeof(*(quantityConfig->quantityConfigEUTRA->filterCoefficientRSRQ)));
+    *quantityConfig->quantityConfigEUTRA->filterCoefficientRSRP = FilterCoefficient_fc4;
+    *quantityConfig->quantityConfigEUTRA->filterCoefficientRSRQ = FilterCoefficient_fc4;
+
+    LOG_I(RRC,
+          "[eNB %d] Frame %d: potential handover preparation: store the information in an intermediate structure in case of failure\n",
+          ctxt_pP->module_id, ctxt_pP->frame);
+    // store the information in an intermediate structure for Hanodver management
+    //rrc_inst->handover_info.as_config.sourceRadioResourceConfig.srb_ToAddModList = CALLOC(1,sizeof());
+    ue_context_pP->ue_context.handover_info = CALLOC(1, sizeof(*(ue_context_pP->ue_context.handover_info)));
+    //memcpy((void *)rrc_inst->handover_info[ue_mod_idP]->as_config.sourceRadioResourceConfig.srb_ToAddModList,(void *)SRB_list,sizeof(SRB_ToAddModList_t));
+    ue_context_pP->ue_context.handover_info->as_config.sourceRadioResourceConfig.srb_ToAddModList = *SRB_configList2;
+    //memcpy((void *)rrc_inst->handover_info[ue_mod_idP]->as_config.sourceRadioResourceConfig.drb_ToAddModList,(void *)DRB_list,sizeof(DRB_ToAddModList_t));
+    ue_context_pP->ue_context.handover_info->as_config.sourceRadioResourceConfig.drb_ToAddModList = *DRB_configList;
+    ue_context_pP->ue_context.handover_info->as_config.sourceRadioResourceConfig.drb_ToReleaseList = NULL;
+    ue_context_pP->ue_context.handover_info->as_config.sourceRadioResourceConfig.mac_MainConfig =
+      CALLOC(1, sizeof(*ue_context_pP->ue_context.handover_info->as_config.sourceRadioResourceConfig.mac_MainConfig));
+    memcpy((void*)ue_context_pP->ue_context.handover_info->as_config.sourceRadioResourceConfig.mac_MainConfig,
+           (void *)mac_MainConfig, sizeof(MAC_MainConfig_t));
+    ue_context_pP->ue_context.handover_info->as_config.sourceRadioResourceConfig.physicalConfigDedicated =
+      CALLOC(1, sizeof(PhysicalConfigDedicated_t));
+    memcpy((void*)ue_context_pP->ue_context.handover_info->as_config.sourceRadioResourceConfig.physicalConfigDedicated,
+           (void*)ue_context_pP->ue_context.physicalConfigDedicated, sizeof(PhysicalConfigDedicated_t));
+    ue_context_pP->ue_context.handover_info->as_config.sourceRadioResourceConfig.sps_Config = NULL;
+    //memcpy((void *)rrc_inst->handover_info[ue_mod_idP]->as_config.sourceRadioResourceConfig.sps_Config,(void *)rrc_inst->sps_Config[ue_mod_idP],sizeof(SPS_Config_t));
+
+  }
+
+#if defined(ENABLE_ITTI)
+  /* Initialize NAS list */
+  dedicatedInfoNASList = CALLOC(1, sizeof(struct RRCConnectionReconfiguration_r8_IEs__dedicatedInfoNASList));
+
+  /* Add all NAS PDUs to the list */
+  for (i = 0; i < ue_context_pP->ue_context.nb_of_e_rabs; i++) {
+    if (ue_context_pP->ue_context.e_rab[i].param.nas_pdu.buffer != NULL) {
+      dedicatedInfoNas = CALLOC(1, sizeof(DedicatedInfoNAS_t));
+      memset(dedicatedInfoNas, 0, sizeof(OCTET_STRING_t));
+      OCTET_STRING_fromBuf(dedicatedInfoNas, 
+			   (char*)ue_context_pP->ue_context.e_rab[i].param.nas_pdu.buffer,
+                           ue_context_pP->ue_context.e_rab[i].param.nas_pdu.length);
+      ASN_SEQUENCE_ADD(&dedicatedInfoNASList->list, dedicatedInfoNas);
+    }
+
+    /* TODO parameters yet to process ... */
+    {
+      //      ue_context_pP->ue_context.e_rab[i].param.qos;
+      //      ue_context_pP->ue_context.e_rab[i].param.sgw_addr;
+      //      ue_context_pP->ue_context.e_rab[i].param.gtp_teid;
+    }
+
+    /* TODO should test if e RAB are Ok before! */
+    ue_context_pP->ue_context.e_rab[i].status = E_RAB_STATUS_DONE;
+    LOG_D(RRC, "setting the status for the default DRB (index %d) to (%d,%s)\n", 
+	  i, ue_context_pP->ue_context.e_rab[i].status, "E_RAB_STATUS_DONE");
+  }
+
+  /* If list is empty free the list and reset the address */
+  if (dedicatedInfoNASList->list.count == 0) {
+    free(dedicatedInfoNASList);
+    dedicatedInfoNASList = NULL;
+  }
+
+#endif
+
+  memset(buffer, 0, RRC_BUF_SIZE);
+
+  size = do_RRCConnectionReconfiguration(ctxt_pP,
+                                         buffer,
+                                         xid,   //Transaction_id,
+                                         (SRB_ToAddModList_t*)*SRB_configList2, // SRB_configList
+                                         (DRB_ToAddModList_t*)*DRB_configList,
+                                         (DRB_ToReleaseList_t*)NULL,  // DRB2_list,
+                                         (struct SPS_Config*)NULL,    // *sps_Config,
+                                         (struct PhysicalConfigDedicated*)*physicalConfigDedicated,
+#ifdef EXMIMO_IOT
+                                         NULL, NULL, NULL,NULL,
+#else
+                                         (MeasObjectToAddModList_t*)MeasObj_list,
+                                         (ReportConfigToAddModList_t*)ReportConfig_list,
+                                         (QuantityConfig_t*)quantityConfig,
+                                         (MeasIdToAddModList_t*)MeasId_list,
+#endif
+                                         (MAC_MainConfig_t*)mac_MainConfig,
+                                         (MeasGapConfig_t*)NULL,
+                                         (MobilityControlInfo_t*)NULL,
+                                         (struct MeasConfig__speedStatePars*)Sparams,
+                                         (RSRP_Range_t*)rsrp,
+                                         (C_RNTI_t*)cba_RNTI,
+                                         (struct RRCConnectionReconfiguration_r8_IEs__dedicatedInfoNASList*)dedicatedInfoNASList
+#if defined(Rel10) || defined(Rel14)
+                                         , (SCellToAddMod_r10_t*)NULL
+#endif
+                                        );
+
+#ifdef RRC_MSG_PRINT
+  LOG_F(RRC,"[MSG] RRC Connection Reconfiguration\n");
+  for (i = 0; i < size; i++) {
+    LOG_F(RRC,"%02x ", ((uint8_t*)buffer)[i]);
+  }
+  LOG_F(RRC,"\n");
+  ////////////////////////////////////////
+#endif
+
+#if defined(ENABLE_ITTI)
+
+  /* Free all NAS PDUs */
+  for (i = 0; i < ue_context_pP->ue_context.nb_of_e_rabs; i++) {
+    if (ue_context_pP->ue_context.e_rab[i].param.nas_pdu.buffer != NULL) {
+      /* Free the NAS PDU buffer and invalidate it */
+      free(ue_context_pP->ue_context.e_rab[i].param.nas_pdu.buffer);
+      ue_context_pP->ue_context.e_rab[i].param.nas_pdu.buffer = NULL;
+    }
+  }
+
+#endif
+
+  LOG_I(RRC,
+        "[eNB %d] Frame %d, Logical Channel DL-DCCH, Generate RRCConnectionReconfiguration (bytes %d, UE id %x)\n",
+        ctxt_pP->module_id, ctxt_pP->frame, size, ue_context_pP->ue_context.rnti);
+
+  LOG_D(RRC,
+        "[FRAME %05d][RRC_eNB][MOD %u][][--- PDCP_DATA_REQ/%d Bytes (rrcConnectionReconfiguration to UE %x MUI %d) --->][PDCP][MOD %u][RB %u]\n",
+        ctxt_pP->frame, ctxt_pP->module_id, size, ue_context_pP->ue_context.rnti, rrc_eNB_mui, ctxt_pP->module_id, DCCH);
+
+  MSC_LOG_TX_MESSAGE(
+    MSC_RRC_ENB,
+    MSC_RRC_UE,
+    buffer,
+    size,
+    MSC_AS_TIME_FMT" rrcConnectionReconfiguration UE %x MUI %d size %u",
+    MSC_AS_TIME_ARGS(ctxt_pP),
+    ue_context_pP->ue_context.rnti,
+    rrc_eNB_mui,
+    size);
+
+  rrc_data_req(
+	       ctxt_pP,
+	       DCCH,
+	       rrc_eNB_mui++,
+	       SDU_CONFIRM_NO,
+	       size,
+	       buffer,
+	       PDCP_TRANSMISSION_MODE_CONTROL);
+}
+
+#if defined(FLEXRAN_AGENT_SB_IF)
+
+//-----------------------------------------------------------------------------
+void
+flexran_rrc_eNB_generate_defaultRRCConnectionReconfiguration(const protocol_ctxt_t* const ctxt_pP,
+                 rrc_eNB_ue_context_t*          const ue_context_pP,
+                 const uint8_t                ho_state,
+                 agent_reconf_rrc * trig_param
+                 )
+//-----------------------------------------------------------------------------
+{
+  uint8_t                             buffer[RRC_BUF_SIZE];
+  uint16_t                            size;
+  int                                 i;
+ 
+  // configure SRB1/SRB2, PhysicalConfigDedicated, MAC_MainConfig for UE
+  eNB_RRC_INST*                       rrc_inst = &eNB_rrc_inst[ctxt_pP->module_id];
+  struct PhysicalConfigDedicated**    physicalConfigDedicated = &ue_context_pP->ue_context.physicalConfigDedicated;
+
+  struct SRB_ToAddMod                *SRB2_config                      = NULL;
+  struct SRB_ToAddMod__rlc_Config    *SRB2_rlc_config                  = NULL;
+  struct SRB_ToAddMod__logicalChannelConfig *SRB2_lchan_config         = NULL;
+  struct LogicalChannelConfig__ul_SpecificParameters
+      *SRB2_ul_SpecificParameters       = NULL;
+  SRB_ToAddModList_t*                 SRB_configList = ue_context_pP->ue_context.SRB_configList;
+  SRB_ToAddModList_t                 **SRB_configList2                  = NULL;
+
+  struct DRB_ToAddMod                *DRB_config                       = NULL;
+  struct RLC_Config                  *DRB_rlc_config                   = NULL;
+  struct PDCP_Config                 *DRB_pdcp_config                  = NULL;
+  struct PDCP_Config__rlc_AM         *PDCP_rlc_AM                      = NULL;
+  struct PDCP_Config__rlc_UM         *PDCP_rlc_UM                      = NULL;
+  struct LogicalChannelConfig        *DRB_lchan_config                 = NULL;
+  struct LogicalChannelConfig__ul_SpecificParameters
+      *DRB_ul_SpecificParameters        = NULL;
+  DRB_ToAddModList_t**                DRB_configList = &ue_context_pP->ue_context.DRB_configList;
+  DRB_ToAddModList_t**                DRB_configList2 = NULL;
+   MAC_MainConfig_t                   *mac_MainConfig                   = NULL;
+  MeasObjectToAddModList_t           *MeasObj_list                     = NULL;
+  MeasObjectToAddMod_t               *MeasObj                          = NULL;
+  ReportConfigToAddModList_t         *ReportConfig_list                = NULL;
+  ReportConfigToAddMod_t             *ReportConfig_per;//, *ReportConfig_A1,
+                                     // *ReportConfig_A2, *ReportConfig_A3, *ReportConfig_A4, *ReportConfig_A5;
+  MeasIdToAddModList_t               *MeasId_list                      = NULL;
+  MeasIdToAddMod_t                   *MeasId0; //, *MeasId1, *MeasId2, *MeasId3, *MeasId4, *MeasId5;
+#if Rel10
+  long                               *sr_ProhibitTimer_r9              = NULL;
+  //     uint8_t sCellIndexToAdd = rrc_find_free_SCell_index(enb_mod_idP, ue_mod_idP, 1);
+  //uint8_t                            sCellIndexToAdd = 0;
+#endif
+
+  long                               *logicalchannelgroup, *logicalchannelgroup_drb;
+  long                               *maxHARQ_Tx, *periodicBSR_Timer;
+
+  RSRP_Range_t                       *rsrp                             = NULL;
+  struct MeasConfig__speedStatePars  *Sparams                          = NULL;
+  QuantityConfig_t                   *quantityConfig                   = NULL;
+  CellsToAddMod_t                    *CellToAdd                        = NULL;
+  CellsToAddModList_t                *CellsToAddModList                = NULL;
+  struct RRCConnectionReconfiguration_r8_IEs__dedicatedInfoNASList *dedicatedInfoNASList = NULL;
+  DedicatedInfoNAS_t                 *dedicatedInfoNas                 = NULL;
+  /* for no gcc warnings */
+  (void)dedicatedInfoNas;
+
+  C_RNTI_t                           *cba_RNTI                         = NULL;
+
+  uint8_t xid = rrc_eNB_get_next_transaction_identifier(ctxt_pP->module_id);   //Transaction_id,
+
+#ifdef CBA
+  //struct PUSCH_CBAConfigDedicated_vlola  *pusch_CBAConfigDedicated_vlola;
+  uint8_t                            *cba_RNTI_buf;
+  cba_RNTI = CALLOC(1, sizeof(C_RNTI_t));
+  cba_RNTI_buf = CALLOC(1, 2 * sizeof(uint8_t));
+  cba_RNTI->buf = cba_RNTI_buf;
+  cba_RNTI->size = 2;
+  cba_RNTI->bits_unused = 0;
+
+  // associate UEs to the CBa groups as a function of their UE id
+  if (rrc_inst->num_active_cba_groups) {
+    cba_RNTI->buf[0] = rrc_inst->cba_rnti[ue_mod_idP % rrc_inst->num_active_cba_groups] & 0xff;
+    cba_RNTI->buf[1] = 0xff;
+    LOG_D(RRC,
+          "[eNB %d] Frame %d: cba_RNTI = %x in group %d is attribued to UE %d\n",
+          enb_mod_idP, frameP,
+          rrc_inst->cba_rnti[ue_mod_idP % rrc_inst->num_active_cba_groups],
+          ue_mod_idP % rrc_inst->num_active_cba_groups, ue_mod_idP);
+  } else {
+    cba_RNTI->buf[0] = 0x0;
+    cba_RNTI->buf[1] = 0x0;
+    LOG_D(RRC, "[eNB %d] Frame %d: no cba_RNTI is configured for UE %d\n", enb_mod_idP, frameP, ue_mod_idP);
+  }
+
+#endif
+
+  T(T_ENB_RRC_CONNECTION_RECONFIGURATION, T_INT(ctxt_pP->module_id), T_INT(ctxt_pP->frame),
+    T_INT(ctxt_pP->subframe), T_INT(ctxt_pP->rnti));
+
+  // Configure SRB2
+  /// SRB2
+  SRB_configList2=&ue_context_pP->ue_context.SRB_configList2[xid];
+  if (*SRB_configList2) {
+    free(*SRB_configList2);
+  }
+  *SRB_configList2 = CALLOC(1, sizeof(**SRB_configList2));
+  memset(*SRB_configList2, 0, sizeof(**SRB_configList2));
+  SRB2_config = CALLOC(1, sizeof(*SRB2_config));
+
+  SRB2_config->srb_Identity = 2;
+  SRB2_rlc_config = CALLOC(1, sizeof(*SRB2_rlc_config));
+  SRB2_config->rlc_Config = SRB2_rlc_config;
+
+  SRB2_rlc_config->present = SRB_ToAddMod__rlc_Config_PR_explicitValue;
+  SRB2_rlc_config->choice.explicitValue.present = RLC_Config_PR_am;
+  SRB2_rlc_config->choice.explicitValue.choice.am.ul_AM_RLC.t_PollRetransmit = T_PollRetransmit_ms15;
+  SRB2_rlc_config->choice.explicitValue.choice.am.ul_AM_RLC.pollPDU = PollPDU_p8;
+  SRB2_rlc_config->choice.explicitValue.choice.am.ul_AM_RLC.pollByte = PollByte_kB1000;
+  SRB2_rlc_config->choice.explicitValue.choice.am.ul_AM_RLC.maxRetxThreshold = UL_AM_RLC__maxRetxThreshold_t32;
+  SRB2_rlc_config->choice.explicitValue.choice.am.dl_AM_RLC.t_Reordering = T_Reordering_ms35;
+  SRB2_rlc_config->choice.explicitValue.choice.am.dl_AM_RLC.t_StatusProhibit = T_StatusProhibit_ms10;
+
+  SRB2_lchan_config = CALLOC(1, sizeof(*SRB2_lchan_config));
+  SRB2_config->logicalChannelConfig = SRB2_lchan_config;
+
+  SRB2_lchan_config->present = SRB_ToAddMod__logicalChannelConfig_PR_explicitValue;
+
+  SRB2_ul_SpecificParameters = CALLOC(1, sizeof(*SRB2_ul_SpecificParameters));
+
+  SRB2_ul_SpecificParameters->priority = 3; // let some priority for SRB1 and dedicated DRBs
+  SRB2_ul_SpecificParameters->prioritisedBitRate =
+    LogicalChannelConfig__ul_SpecificParameters__prioritisedBitRate_infinity;
+  SRB2_ul_SpecificParameters->bucketSizeDuration =
+    LogicalChannelConfig__ul_SpecificParameters__bucketSizeDuration_ms50;
+
+  // LCG for CCCH and DCCH is 0 as defined in 36331
+  logicalchannelgroup = CALLOC(1, sizeof(long));
+  *logicalchannelgroup = 0;
+
+  SRB2_ul_SpecificParameters->logicalChannelGroup = logicalchannelgroup;
+
+  SRB2_lchan_config->choice.explicitValue.ul_SpecificParameters = SRB2_ul_SpecificParameters;
+  // this list has the configuration for SRB1 and SRB2
+  ASN_SEQUENCE_ADD(&SRB_configList->list, SRB2_config);
+  // this list has only the configuration for SRB2
+  ASN_SEQUENCE_ADD(&(*SRB_configList2)->list, SRB2_config);
+
+  // Configure DRB
+  //*DRB_configList = CALLOC(1, sizeof(*DRB_configList));
+  // list for all the configured DRB
+  if (*DRB_configList) {
+    free(*DRB_configList);
+  }
+  *DRB_configList = CALLOC(1, sizeof(**DRB_configList));
+  memset(*DRB_configList, 0, sizeof(**DRB_configList));
+
+  // list for the configured DRB for a this xid
+  DRB_configList2=&ue_context_pP->ue_context.DRB_configList2[xid];
+  if (*DRB_configList2) {
+    free(*DRB_configList2);
+  }
+  *DRB_configList2 = CALLOC(1, sizeof(**DRB_configList2));
+  memset(*DRB_configList2, 0, sizeof(**DRB_configList2));
+
+
+  /// DRB
+  DRB_config = CALLOC(1, sizeof(*DRB_config));
+
+  DRB_config->eps_BearerIdentity = CALLOC(1, sizeof(long));
+  *(DRB_config->eps_BearerIdentity) = 5L; // LW set to first value, allowed value 5..15, value : x+4
+  // DRB_config->drb_Identity = (DRB_Identity_t) 1; //allowed values 1..32
+  // NN: this is the 1st DRB for this ue, so set it to 1
+  DRB_config->drb_Identity = (DRB_Identity_t) 1;  // (ue_mod_idP+1); //allowed values 1..32, value: x
+  DRB_config->logicalChannelIdentity = CALLOC(1, sizeof(long));
+  *(DRB_config->logicalChannelIdentity) = (long)3; // value : x+2
+  DRB_rlc_config = CALLOC(1, sizeof(*DRB_rlc_config));
+  DRB_config->rlc_Config = DRB_rlc_config;
+
+#ifdef RRC_DEFAULT_RAB_IS_AM
+  DRB_rlc_config->present = RLC_Config_PR_am;
+  DRB_rlc_config->choice.am.ul_AM_RLC.t_PollRetransmit = T_PollRetransmit_ms50;
+  DRB_rlc_config->choice.am.ul_AM_RLC.pollPDU = PollPDU_p16;
+  DRB_rlc_config->choice.am.ul_AM_RLC.pollByte = PollByte_kBinfinity;
+  DRB_rlc_config->choice.am.ul_AM_RLC.maxRetxThreshold = UL_AM_RLC__maxRetxThreshold_t8;
+  DRB_rlc_config->choice.am.dl_AM_RLC.t_Reordering = T_Reordering_ms35;
+  DRB_rlc_config->choice.am.dl_AM_RLC.t_StatusProhibit = T_StatusProhibit_ms25;
+#else
+  DRB_rlc_config->present = RLC_Config_PR_um_Bi_Directional;
+  DRB_rlc_config->choice.um_Bi_Directional.ul_UM_RLC.sn_FieldLength = SN_FieldLength_size10;
+  DRB_rlc_config->choice.um_Bi_Directional.dl_UM_RLC.sn_FieldLength = SN_FieldLength_size10;
+#ifdef CBA
+  DRB_rlc_config->choice.um_Bi_Directional.dl_UM_RLC.t_Reordering   = T_Reordering_ms5;//T_Reordering_ms25;
+#else
+  DRB_rlc_config->choice.um_Bi_Directional.dl_UM_RLC.t_Reordering = T_Reordering_ms35;
+#endif
+#endif
+
+  DRB_pdcp_config = CALLOC(1, sizeof(*DRB_pdcp_config));
+  DRB_config->pdcp_Config = DRB_pdcp_config;
+  DRB_pdcp_config->discardTimer = CALLOC(1, sizeof(long));
+  *DRB_pdcp_config->discardTimer = PDCP_Config__discardTimer_infinity;
+  DRB_pdcp_config->rlc_AM = NULL;
+  DRB_pdcp_config->rlc_UM = NULL;
+
+  /* avoid gcc warnings */
+  (void)PDCP_rlc_AM;
+  (void)PDCP_rlc_UM;
+
+#ifdef RRC_DEFAULT_RAB_IS_AM // EXMIMO_IOT
+  PDCP_rlc_AM = CALLOC(1, sizeof(*PDCP_rlc_AM));
+  DRB_pdcp_config->rlc_AM = PDCP_rlc_AM;
+  PDCP_rlc_AM->statusReportRequired = FALSE;
+#else
+  PDCP_rlc_UM = CALLOC(1, sizeof(*PDCP_rlc_UM));
+  DRB_pdcp_config->rlc_UM = PDCP_rlc_UM;
+  PDCP_rlc_UM->pdcp_SN_Size = PDCP_Config__rlc_UM__pdcp_SN_Size_len12bits;
+#endif
+  DRB_pdcp_config->headerCompression.present = PDCP_Config__headerCompression_PR_notUsed;
+
+  DRB_lchan_config = CALLOC(1, sizeof(*DRB_lchan_config));
+  DRB_config->logicalChannelConfig = DRB_lchan_config;
+  DRB_ul_SpecificParameters = CALLOC(1, sizeof(*DRB_ul_SpecificParameters));
+  DRB_lchan_config->ul_SpecificParameters = DRB_ul_SpecificParameters;
+
+  DRB_ul_SpecificParameters->priority = 12;    // lower priority than srb1, srb2 and other dedicated bearer
+  DRB_ul_SpecificParameters->prioritisedBitRate =LogicalChannelConfig__ul_SpecificParameters__prioritisedBitRate_kBps8 ;
+    //LogicalChannelConfig__ul_SpecificParameters__prioritisedBitRate_infinity;
+  DRB_ul_SpecificParameters->bucketSizeDuration =
+    LogicalChannelConfig__ul_SpecificParameters__bucketSizeDuration_ms50;
+
+  // LCG for DTCH can take the value from 1 to 3 as defined in 36331: normally controlled by upper layers (like RRM)
+  logicalchannelgroup_drb = CALLOC(1, sizeof(long));
+  *logicalchannelgroup_drb = 1;
+  DRB_ul_SpecificParameters->logicalChannelGroup = logicalchannelgroup_drb;
+
+  ASN_SEQUENCE_ADD(&(*DRB_configList)->list, DRB_config);
+  ASN_SEQUENCE_ADD(&(*DRB_configList2)->list, DRB_config);
+
+  //ue_context_pP->ue_context.DRB_configList2[0] = &(*DRB_configList);
+
+  mac_MainConfig = CALLOC(1, sizeof(*mac_MainConfig));
+  // ue_context_pP->ue_context.mac_MainConfig = mac_MainConfig;
+
+  mac_MainConfig->ul_SCH_Config = CALLOC(1, sizeof(*mac_MainConfig->ul_SCH_Config));
+
+  maxHARQ_Tx = CALLOC(1, sizeof(long));
+  *maxHARQ_Tx = MAC_MainConfig__ul_SCH_Config__maxHARQ_Tx_n5;
+  mac_MainConfig->ul_SCH_Config->maxHARQ_Tx = maxHARQ_Tx;
+  periodicBSR_Timer = CALLOC(1, sizeof(long));
+  *periodicBSR_Timer = PeriodicBSR_Timer_r12_sf64;
+  mac_MainConfig->ul_SCH_Config->periodicBSR_Timer = periodicBSR_Timer;
+  mac_MainConfig->ul_SCH_Config->retxBSR_Timer = RetxBSR_Timer_r12_sf320;
+  mac_MainConfig->ul_SCH_Config->ttiBundling = 0; // FALSE
+
+  mac_MainConfig->timeAlignmentTimerDedicated = TimeAlignmentTimer_infinity;
+
+  mac_MainConfig->drx_Config = NULL;
+
+  mac_MainConfig->phr_Config = CALLOC(1, sizeof(*mac_MainConfig->phr_Config));
+
+  mac_MainConfig->phr_Config->present = MAC_MainConfig__phr_Config_PR_setup;
+  mac_MainConfig->phr_Config->choice.setup.periodicPHR_Timer = MAC_MainConfig__phr_Config__setup__periodicPHR_Timer_sf20; // sf20 = 20 subframes
+
+  mac_MainConfig->phr_Config->choice.setup.prohibitPHR_Timer = MAC_MainConfig__phr_Config__setup__prohibitPHR_Timer_sf20; // sf20 = 20 subframes
+
+  mac_MainConfig->phr_Config->choice.setup.dl_PathlossChange = MAC_MainConfig__phr_Config__setup__dl_PathlossChange_dB1;  // Value dB1 =1 dB, dB3 = 3 dB
+
+#ifdef Rel10
+  sr_ProhibitTimer_r9 = CALLOC(1, sizeof(long));
+  *sr_ProhibitTimer_r9 = 0;   // SR tx on PUCCH, Value in number of SR period(s). Value 0 = no timer for SR, Value 2= 2*SR
+  mac_MainConfig->ext1 = CALLOC(1, sizeof(struct MAC_MainConfig__ext1));
+  mac_MainConfig->ext1->sr_ProhibitTimer_r9 = sr_ProhibitTimer_r9;
+  //sps_RA_ConfigList_rlola = NULL;
+#endif
+
+  //change the transmission mode for the primary component carrier
+  //TODO: add codebook subset restriction here
+  //TODO: change TM for secondary CC in SCelltoaddmodlist
+  if (*physicalConfigDedicated) {
+    if ((*physicalConfigDedicated)->antennaInfo) {
+      (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.transmissionMode = rrc_inst->configuration.ue_TransmissionMode[0];
+      LOG_D(RRC,"Setting transmission mode to %ld+1\n",rrc_inst->configuration.ue_TransmissionMode[0]);
+      if (rrc_inst->configuration.ue_TransmissionMode[0]==AntennaInfoDedicated__transmissionMode_tm3) {
+  (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction=     
+    CALLOC(1,sizeof(AntennaInfoDedicated__codebookSubsetRestriction_PR));
+  (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->present =
+    AntennaInfoDedicated__codebookSubsetRestriction_PR_n2TxAntenna_tm3;
+  (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm3.buf= MALLOC(1);
+  (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm3.buf[0] = 0xc0;
+  (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm3.size=1;
+  (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm3.bits_unused=6;
+      }
+      else if (rrc_inst->configuration.ue_TransmissionMode[0]==AntennaInfoDedicated__transmissionMode_tm4) {
+  (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction=     
+    CALLOC(1,sizeof(AntennaInfoDedicated__codebookSubsetRestriction_PR));
+  (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->present =
+    AntennaInfoDedicated__codebookSubsetRestriction_PR_n2TxAntenna_tm4;
+  (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm4.buf= MALLOC(1);
+  (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm4.buf[0] = 0xfc;
+  (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm4.size=1;
+  (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm4.bits_unused=2;
+
+      }
+      else if (rrc_inst->configuration.ue_TransmissionMode[0]==AntennaInfoDedicated__transmissionMode_tm5) {
+  (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction=     
+    CALLOC(1,sizeof(AntennaInfoDedicated__codebookSubsetRestriction_PR));
+  (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->present =
+    AntennaInfoDedicated__codebookSubsetRestriction_PR_n2TxAntenna_tm5;
+  (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm5.buf= MALLOC(1);
+  (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm5.buf[0] = 0xf0;
+  (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm5.size=1;
+  (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm5.bits_unused=4;
+      }
+      else if (rrc_inst->configuration.ue_TransmissionMode[0]==AntennaInfoDedicated__transmissionMode_tm6) {
+  (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction=     
+    CALLOC(1,sizeof(AntennaInfoDedicated__codebookSubsetRestriction_PR));
+  (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->present =
+    AntennaInfoDedicated__codebookSubsetRestriction_PR_n2TxAntenna_tm6;
+  (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm6.buf= MALLOC(1);
+  (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm6.buf[0] = 0xf0;
+  (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm6.size=1;
+  (*physicalConfigDedicated)->antennaInfo->choice.explicitValue.codebookSubsetRestriction->choice.n2TxAntenna_tm6.bits_unused=4;
       }
     }
     else {
@@ -1727,15 +2467,15 @@ rrc_eNB_generate_defaultRRCConnectionReconfiguration(const protocol_ctxt_t* cons
     }
     if ((*physicalConfigDedicated)->cqi_ReportConfig) {
       if ((rrc_inst->configuration.ue_TransmissionMode[0]==AntennaInfoDedicated__transmissionMode_tm4) ||
-	  (rrc_inst->configuration.ue_TransmissionMode[0]==AntennaInfoDedicated__transmissionMode_tm5) ||
-	  (rrc_inst->configuration.ue_TransmissionMode[0]==AntennaInfoDedicated__transmissionMode_tm6)) {
-	//feedback mode needs to be set as well
-	//TODO: I think this is taken into account in the PHY automatically based on the transmission mode variable
-	printf("setting cqi reporting mode to rm31\n");
+    (rrc_inst->configuration.ue_TransmissionMode[0]==AntennaInfoDedicated__transmissionMode_tm5) ||
+    (rrc_inst->configuration.ue_TransmissionMode[0]==AntennaInfoDedicated__transmissionMode_tm6)) {
+  //feedback mode needs to be set as well
+  //TODO: I think this is taken into account in the PHY automatically based on the transmission mode variable
+  printf("setting cqi reporting mode to rm31\n");
 #if defined(Rel10) || defined(Rel14)
-	*((*physicalConfigDedicated)->cqi_ReportConfig->cqi_ReportModeAperiodic)=CQI_ReportModeAperiodic_rm31;
+  *((*physicalConfigDedicated)->cqi_ReportConfig->cqi_ReportModeAperiodic)=CQI_ReportModeAperiodic_rm31;
 #else
-	*((*physicalConfigDedicated)->cqi_ReportConfig->cqi_ReportModeAperiodic)=CQI_ReportConfig__cqi_ReportModeAperiodic_rm31; // HLC CQI, no PMI
+  *((*physicalConfigDedicated)->cqi_ReportConfig->cqi_ReportModeAperiodic)=CQI_ReportConfig__cqi_ReportModeAperiodic_rm31; // HLC CQI, no PMI
 #endif
       }
     }
@@ -1757,43 +2497,14 @@ rrc_eNB_generate_defaultRRCConnectionReconfiguration(const protocol_ctxt_t* cons
   MeasId0->reportConfigId = 1;
   ASN_SEQUENCE_ADD(&MeasId_list->list, MeasId0);
 
-  MeasId1 = CALLOC(1, sizeof(*MeasId1));
-  MeasId1->measId = 2;
-  MeasId1->measObjectId = 1;
-  MeasId1->reportConfigId = 2;
-  ASN_SEQUENCE_ADD(&MeasId_list->list, MeasId1);
-
-  MeasId2 = CALLOC(1, sizeof(*MeasId2));
-  MeasId2->measId = 3;
-  MeasId2->measObjectId = 1;
-  MeasId2->reportConfigId = 3;
-  ASN_SEQUENCE_ADD(&MeasId_list->list, MeasId2);
-
-  MeasId3 = CALLOC(1, sizeof(*MeasId3));
-  MeasId3->measId = 4;
-  MeasId3->measObjectId = 1;
-  MeasId3->reportConfigId = 4;
-  ASN_SEQUENCE_ADD(&MeasId_list->list, MeasId3);
-
-  MeasId4 = CALLOC(1, sizeof(*MeasId4));
-  MeasId4->measId = 5;
-  MeasId4->measObjectId = 1;
-  MeasId4->reportConfigId = 5;
-  ASN_SEQUENCE_ADD(&MeasId_list->list, MeasId4);
-
-  MeasId5 = CALLOC(1, sizeof(*MeasId5));
-  MeasId5->measId = 6;
-  MeasId5->measObjectId = 1;
-  MeasId5->reportConfigId = 6;
-  ASN_SEQUENCE_ADD(&MeasId_list->list, MeasId5);
-
-  //  rrcConnectionReconfiguration->criticalExtensions.choice.c1.choice.rrcConnectionReconfiguration_r8.measConfig->measIdToAddModList = MeasId_list;
+  /*
+   * Add one EUTRA Measurement Object
+  */
 
-  // Add one EUTRA Measurement Object
   MeasObj_list = CALLOC(1, sizeof(*MeasObj_list));
   memset((void *)MeasObj_list, 0, sizeof(*MeasObj_list));
 
-  // Configure MeasObject
+  // Configure MeasObject 
 
   MeasObj = CALLOC(1, sizeof(*MeasObj));
   memset((void *)MeasObj, 0, sizeof(*MeasObj));
@@ -1829,155 +2540,65 @@ rrc_eNB_generate_defaultRRCConnectionReconfiguration(const protocol_ctxt_t* cons
   //  rrcConnectionReconfiguration->criticalExtensions.choice.c1.choice.rrcConnectionReconfiguration_r8.measConfig->measObjectToAddModList = MeasObj_list;
 
   // Report Configurations for periodical, A1-A5 events
-  ReportConfig_list = CALLOC(1, sizeof(*ReportConfig_list));
 
-  ReportConfig_per = CALLOC(1, sizeof(*ReportConfig_per));
+  /* RRC Strategy Measurement */
 
-  ReportConfig_A1 = CALLOC(1, sizeof(*ReportConfig_A1));
 
-  ReportConfig_A2 = CALLOC(1, sizeof(*ReportConfig_A2));
+  if (strcmp("one_shot", trig_param->trigger_policy) == 0){
 
-  ReportConfig_A3 = CALLOC(1, sizeof(*ReportConfig_A3));
+      trig_param->report_interval = 0;
+      trig_param->report_amount = 0;
 
-  ReportConfig_A4 = CALLOC(1, sizeof(*ReportConfig_A4));
+  }
 
-  ReportConfig_A5 = CALLOC(1, sizeof(*ReportConfig_A5));
+  else if (strcmp("event_driven", trig_param->trigger_policy) == 0){
 
-  ReportConfig_per->reportConfigId = 1;
-  ReportConfig_per->reportConfig.present = ReportConfigToAddMod__reportConfig_PR_reportConfigEUTRA;
-  ReportConfig_per->reportConfig.choice.reportConfigEUTRA.triggerType.present =
-    ReportConfigEUTRA__triggerType_PR_periodical;
-  ReportConfig_per->reportConfig.choice.reportConfigEUTRA.triggerType.choice.periodical.purpose =
-    ReportConfigEUTRA__triggerType__periodical__purpose_reportStrongestCells;
-  ReportConfig_per->reportConfig.choice.reportConfigEUTRA.triggerQuantity = ReportConfigEUTRA__triggerQuantity_rsrp;
-  ReportConfig_per->reportConfig.choice.reportConfigEUTRA.reportQuantity = ReportConfigEUTRA__reportQuantity_both;
-  ReportConfig_per->reportConfig.choice.reportConfigEUTRA.maxReportCells = 2;
-  ReportConfig_per->reportConfig.choice.reportConfigEUTRA.reportInterval = ReportInterval_ms120;
-  ReportConfig_per->reportConfig.choice.reportConfigEUTRA.reportAmount = ReportConfigEUTRA__reportAmount_infinity;
+      trig_param->report_interval = 6;
+      trig_param->report_amount = 2;
 
-  ASN_SEQUENCE_ADD(&ReportConfig_list->list, ReportConfig_per);
+  }
 
-  ReportConfig_A1->reportConfigId = 2;
-  ReportConfig_A1->reportConfig.present = ReportConfigToAddMod__reportConfig_PR_reportConfigEUTRA;
-  ReportConfig_A1->reportConfig.choice.reportConfigEUTRA.triggerType.present =
-    ReportConfigEUTRA__triggerType_PR_event;
-  ReportConfig_A1->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.present =
-    ReportConfigEUTRA__triggerType__event__eventId_PR_eventA1;
-  ReportConfig_A1->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.choice.eventA1.
-  a1_Threshold.present = ThresholdEUTRA_PR_threshold_RSRP;
-  ReportConfig_A1->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.choice.eventA1.
-  a1_Threshold.choice.threshold_RSRP = 10;
+  else if (strcmp("periodical", trig_param->trigger_policy) == 0){
 
-  ReportConfig_A1->reportConfig.choice.reportConfigEUTRA.triggerQuantity = ReportConfigEUTRA__triggerQuantity_rsrp;
-  ReportConfig_A1->reportConfig.choice.reportConfigEUTRA.reportQuantity = ReportConfigEUTRA__reportQuantity_both;
-  ReportConfig_A1->reportConfig.choice.reportConfigEUTRA.maxReportCells = 2;
-  ReportConfig_A1->reportConfig.choice.reportConfigEUTRA.reportInterval = ReportInterval_ms120;
-  ReportConfig_A1->reportConfig.choice.reportConfigEUTRA.reportAmount = ReportConfigEUTRA__reportAmount_infinity;
+      trig_param->report_interval = 1;
+      trig_param->report_amount = 7;
 
-  ASN_SEQUENCE_ADD(&ReportConfig_list->list, ReportConfig_A1);
+  }
 
-  if (ho_state == 1 /*HO_MEASURMENT */ ) {
-    LOG_I(RRC, "[eNB %d] frame %d: requesting A2, A3, A4, A5, and A6 event reporting\n",
-          ctxt_pP->module_id, ctxt_pP->frame);
-    ReportConfig_A2->reportConfigId = 3;
-    ReportConfig_A2->reportConfig.present = ReportConfigToAddMod__reportConfig_PR_reportConfigEUTRA;
-    ReportConfig_A2->reportConfig.choice.reportConfigEUTRA.triggerType.present =
-      ReportConfigEUTRA__triggerType_PR_event;
-    ReportConfig_A2->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.present =
-      ReportConfigEUTRA__triggerType__event__eventId_PR_eventA2;
-    ReportConfig_A2->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.choice.
-    eventA2.a2_Threshold.present = ThresholdEUTRA_PR_threshold_RSRP;
-    ReportConfig_A2->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.choice.
-    eventA2.a2_Threshold.choice.threshold_RSRP = 10;
+  else {
 
-    ReportConfig_A2->reportConfig.choice.reportConfigEUTRA.triggerQuantity =
-      ReportConfigEUTRA__triggerQuantity_rsrp;
-    ReportConfig_A2->reportConfig.choice.reportConfigEUTRA.reportQuantity = ReportConfigEUTRA__reportQuantity_both;
-    ReportConfig_A2->reportConfig.choice.reportConfigEUTRA.maxReportCells = 2;
-    ReportConfig_A2->reportConfig.choice.reportConfigEUTRA.reportInterval = ReportInterval_ms120;
-    ReportConfig_A2->reportConfig.choice.reportConfigEUTRA.reportAmount = ReportConfigEUTRA__reportAmount_infinity;
+     LOG_E(FLEXRAN_AGENT, "There is something wrong on RRC agent!");
+  }
 
-    ASN_SEQUENCE_ADD(&ReportConfig_list->list, ReportConfig_A2);
 
-    ReportConfig_A3->reportConfigId = 4;
-    ReportConfig_A3->reportConfig.present = ReportConfigToAddMod__reportConfig_PR_reportConfigEUTRA;
-    ReportConfig_A3->reportConfig.choice.reportConfigEUTRA.triggerType.present =
-      ReportConfigEUTRA__triggerType_PR_event;
-    ReportConfig_A3->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.present =
-      ReportConfigEUTRA__triggerType__event__eventId_PR_eventA3;
 
-    ReportConfig_A3->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.choice.eventA3.a3_Offset = 1;   //10;
-    ReportConfig_A3->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.choice.
-    eventA3.reportOnLeave = 1;
+  ReportConfig_list = CALLOC(1, sizeof(*ReportConfig_list));
 
-    ReportConfig_A3->reportConfig.choice.reportConfigEUTRA.triggerQuantity =
-      ReportConfigEUTRA__triggerQuantity_rsrp;
-    ReportConfig_A3->reportConfig.choice.reportConfigEUTRA.reportQuantity = ReportConfigEUTRA__reportQuantity_both;
-    ReportConfig_A3->reportConfig.choice.reportConfigEUTRA.maxReportCells = 2;
-    ReportConfig_A3->reportConfig.choice.reportConfigEUTRA.reportInterval = ReportInterval_ms120;
-    ReportConfig_A3->reportConfig.choice.reportConfigEUTRA.reportAmount = ReportConfigEUTRA__reportAmount_infinity;
+  ReportConfig_per = CALLOC(1, sizeof(*ReportConfig_per));
 
-    ReportConfig_A3->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.hysteresis = 0.5; // FIXME ...hysteresis is of type long!
-    ReportConfig_A3->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.timeToTrigger =
-      TimeToTrigger_ms40;
-    ASN_SEQUENCE_ADD(&ReportConfig_list->list, ReportConfig_A3);
+    // Periodical Measurement Report
 
-    ReportConfig_A4->reportConfigId = 5;
-    ReportConfig_A4->reportConfig.present = ReportConfigToAddMod__reportConfig_PR_reportConfigEUTRA;
-    ReportConfig_A4->reportConfig.choice.reportConfigEUTRA.triggerType.present =
-      ReportConfigEUTRA__triggerType_PR_event;
-    ReportConfig_A4->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.present =
-      ReportConfigEUTRA__triggerType__event__eventId_PR_eventA4;
-    ReportConfig_A4->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.choice.
-    eventA4.a4_Threshold.present = ThresholdEUTRA_PR_threshold_RSRP;
-    ReportConfig_A4->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.choice.
-    eventA4.a4_Threshold.choice.threshold_RSRP = 10;
+  ReportConfig_per->reportConfigId = 1;
+  ReportConfig_per->reportConfig.present = ReportConfigToAddMod__reportConfig_PR_reportConfigEUTRA;
 
-    ReportConfig_A4->reportConfig.choice.reportConfigEUTRA.triggerQuantity =
-      ReportConfigEUTRA__triggerQuantity_rsrp;
-    ReportConfig_A4->reportConfig.choice.reportConfigEUTRA.reportQuantity = ReportConfigEUTRA__reportQuantity_both;
-    ReportConfig_A4->reportConfig.choice.reportConfigEUTRA.maxReportCells = 2;
-    ReportConfig_A4->reportConfig.choice.reportConfigEUTRA.reportInterval = ReportInterval_ms120;
-    ReportConfig_A4->reportConfig.choice.reportConfigEUTRA.reportAmount = ReportConfigEUTRA__reportAmount_infinity;
+    ReportConfig_per->reportConfig.choice.reportConfigEUTRA.triggerType.present =
+      ReportConfigEUTRA__triggerType_PR_periodical;
 
-    ASN_SEQUENCE_ADD(&ReportConfig_list->list, ReportConfig_A4);
+    ReportConfig_per->reportConfig.choice.reportConfigEUTRA.triggerType.choice.periodical.purpose =
+      ReportConfigEUTRA__triggerType__periodical__purpose_reportStrongestCells;
 
-    ReportConfig_A5->reportConfigId = 6;
-    ReportConfig_A5->reportConfig.present = ReportConfigToAddMod__reportConfig_PR_reportConfigEUTRA;
-    ReportConfig_A5->reportConfig.choice.reportConfigEUTRA.triggerType.present =
-      ReportConfigEUTRA__triggerType_PR_event;
-    ReportConfig_A5->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.present =
-      ReportConfigEUTRA__triggerType__event__eventId_PR_eventA5;
-    ReportConfig_A5->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.choice.
-    eventA5.a5_Threshold1.present = ThresholdEUTRA_PR_threshold_RSRP;
-    ReportConfig_A5->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.choice.
-    eventA5.a5_Threshold2.present = ThresholdEUTRA_PR_threshold_RSRP;
-    ReportConfig_A5->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.choice.
-    eventA5.a5_Threshold1.choice.threshold_RSRP = 10;
-    ReportConfig_A5->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.eventId.choice.
-    eventA5.a5_Threshold2.choice.threshold_RSRP = 10;
+    // ReportConfig_per->reportConfig.choice.reportConfigEUTRA.triggerType.choice.event.timeToTrigger = TimeToTrigger_ms40;  
+    ReportConfig_per->reportConfig.choice.reportConfigEUTRA.triggerQuantity = ReportConfigEUTRA__triggerQuantity_rsrp;
+   ReportConfig_per->reportConfig.choice.reportConfigEUTRA.reportQuantity = ReportConfigEUTRA__reportQuantity_both;
+   ReportConfig_per->reportConfig.choice.reportConfigEUTRA.maxReportCells = 2;
+   ReportConfig_per->reportConfig.choice.reportConfigEUTRA.reportInterval = trig_param->report_interval ;//ReportInterval_ms2048; // RRC counter frame- ms1024 is 1ms   
 
-    ReportConfig_A5->reportConfig.choice.reportConfigEUTRA.triggerQuantity =
-      ReportConfigEUTRA__triggerQuantity_rsrp;
-    ReportConfig_A5->reportConfig.choice.reportConfigEUTRA.reportQuantity = ReportConfigEUTRA__reportQuantity_both;
-    ReportConfig_A5->reportConfig.choice.reportConfigEUTRA.maxReportCells = 2;
-    ReportConfig_A5->reportConfig.choice.reportConfigEUTRA.reportInterval = ReportInterval_ms120;
-    ReportConfig_A5->reportConfig.choice.reportConfigEUTRA.reportAmount = ReportConfigEUTRA__reportAmount_infinity;
+   ReportConfig_per->reportConfig.choice.reportConfigEUTRA.reportAmount = trig_param->report_amount; //ReportConfigEUTRA__reportAmount_r2; // put r1 to see once, r2 for 2 times and ...
 
-    ASN_SEQUENCE_ADD(&ReportConfig_list->list, ReportConfig_A5);
-    //  rrcConnectionReconfiguration->criticalExtensions.choice.c1.choice.rrcConnectionReconfiguration_r8.measConfig->reportConfigToAddModList = ReportConfig_list;
 
-    rsrp = CALLOC(1, sizeof(RSRP_Range_t));
-    *rsrp = 20;
+  ASN_SEQUENCE_ADD(&ReportConfig_list->list, ReportConfig_per);
+
 
-    Sparams = CALLOC(1, sizeof(*Sparams));
-    Sparams->present = MeasConfig__speedStatePars_PR_setup;
-    Sparams->choice.setup.timeToTrigger_SF.sf_High = SpeedStateScaleFactors__sf_Medium_oDot75;
-    Sparams->choice.setup.timeToTrigger_SF.sf_Medium = SpeedStateScaleFactors__sf_High_oDot5;
-    Sparams->choice.setup.mobilityStateParameters.n_CellChangeHigh = 10;
-    Sparams->choice.setup.mobilityStateParameters.n_CellChangeMedium = 5;
-    Sparams->choice.setup.mobilityStateParameters.t_Evaluation = MobilityStateParameters__t_Evaluation_s60;
-    Sparams->choice.setup.mobilityStateParameters.t_HystNormal = MobilityStateParameters__t_HystNormal_s120;
 
     quantityConfig = CALLOC(1, sizeof(*quantityConfig));
     memset((void *)quantityConfig, 0, sizeof(*quantityConfig));
@@ -1993,30 +2614,7 @@ rrc_eNB_generate_defaultRRCConnectionReconfiguration(const protocol_ctxt_t* cons
     *quantityConfig->quantityConfigEUTRA->filterCoefficientRSRP = FilterCoefficient_fc4;
     *quantityConfig->quantityConfigEUTRA->filterCoefficientRSRQ = FilterCoefficient_fc4;
 
-    LOG_I(RRC,
-          "[eNB %d] Frame %d: potential handover preparation: store the information in an intermediate structure in case of failure\n",
-          ctxt_pP->module_id, ctxt_pP->frame);
-    // store the information in an intermediate structure for Hanodver management
-    //rrc_inst->handover_info.as_config.sourceRadioResourceConfig.srb_ToAddModList = CALLOC(1,sizeof());
-    ue_context_pP->ue_context.handover_info = CALLOC(1, sizeof(*(ue_context_pP->ue_context.handover_info)));
-    //memcpy((void *)rrc_inst->handover_info[ue_mod_idP]->as_config.sourceRadioResourceConfig.srb_ToAddModList,(void *)SRB_list,sizeof(SRB_ToAddModList_t));
-    ue_context_pP->ue_context.handover_info->as_config.sourceRadioResourceConfig.srb_ToAddModList = *SRB_configList2;
-    //memcpy((void *)rrc_inst->handover_info[ue_mod_idP]->as_config.sourceRadioResourceConfig.drb_ToAddModList,(void *)DRB_list,sizeof(DRB_ToAddModList_t));
-    ue_context_pP->ue_context.handover_info->as_config.sourceRadioResourceConfig.drb_ToAddModList = *DRB_configList;
-    ue_context_pP->ue_context.handover_info->as_config.sourceRadioResourceConfig.drb_ToReleaseList = NULL;
-    ue_context_pP->ue_context.handover_info->as_config.sourceRadioResourceConfig.mac_MainConfig =
-      CALLOC(1, sizeof(*ue_context_pP->ue_context.handover_info->as_config.sourceRadioResourceConfig.mac_MainConfig));
-    memcpy((void*)ue_context_pP->ue_context.handover_info->as_config.sourceRadioResourceConfig.mac_MainConfig,
-           (void *)mac_MainConfig, sizeof(MAC_MainConfig_t));
-    ue_context_pP->ue_context.handover_info->as_config.sourceRadioResourceConfig.physicalConfigDedicated =
-      CALLOC(1, sizeof(PhysicalConfigDedicated_t));
-    memcpy((void*)ue_context_pP->ue_context.handover_info->as_config.sourceRadioResourceConfig.physicalConfigDedicated,
-           (void*)ue_context_pP->ue_context.physicalConfigDedicated, sizeof(PhysicalConfigDedicated_t));
-    ue_context_pP->ue_context.handover_info->as_config.sourceRadioResourceConfig.sps_Config = NULL;
-    //memcpy((void *)rrc_inst->handover_info[ue_mod_idP]->as_config.sourceRadioResourceConfig.sps_Config,(void *)rrc_inst->sps_Config[ue_mod_idP],sizeof(SPS_Config_t));
-
-  }
-
+  
 #if defined(ENABLE_ITTI)
   /* Initialize NAS list */
   dedicatedInfoNASList = CALLOC(1, sizeof(struct RRCConnectionReconfiguration_r8_IEs__dedicatedInfoNASList));
@@ -2027,22 +2625,22 @@ rrc_eNB_generate_defaultRRCConnectionReconfiguration(const protocol_ctxt_t* cons
       dedicatedInfoNas = CALLOC(1, sizeof(DedicatedInfoNAS_t));
       memset(dedicatedInfoNas, 0, sizeof(OCTET_STRING_t));
       OCTET_STRING_fromBuf(dedicatedInfoNas, 
-			   (char*)ue_context_pP->ue_context.e_rab[i].param.nas_pdu.buffer,
+         (char*)ue_context_pP->ue_context.e_rab[i].param.nas_pdu.buffer,
                            ue_context_pP->ue_context.e_rab[i].param.nas_pdu.length);
       ASN_SEQUENCE_ADD(&dedicatedInfoNASList->list, dedicatedInfoNas);
     }
 
     /* TODO parameters yet to process ... */
-    {
+    // {
       //      ue_context_pP->ue_context.e_rab[i].param.qos;
       //      ue_context_pP->ue_context.e_rab[i].param.sgw_addr;
       //      ue_context_pP->ue_context.e_rab[i].param.gtp_teid;
-    }
+    // }
 
     /* TODO should test if e RAB are Ok before! */
     ue_context_pP->ue_context.e_rab[i].status = E_RAB_STATUS_DONE;
     LOG_D(RRC, "setting the status for the default DRB (index %d) to (%d,%s)\n", 
-	  i, ue_context_pP->ue_context.e_rab[i].status, "E_RAB_STATUS_DONE");
+    i, ue_context_pP->ue_context.e_rab[i].status, "E_RAB_STATUS_DONE");
   }
 
   /* If list is empty free the list and reset the address */
@@ -2054,23 +2652,23 @@ rrc_eNB_generate_defaultRRCConnectionReconfiguration(const protocol_ctxt_t* cons
 #endif
 
   memset(buffer, 0, RRC_BUF_SIZE);
-
+  
   size = do_RRCConnectionReconfiguration(ctxt_pP,
                                          buffer,
                                          xid,   //Transaction_id,
-                                         (SRB_ToAddModList_t*)*SRB_configList2, // SRB_configList
-                                         (DRB_ToAddModList_t*)*DRB_configList,
+                                         (SRB_ToAddModList_t*)NULL, // SRB_configList
+                                         (DRB_ToAddModList_t*)NULL,
                                          (DRB_ToReleaseList_t*)NULL,  // DRB2_list,
                                          (struct SPS_Config*)NULL,    // *sps_Config,
                                          (struct PhysicalConfigDedicated*)*physicalConfigDedicated,
-#ifdef EXMIMO_IOT
-                                         NULL, NULL, NULL,NULL,
-#else
+// #ifdef EXMIMO_IOT
+//                                          NULL, NULL, NULL,NULL,
+// #else
                                          (MeasObjectToAddModList_t*)MeasObj_list,
                                          (ReportConfigToAddModList_t*)ReportConfig_list,
                                          (QuantityConfig_t*)quantityConfig,
                                          (MeasIdToAddModList_t*)MeasId_list,
-#endif
+// #endif
                                          (MAC_MainConfig_t*)mac_MainConfig,
                                          (MeasGapConfig_t*)NULL,
                                          (MobilityControlInfo_t*)NULL,
@@ -2125,15 +2723,16 @@ rrc_eNB_generate_defaultRRCConnectionReconfiguration(const protocol_ctxt_t* cons
     size);
 
   rrc_data_req(
-	       ctxt_pP,
-	       DCCH,
-	       rrc_eNB_mui++,
-	       SDU_CONFIRM_NO,
-	       size,
-	       buffer,
-	       PDCP_TRANSMISSION_MODE_CONTROL);
+         ctxt_pP,
+         DCCH,
+         rrc_eNB_mui++,
+         SDU_CONFIRM_NO,
+         size,
+         buffer,
+         PDCP_TRANSMISSION_MODE_CONTROL);
 }
 
+#endif
 
 
 //-----------------------------------------------------------------------------
@@ -2217,46 +2816,72 @@ rrc_eNB_generate_RRCConnectionReconfiguration_SCell(
 void
 rrc_eNB_process_MeasurementReport(
   const protocol_ctxt_t* const ctxt_pP,
-  rrc_eNB_ue_context_t*          const ue_context_pP,
+  rrc_eNB_ue_context_t*         ue_context_pP,
   const MeasResults_t*   const measResults2
 )
 //-----------------------------------------------------------------------------
 {
+  int i=0;
+  int neighboring_cells=-1;
+  
   T(T_ENB_RRC_MEASUREMENT_REPORT, T_INT(ctxt_pP->module_id), T_INT(ctxt_pP->frame),
     T_INT(ctxt_pP->subframe), T_INT(ctxt_pP->rnti));
 
+  if (measResults2 == NULL )
+    return;
+  
+  if (measResults2->measId > 0 ){
+     if (ue_context_pP->ue_context.measResults == NULL) {
+       ue_context_pP->ue_context.measResults = CALLOC(1, sizeof(MeasResults_t));
+     }
+     ue_context_pP->ue_context.measResults->measId=measResults2->measId; 
+     ue_context_pP->ue_context.measResults->measResultPCell.rsrpResult=measResults2->measResultPCell.rsrpResult;
+     ue_context_pP->ue_context.measResults->measResultPCell.rsrqResult=measResults2->measResultPCell.rsrqResult;
+     LOG_D(RRC, "[eNB %d]Frame %d: UE %x (Measurement Id %d): RSRP of Source %ld\n", ctxt_pP->module_id, ctxt_pP->frame, ctxt_pP->rnti, (int)measResults2->measId, ue_context_pP->ue_context.measResults->measResultPCell.rsrpResult-140);
+     LOG_D(RRC, "[eNB %d]Frame %d: UE %x (Measurement Id %d): RSRQ of Source %ld\n", ctxt_pP->module_id, ctxt_pP->frame, ctxt_pP->rnti, (int)measResults2->measId, ue_context_pP->ue_context.measResults->measResultPCell.rsrqResult/2 - 20);
+   }
+   if (measResults2->measResultNeighCells == NULL)
+     return;
+
+   if (measResults2->measResultNeighCells->choice.measResultListEUTRA.list.count > 0) {
+     neighboring_cells = measResults2->measResultNeighCells->choice.measResultListEUTRA.list.count;
+     
+     if (ue_context_pP->ue_context.measResults->measResultNeighCells == NULL) {
+       
+       ue_context_pP->ue_context.measResults->measResultNeighCells = CALLOC(1, sizeof(*measResults2->measResultNeighCells)*neighboring_cells);
+     }
+     ue_context_pP->ue_context.measResults->measResultNeighCells->choice.measResultListEUTRA.list.count = neighboring_cells;
+     for (i=0; i < neighboring_cells; i++){
+       memcpy (ue_context_pP->ue_context.measResults->measResultNeighCells->choice.measResultListEUTRA.list.array[i],
+	       measResults2->measResultNeighCells->choice.measResultListEUTRA.list.array[i],
+	       sizeof(MeasResultListEUTRA_t));
+       
+       LOG_D(RRC, "Physical Cell Id %d\n",
+	     (int)ue_context_pP->ue_context.measResults->measResultNeighCells->choice.measResultListEUTRA.list.array[i]->physCellId);
+       LOG_D(RRC, "RSRP of Target %d\n",
+	     (int)*(ue_context_pP->ue_context.measResults->measResultNeighCells->choice.measResultListEUTRA.list.array[i]->measResult.rsrpResult));
+       LOG_D(RRC, "RSRQ of Target %d\n",
+	     (int)*(ue_context_pP->ue_context.measResults->measResultNeighCells->choice.measResultListEUTRA.list.array[i]->measResult.rsrqResult));
+     }
+   }
 
-  LOG_I(RRC, "[eNB %d] Frame %d: Process Measurement Report From UE %x (Measurement Id %d)\n",
-        ctxt_pP->module_id, ctxt_pP->frame, ctxt_pP->rnti, (int)measResults2->measId);
-
-  if (measResults2->measResultNeighCells->choice.measResultListEUTRA.list.count > 0) {
-    LOG_I(RRC, "Physical Cell Id %d\n",
-          (int)measResults2->measResultNeighCells->choice.measResultListEUTRA.list.array[0]->physCellId);
-    LOG_I(RRC, "RSRP of Target %d\n",
-          (int)*(measResults2->measResultNeighCells->choice.measResultListEUTRA.list.array[0]->
-                 measResult.rsrpResult));
-    LOG_I(RRC, "RSRQ of Target %d\n",
-          (int)*(measResults2->measResultNeighCells->choice.measResultListEUTRA.list.array[0]->
-                 measResult.rsrqResult));
-  }
-
-#if defined(Rel10) || defined(Rel14)
-  LOG_I(RRC, "RSRP of Source %ld\n", measResults2->measResultPCell.rsrpResult);
-  LOG_I(RRC, "RSRQ of Source %ld\n", measResults2->measResultPCell.rsrqResult);
-#else
-  LOG_I(RRC, "RSRP of Source %ld\n", measResults2->measResultServCell.rsrpResult);
-  LOG_I(RRC, "RSRQ of Source %ld\n", measResults2->measResultServCell.rsrqResult);
-#endif
+// #if defined(Rel10) || defined(Rel14)
 
-  if (ue_context_pP->ue_context.handover_info->ho_prepare != 0xF0) {
-    rrc_eNB_generate_HandoverPreparationInformation(ctxt_pP,
-        ue_context_pP,
-        measResults2->measResultNeighCells->choice.
-        measResultListEUTRA.list.array[0]->physCellId);
-  } else {
-    LOG_D(RRC, "[eNB %d] Frame %d: Ignoring MeasReport from UE %x as Handover is in progress... \n", ctxt_pP->module_id, ctxt_pP->frame,
-          ctxt_pP->rnti);
-  }
+  
+// #else
+  // LOG_I(RRC, "RSRP of Source %d\n", measResults2->measResultServCell.rsrpResult);
+  // LOG_I(RRC, "RSRQ of Source %d\n", measResults2->measResultServCell.rsrqResult);
+// #endif
+
+  // if (ue_context_pP->ue_context.handover_info->ho_prepare != 0xF0) {
+  //   rrc_eNB_generate_HandoverPreparationInformation(ctxt_pP,
+  //       ue_context_pP,
+  //       measResults2->measResultNeighCells->choice.
+  //       measResultListEUTRA.list.array[0]->physCellId);
+  // } else {
+  //   LOG_D(RRC, "[eNB %d] Frame %d: Ignoring MeasReport from UE %x as Handover is in progress... \n", ctxt_pP->module_id, ctxt_pP->frame,
+  //         ctxt_pP->rnti);
+  // }
 
   //Look for IP address of the target eNB
   //Send Handover Request -> target eNB
@@ -4256,6 +4881,13 @@ rrc_eNB_decode_ccch(
 
         } else {
           // no context available
+#if defined(FLEXRAN_AGENT_SB_IF)
+	  if (rrc_agent_registered[ctxt_pP->module_id]) {
+	    agent_rrc_xface[ctxt_pP->module_id]->flexran_agent_notify_ue_state_change(ctxt_pP->module_id,
+										      ctxt_pP->rnti,
+										      PROTOCOL__FLEX_UE_STATE_CHANGE_TYPE__FLUESC_DEACTIVATED);
+	  }
+#endif
           LOG_I(RRC, PROTOCOL_RRC_CTXT_UE_FMT" Can't create new context for UE random UE identity (0x%" PRIx64 ")\n",
                 PROTOCOL_RRC_CTXT_UE_ARGS(ctxt_pP),
                 random_value);
@@ -4514,8 +5146,8 @@ rrc_eNB_decode_dcch(
 
 #if defined(FLEXRAN_AGENT_SB_IF)
 	//WARNING:Inform the controller about the UE activation. Should be moved to RRC agent in the future
-	if (mac_agent_registered[ctxt_pP->module_id]) {
-	  agent_mac_xface[ctxt_pP->eNB_index]->flexran_agent_notify_ue_state_change(ctxt_pP->module_id,
+	if (rrc_agent_registered[ctxt_pP->module_id]) {
+	  agent_rrc_xface[ctxt_pP->eNB_index]->flexran_agent_notify_ue_state_change(ctxt_pP->module_id,
 										ue_context_p->ue_id_rnti,
 										PROTOCOL__FLEX_UE_STATE_CHANGE_TYPE__FLUESC_UPDATED);
 	}
@@ -4618,8 +5250,8 @@ rrc_eNB_decode_dcch(
 	  
 #if defined(FLEXRAN_AGENT_SB_IF)
 	  //WARNING:Inform the controller about the UE activation. Should be moved to RRC agent in the future
-	  if (mac_agent_registered[ctxt_pP->module_id]) {
-	    agent_mac_xface[ctxt_pP->eNB_index]->flexran_agent_notify_ue_state_change(ctxt_pP->module_id,
+	  if (rrc_agent_registered[ctxt_pP->module_id]) {
+	    agent_rrc_xface[ctxt_pP->eNB_index]->flexran_agent_notify_ue_state_change(ctxt_pP->module_id,
 										  ue_context_p->ue_id_rnti,
 										  PROTOCOL__FLEX_UE_STATE_CHANGE_TYPE__FLUESC_ACTIVATED);
 	  }
@@ -4951,6 +5583,7 @@ rrc_enb_task(
 
     switch (ITTI_MSG_ID(msg_p)) {
     case TERMINATE_MESSAGE:
+      LOG_W(RRC, " *** Exiting RRC thread\n");
       itti_exit_task();
       break;
 
diff --git a/openair2/UTIL/ASYNC_IF/ringbuffer_queue.c b/openair2/UTIL/ASYNC_IF/ringbuffer_queue.c
index 1a3701ed5cc043ccb69b4c6c8a7b899158cb6409..b178d3a5d665d7d2864f762a2a39e3b7888cf2bd 100644
--- a/openair2/UTIL/ASYNC_IF/ringbuffer_queue.c
+++ b/openair2/UTIL/ASYNC_IF/ringbuffer_queue.c
@@ -117,7 +117,7 @@ int message_get(message_queue_t *queue, void **data, int *size, int *priority) {
   return 0;
 }
 
-message_queue_t destroy_message_queue(message_queue_t *queue) {
+void destroy_message_queue(message_queue_t *queue) {
   struct lfds700_misc_prng_state ls;
 
   message_t *m;
diff --git a/openair2/UTIL/ASYNC_IF/ringbuffer_queue.h b/openair2/UTIL/ASYNC_IF/ringbuffer_queue.h
index 185d23daf59d136e69c9293f9ffac722fb210047..04414cbbb2b9618379ad1284a056943e04539c23 100644
--- a/openair2/UTIL/ASYNC_IF/ringbuffer_queue.h
+++ b/openair2/UTIL/ASYNC_IF/ringbuffer_queue.h
@@ -48,6 +48,6 @@ typedef struct {
 message_queue_t * new_message_queue(int size);
 int message_put(message_queue_t *queue, void *data, int size, int priority);
 int message_get(message_queue_t *queue, void **data, int *size, int *priority);
-message_queue_t destroy_message_queue(message_queue_t *queue);
+void destroy_message_queue(message_queue_t *queue);
 
 #endif /* RINGBUFFER_QUEUE_H */
diff --git a/openair2/X2AP/x2ap.c b/openair2/X2AP/x2ap.c
index bde21c0dbe1e57cc0d5abeac07d3f5a9b2e8fc8d..8002867e15c31c8b78ada0894c9bbef20ae2cef1 100644
--- a/openair2/X2AP/x2ap.c
+++ b/openair2/X2AP/x2ap.c
@@ -49,6 +49,7 @@ void *x2ap_task(void *arg)
 
     switch (ITTI_MSG_ID(received_msg)) {
     case TERMINATE_MESSAGE:
+      X2AP_WARN(" *** Exiting X2AP thread\n");
       itti_exit_task();
       break;
 
diff --git a/openair3/GTPV1-U/gtpv1u_eNB.c b/openair3/GTPV1-U/gtpv1u_eNB.c
index f70fe9cf2b8120f9e369a8bc44abf343d8f26b08..6c562e0d86a9b14166b71be6a19fff8758b3259b 100644
--- a/openair3/GTPV1-U/gtpv1u_eNB.c
+++ b/openair3/GTPV1-U/gtpv1u_eNB.c
@@ -1136,6 +1136,7 @@ void *gtpv1u_eNB_task(void *args)
         hashtable_destroy (RC.gtpv1u_data_g->teid_mapping);
       }
 
+      LOG_W(GTPU, " *** Exiting GTPU thread\n");
       itti_exit_task();
     }
     break;
diff --git a/openair3/GTPV1-U/gtpv1u_task.c b/openair3/GTPV1-U/gtpv1u_task.c
index a6dd6fa06151ae08e6373e5d78d9005bbd37db6d..287c22b7e7ab28d162f6b36815b11eb14b629588 100644
--- a/openair3/GTPV1-U/gtpv1u_task.c
+++ b/openair3/GTPV1-U/gtpv1u_task.c
@@ -423,6 +423,7 @@ static void *gtpv1u_thread(void *args)
     switch (ITTI_MSG_ID(received_message_p)) {
 
     case TERMINATE_MESSAGE: {
+      GTPU_WARN(" *** Exiting GTPU thread\n");
       itti_exit_task();
     }
     break;
diff --git a/openair3/S1AP/s1ap_eNB.c b/openair3/S1AP/s1ap_eNB.c
index 08a18b629e0f58ccd075247f83c8832885a78230..cd8d3544ab12bddfb5c12ff2925e3dd5069ab188 100644
--- a/openair3/S1AP/s1ap_eNB.c
+++ b/openair3/S1AP/s1ap_eNB.c
@@ -310,6 +310,7 @@ void *s1ap_eNB_task(void *arg)
 
     switch (ITTI_MSG_ID(received_msg)) {
     case TERMINATE_MESSAGE:
+      S1AP_WARN(" *** Exiting S1AP thread\n");
       itti_exit_task();
       break;
 
diff --git a/openair3/SCTP/sctp_eNB_task.c b/openair3/SCTP/sctp_eNB_task.c
index 7771cab712f22b747f7dbc451e98c01495250004..256bee0cd12ecca1d8c8cd28a42f105e745da12d 100644
--- a/openair3/SCTP/sctp_eNB_task.c
+++ b/openair3/SCTP/sctp_eNB_task.c
@@ -841,6 +841,7 @@ void *sctp_eNB_task(void *arg)
         break;
 
       case TERMINATE_MESSAGE:
+        SCTP_WARN("*** Exiting SCTP thread\n");
         itti_exit_task();
         break;
 
diff --git a/openair3/TEST/EPC_TEST/play_scenario_s1ap.c b/openair3/TEST/EPC_TEST/play_scenario_s1ap.c
index f10126d5b55928aaba1641fc24c606e1e4fabf32..95df0fc306c0bf2ee72ca6275da11363166f693e 100644
--- a/openair3/TEST/EPC_TEST/play_scenario_s1ap.c
+++ b/openair3/TEST/EPC_TEST/play_scenario_s1ap.c
@@ -1089,6 +1089,7 @@ void *et_s1ap_eNB_task(void *arg)
 
     switch (ITTI_MSG_ID(received_msg)) {
     case TERMINATE_MESSAGE:
+      S1AP_WARN("*** Exiting S1AP thread\n");
       itti_exit_task();
       break;
 
diff --git a/openair3/UDP/udp_eNB_task.c b/openair3/UDP/udp_eNB_task.c
index bd7b804a67e633abc9ca966932c0073dcbb2f772..2d33eb117e3beb20411db91e55706b771bf7d708 100644
--- a/openair3/UDP/udp_eNB_task.c
+++ b/openair3/UDP/udp_eNB_task.c
@@ -389,7 +389,7 @@ void *udp_eNB_task(void *args_p)
       break;
 
       case TERMINATE_MESSAGE: {
-        LOG_W(UDP_, "Received TERMINATE_MESSAGE\n");
+        LOG_W(UDP_, " *** Exiting UDP thread\n");
         itti_exit_task();
       }
       break;
diff --git a/targets/RT/USER/lte-enb.c b/targets/RT/USER/lte-enb.c
index 33e6b0684b4cb4d595bd855723ae698076d73985..0626ad772598451290cd4facfd90eb01e1239fa8 100644
--- a/targets/RT/USER/lte-enb.c
+++ b/targets/RT/USER/lte-enb.c
@@ -239,7 +239,9 @@ static void* eNB_thread_rxtx( void* param ) {
 
   VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME( VCD_SIGNAL_DUMPER_FUNCTIONS_eNB_PROC_RXTX0+(proc->subframe_rx&1), 0 );
 
-  printf( "Exiting eNB thread RXn_TXnp4\n");
+#ifdef DEBUG_THREADS
+  printf(" *** Exiting eNB thread RXn_TXnp4\n");
+#endif
 
   eNB_thread_rxtx_status = 0;
   return &eNB_thread_rxtx_status;
@@ -622,6 +624,8 @@ void init_eNB_proc(int inst) {
     pthread_mutex_init( &proc->mutex_asynch_rxtx, NULL);
     pthread_mutex_init( &proc->mutex_RU,NULL);
     pthread_mutex_init( &proc->mutex_RU_PRACH,NULL);
+    pthread_mutex_init( &proc->mutex_synch,NULL);
+    pthread_mutex_init( &proc->mutex_FH, NULL);
 
     pthread_cond_init( &proc->cond_prach, NULL);
     pthread_cond_init( &proc->cond_asynch_rxtx, NULL);
@@ -712,20 +716,34 @@ void kill_eNB_proc(int inst) {
     
     proc = &eNB->proc;
     proc_rxtx = &proc->proc_rxtx[0];
-    
 
     LOG_I(PHY, "Killing TX CC_id %d inst %d\n", CC_id, inst );
 
     if (eNB->single_thread_flag==0) {
-      proc_rxtx[0].instance_cnt_rxtx = 0; // FIXME data race!
-      proc_rxtx[1].instance_cnt_rxtx = 0; // FIXME data race!
-      pthread_cond_signal( &proc_rxtx[0].cond_rxtx );    
-      pthread_cond_signal( &proc_rxtx[1].cond_rxtx );
+      pthread_mutex_lock(&proc_rxtx[0].mutex_rxtx);
+      proc_rxtx[0].instance_cnt_rxtx = 0;
+      pthread_mutex_unlock(&proc_rxtx[0].mutex_rxtx);
+      pthread_mutex_lock(&proc_rxtx[1].mutex_rxtx);
+      proc_rxtx[1].instance_cnt_rxtx = 0;
+      pthread_mutex_unlock(&proc_rxtx[1].mutex_rxtx);
     }
+    pthread_mutex_lock(&PHY_vars_eNB_g[0][CC_id]->proc.mutex_synch);
+    PHY_vars_eNB_g[0][CC_id]->proc.instance_cnt_synch = 1;
+    pthread_mutex_unlock(&PHY_vars_eNB_g[0][CC_id]->proc.mutex_synch);
     proc->instance_cnt_prach = 0;
     pthread_cond_signal( &proc->cond_prach );
 
+    pthread_cond_signal( &proc->cond_FH );
+    pthread_cond_signal( &proc->cond_asynch_rxtx );
+    pthread_cond_signal( &proc->cond_synch );
     pthread_cond_broadcast(&sync_phy_proc.cond_phy_proc_tx);
+
+    LOG_D(PHY, "joining pthread_FH\n");
+    pthread_join( proc->pthread_FH, (void**)&status ); 
+    pthread_mutex_destroy( &proc->mutex_FH );
+    pthread_cond_destroy( &proc->cond_FH );
+            
+    LOG_D(PHY, "joining pthread_prach\n");
     pthread_join( proc->pthread_prach, (void**)&status );    
 
     LOG_I(PHY, "Destroying prach mutex/cond\n");
@@ -750,6 +768,20 @@ void kill_eNB_proc(int inst) {
 	pthread_cond_destroy( &proc_rxtx[i].cond_rxtx );
       }
     }
+
+    LOG_D(PHY, "joining pthread_asynch_rxtx\n");
+    pthread_join(proc->pthread_asynch_rxtx, (void**)&status );
+    pthread_mutex_destroy(&proc->mutex_asynch_rxtx);
+    pthread_cond_destroy(&proc->cond_asynch_rxtx);
+
+    LOG_D(PHY, "joining pthread_single\n");
+    pthread_join(proc->pthread_single, (void**)&status );
+
+    LOG_D(PHY, "joining pthread_synch\n");
+    pthread_join(proc->pthread_synch, (void**)&status );
+    pthread_mutex_destroy(&proc->mutex_synch);
+    pthread_cond_destroy(&proc->cond_synch);
+    LOG_D(PHY, "joined all threads\n");
   }
 }
 
diff --git a/targets/RT/USER/lte-softmodem.c b/targets/RT/USER/lte-softmodem.c
index e90fc4335c5edd68369163e1cde3fcc9f474dc0b..ed1e70868931b3d50401a2b40fd2cf2cee6ad5c5 100644
--- a/targets/RT/USER/lte-softmodem.c
+++ b/targets/RT/USER/lte-softmodem.c
@@ -229,6 +229,8 @@ uint8_t abstraction_flag=0;
 
 /* forward declarations */
 void set_default_frame_parms(LTE_DL_FRAME_PARMS *frame_parms[MAX_NUM_CCs]);
+/* override the enb configuration parameters */
+static void reconfigure_enb_params(int enb_id);
 
 /*---------------------BMC: timespec helpers -----------------------------*/
 
@@ -506,6 +508,7 @@ void *l2l1_task(void *arg) {
       case TERMINATE_MESSAGE:
 	printf("received terminate message\n");
 	oai_exit=1;
+        start_eNB = 0;
 	itti_exit_task ();
 	break;
 
@@ -688,6 +691,54 @@ static void get_options(void) {
 }
 
 
+static void reconfigure_enb_params(int enb_id)
+{
+  int CC_id, k;
+  const Enb_properties_array_t *enb_properties=enb_config_get();
+
+  for (CC_id=0; CC_id<MAX_NUM_CCs; CC_id++) {
+
+    node_function[CC_id]  = enb_properties->properties[enb_id]->cc_node_function[CC_id];
+    node_timing[CC_id]    = enb_properties->properties[enb_id]->cc_node_timing[CC_id];
+    node_synch_ref[CC_id] = enb_properties->properties[enb_id]->cc_node_synch_ref[CC_id];
+
+    frame_parms[CC_id]->frame_type   = enb_properties->properties[enb_id]->frame_type[CC_id];
+    frame_parms[CC_id]->tdd_config   = enb_properties->properties[enb_id]->tdd_config[CC_id];
+    frame_parms[CC_id]->tdd_config_S = enb_properties->properties[enb_id]->tdd_config_s[CC_id];
+    frame_parms[CC_id]->Ncp          = enb_properties->properties[enb_id]->prefix_type[CC_id];
+
+                //for (j=0; j < enb_properties->properties[i]->nb_cc; j++ ){
+    frame_parms[CC_id]->Nid_cell             = enb_properties->properties[enb_id]->Nid_cell[CC_id];
+    frame_parms[CC_id]->N_RB_DL              = enb_properties->properties[enb_id]->N_RB_DL[CC_id];
+    frame_parms[CC_id]->N_RB_UL              = enb_properties->properties[enb_id]->N_RB_DL[CC_id];
+    frame_parms[CC_id]->nb_antennas_tx       = enb_properties->properties[enb_id]->nb_antennas_tx[CC_id];
+    frame_parms[CC_id]->nb_antenna_ports_eNB = enb_properties->properties[enb_id]->nb_antenna_ports[CC_id];
+    frame_parms[CC_id]->nb_antennas_rx       = enb_properties->properties[enb_id]->nb_antennas_rx[CC_id];
+
+    frame_parms[CC_id]->prach_config_common.prach_ConfigInfo.prach_ConfigIndex = enb_properties->properties[enb_id]->prach_config_index[CC_id];
+    frame_parms[CC_id]->prach_config_common.prach_ConfigInfo.prach_FreqOffset  = enb_properties->properties[enb_id]->prach_freq_offset[CC_id];
+
+    frame_parms[CC_id]->mode1_flag      = (frame_parms[CC_id]->nb_antenna_ports_eNB == 1) ? 1 : 0;
+    frame_parms[CC_id]->threequarter_fs = threequarter_fs;
+
+    for (k = 0 ; k < 4; k++) {
+      downlink_frequency[CC_id][k]      =  enb_properties->properties[enb_id]->downlink_frequency[CC_id];
+      uplink_frequency_offset[CC_id][k] =  enb_properties->properties[enb_id]->uplink_frequency_offset[CC_id];
+      rx_gain[CC_id][k]                 =  (double)enb_properties->properties[enb_id]->rx_gain[CC_id];
+      tx_gain[CC_id][k]                 =  (double)enb_properties->properties[enb_id]->tx_gain[CC_id];
+    }
+
+    printf("Downlink frequency/ uplink offset of CC_id %d set to %ju/%d\n", CC_id,
+           enb_properties->properties[enb_id]->downlink_frequency[CC_id],
+           enb_properties->properties[enb_id]->uplink_frequency_offset[CC_id]);
+
+    init_ul_hopping(frame_parms[CC_id]);
+    init_frame_parms(frame_parms[CC_id],1);
+    //   phy_init_top(frame_parms[CC_id]);
+    phy_init_lte_top(frame_parms[CC_id]);
+  } // CC_id
+}
+
 #if T_TRACER
 int T_nowait = 0;     /* by default we wait for the tracer */
 int T_port = 2021;    /* default port to listen to to wait for the tracer */
@@ -836,7 +887,6 @@ void init_openair0() {
   }
 }
 
-
 void wait_RUs(void) {
 
   LOG_I(PHY,"Waiting for RUs to be configured ...\n");
@@ -873,6 +923,191 @@ void wait_eNBs(void) {
   printf("eNB L1 are configured\n");
 }
 
+void fill_PHY_vars_eNB_g(uint8_t abstraction_flag, uint8_t beta_ACK, uint8_t beta_RI, uint8_t beta_CQI)
+{
+  int CC_id, i, j, k, re;
+  for (CC_id = 0; CC_id < MAX_NUM_CCs; CC_id++) {
+    PHY_vars_eNB_g[0][CC_id] = init_lte_eNB(frame_parms[CC_id],
+                                            0,
+                                            frame_parms[CC_id]->Nid_cell,
+                                            node_function[CC_id],
+                                            abstraction_flag);
+    PHY_vars_eNB_g[0][CC_id]->ue_dl_rb_alloc = 0x1fff;
+    PHY_vars_eNB_g[0][CC_id]->target_ue_dl_mcs = target_dl_mcs;
+    PHY_vars_eNB_g[0][CC_id]->ue_ul_nb_rb = 6;
+    PHY_vars_eNB_g[0][CC_id]->target_ue_ul_mcs = target_ul_mcs;
+    // initialization for phy-test
+    for (k = 0; k < NUMBER_OF_UE_MAX; k++) {
+      PHY_vars_eNB_g[0][CC_id]->transmission_mode[k] = transmission_mode;
+      if (transmission_mode == 7)
+        lte_gold_ue_spec_port5(PHY_vars_eNB_g[0][CC_id]->lte_gold_uespec_port5_table[k],
+                               frame_parms[CC_id]->Nid_cell,
+                               0x1235+k);
+    }
+    if ((transmission_mode == 1) || (transmission_mode == 7)) {
+      for (j = 0; j < frame_parms[CC_id]->nb_antennas_tx; j++)
+        for (re = 0; re < frame_parms[CC_id]->ofdm_symbol_size; re++)
+          PHY_vars_eNB_g[0][CC_id]->common_vars.beam_weights[0][0][j][re] = 0x00007fff / frame_parms[CC_id]->nb_antennas_tx;
+    }
+
+    if (phy_test==1)
+      PHY_vars_eNB_g[0][CC_id]->mac_enabled = 0;
+    else
+      PHY_vars_eNB_g[0][CC_id]->mac_enabled = 1;
+
+    if (PHY_vars_eNB_g[0][CC_id]->mac_enabled == 0) { //set default parameters for testing mode
+      for (i = 0; i < NUMBER_OF_UE_MAX; i++) {
+        PHY_vars_eNB_g[0][CC_id]->pusch_config_dedicated[i].betaOffset_ACK_Index = beta_ACK;
+        PHY_vars_eNB_g[0][CC_id]->pusch_config_dedicated[i].betaOffset_RI_Index  = beta_RI;
+        PHY_vars_eNB_g[0][CC_id]->pusch_config_dedicated[i].betaOffset_CQI_Index = beta_CQI;
+
+        PHY_vars_eNB_g[0][CC_id]->scheduling_request_config[i].sr_PUCCH_ResourceIndex = i;
+        PHY_vars_eNB_g[0][CC_id]->scheduling_request_config[i].sr_ConfigIndex = 7+(i%3);
+        PHY_vars_eNB_g[0][CC_id]->scheduling_request_config[i].dsr_TransMax = sr_n4;
+      }
+    }
+
+    compute_prach_seq(&PHY_vars_eNB_g[0][CC_id]->frame_parms.prach_config_common,
+                      PHY_vars_eNB_g[0][CC_id]->frame_parms.frame_type,
+                      PHY_vars_eNB_g[0][CC_id]->X_u);
+
+
+    PHY_vars_eNB_g[0][CC_id]->rx_total_gain_dB = (int)rx_gain[CC_id][0];
+
+    if (frame_parms[CC_id]->frame_type == FDD) {
+        PHY_vars_eNB_g[0][CC_id]->N_TA_offset = 0;
+    } else {
+        if (frame_parms[CC_id]->N_RB_DL == 100)
+            PHY_vars_eNB_g[0][CC_id]->N_TA_offset = 624;
+        else if (frame_parms[CC_id]->N_RB_DL == 50)
+            PHY_vars_eNB_g[0][CC_id]->N_TA_offset = 624/2;
+        else if (frame_parms[CC_id]->N_RB_DL == 25)
+            PHY_vars_eNB_g[0][CC_id]->N_TA_offset = 624/4;
+    }
+  }
+}
+
+#if defined(ENABLE_ITTI) && defined(FLEXRAN_AGENT_SB_IF)
+/*
+ * helper function to terminate a certain ITTI task
+ */
+void terminate_task(task_id_t task_id, mid_t mod_id)
+{
+  LOG_I(ENB_APP, "sending TERMINATE_MESSAGE to task %s (%d)\n", itti_get_task_name(task_id), task_id);
+  MessageDef *msg;
+  msg = itti_alloc_new_message (ENB_APP, TERMINATE_MESSAGE);
+  itti_send_msg_to_task (task_id, ENB_MODULE_ID_TO_INSTANCE(mod_id), msg);
+}
+
+int stop_L1L2(int enb_id)
+{
+  int CC_id;
+
+  LOG_W(ENB_APP, "stopping lte-softmodem\n");
+  oai_exit = 1;
+
+  /* stop trx devices */
+  for(CC_id=0; CC_id<MAX_NUM_CCs; CC_id++) {
+    if (PHY_vars_eNB_g[0][CC_id]->rfdevice.trx_stop_func) {
+        LOG_I(ENB_APP, "stopping PHY_vars_eNB_g[0][%d]->rfdevice (via trx_stop_func())\n", CC_id);
+        PHY_vars_eNB_g[0][CC_id]->rfdevice.trx_stop_func(&PHY_vars_eNB_g[0][CC_id]->rfdevice);
+    }
+    if (PHY_vars_eNB_g[0][CC_id]->ifdevice.trx_stop_func) {
+        LOG_I(ENB_APP, "stopping PHY_vars_eNB_g[0][%d]->ifdevice (via trx_stop_func())\n", CC_id);
+        PHY_vars_eNB_g[0][CC_id]->ifdevice.trx_stop_func(&PHY_vars_eNB_g[0][CC_id]->ifdevice);
+    }
+  }
+
+  /* these tasks need to pick up new configuration */
+  terminate_task(TASK_RRC_ENB, enb_id);
+  terminate_task(TASK_L2L1, enb_id);
+  LOG_W(ENB_APP, "calling kill_eNB_proc() for instance %d\n", enb_id);
+  kill_eNB_proc(enb_id);
+  oai_exit = 0;
+  return 0;
+}
+
+/*
+ * Restart the lte-softmodem.
+ * This function checks whether we are in ENB_NORMAL_OPERATION (defined by
+ * FlexRAN). If yes, first stop L1/L2/L3, then resume.
+ */
+int restart_L1L2(int enb_id)
+{
+  int i, aa, CC_id;
+  /* needed for fill_PHY_vars_eNB_g(), defined locally in main();
+   * abstraction flag is needed too, but defined both globally and in main () */
+  uint8_t beta_ACK = 0, beta_RI = 0, beta_CQI = 2;
+  /* needed for macphy_init() */
+  int eMBMS_active = 0;
+
+  LOG_W(ENB_APP, "restarting lte-softmodem\n");
+
+  /* block threads */
+  sync_var = -1;
+
+  reconfigure_enb_params(enb_id);     /* set frame parameters from configuration */
+
+  /* PHY_vars_eNB_g will be filled by init_lte_eNB(), so free and
+   * let the data structure be filled again */
+  for (CC_id=0; CC_id<MAX_NUM_CCs; CC_id++) {
+    free(PHY_vars_eNB_g[0][CC_id]);
+    fill_PHY_vars_eNB_g(abstraction_flag, beta_ACK, beta_RI, beta_CQI);
+  }
+
+  dump_frame_parms(frame_parms[0]);
+  init_openair0();
+
+  /* give MAC interface current cell information, the rest is the same.
+   * For more info, check l2_init(). Then, initialize it (cf. line 1904). */
+  mac_xface->frame_parms = frame_parms[0];
+  mac_xface->macphy_init(eMBMS_active,(uecap_xer_in==1)?uecap_xer:NULL,0,0);
+
+  LOG_I(ENB_APP, "attempting to create ITTI tasks\n");
+  if (itti_create_task (TASK_RRC_ENB, rrc_enb_task, NULL) < 0) {
+    LOG_E(RRC, "Create task for RRC eNB failed\n");
+    return -1;
+  } else {
+    LOG_I(RRC, "Re-created task for RRC eNB successfully\n");
+  }
+  if (itti_create_task (TASK_L2L1, l2l1_task, NULL) < 0) {
+    LOG_E(PDCP, "Create task for L2L1 failed\n");
+    return -1;
+  } else {
+    LOG_I(PDCP, "Re-created task for L2L1 successfully\n");
+  }
+
+  /* TODO XForms here */
+
+  printf("Initializing eNB threads\n");
+  init_eNB(node_function, node_timing, 1, eth_params, single_thread_flag, wait_for_sync);
+  for(CC_id=0; CC_id<MAX_NUM_CCs; CC_id++) {
+      PHY_vars_eNB_g[0][CC_id]->rf_map.card=0;
+      PHY_vars_eNB_g[0][CC_id]->rf_map.chain=CC_id+chain_offset;
+  }
+
+  mlockall(MCL_CURRENT | MCL_FUTURE);
+
+  printf("Setting eNB buffer to all-RX\n");
+  // Set LSBs for antenna switch (ExpressMIMO)
+  for (CC_id=0; CC_id<MAX_NUM_CCs; CC_id++) {
+    PHY_vars_eNB_g[0][CC_id]->hw_timing_advance = 0;
+    for (i=0; i<frame_parms[CC_id]->samples_per_tti*10; i++)
+      for (aa=0; aa<frame_parms[CC_id]->nb_antennas_tx; aa++)
+        PHY_vars_eNB_g[0][CC_id]->common_vars.txdata[0][aa][i] = 0x00010001;
+  }
+
+  printf("Sending sync to all threads\n");
+
+  pthread_mutex_lock(&sync_mutex);
+  sync_var=0;
+  pthread_cond_broadcast(&sync_cond);
+  pthread_mutex_unlock(&sync_mutex);
+
+  return 0;
+}
+#endif
+
 int main( int argc, char **argv )
 {
   int i;
@@ -1029,6 +1264,27 @@ int main( int argc, char **argv )
 
   for (CC_id=0; CC_id<MAX_NUM_CCs; CC_id++) {
 
+#ifdef FLEXRAN_AGENT_SB_IF
+    pthread_mutex_init(&mutex_node_ctrl, NULL);
+    pthread_cond_init(&cond_node_ctrl, NULL);
+
+    for (i = 0; i < NB_eNB_INST; i++) {
+      flexran_agent_start(i);
+    }
+
+    LOG_I(ENB_APP, " * Waiting for FlexRAN RTController command *\n");
+    pthread_mutex_lock(&mutex_node_ctrl);
+    while (ENB_NORMAL_OPERATION != node_control_state)
+      pthread_cond_wait(&cond_node_ctrl, &mutex_node_ctrl);
+    pthread_mutex_unlock(&mutex_node_ctrl);
+
+    /* reconfigure eNB in case FlexRAN controller applied changes */
+    for (i=0; i < NB_eNB_INST; i++){
+      LOG_I(ENB_APP, "Reconfigure eNB module %d and FlexRAN eNB variables\n", i);
+      reconfigure_enb_params(i);
+      flexran_set_enb_vars(i, RAN_LTE_OAI);
+    }
+#endif
 
     if (UE_flag==1) {     
       NB_UE_INST=1;     
@@ -1352,7 +1608,6 @@ int main( int argc, char **argv )
       }
     }
   }
-
 #endif
 
   printf("stopping MODEM threads\n");
@@ -1367,7 +1622,10 @@ int main( int argc, char **argv )
   pthread_cond_destroy(&sync_cond);
   pthread_mutex_destroy(&sync_mutex);
 
-
+#ifdef FLEXRAN_AGENT_SB_IF
+    pthread_cond_destroy(&cond_node_ctrl);
+    pthread_mutex_destroy(&mutex_node_ctrl);
+#endif
 
   // *** Handle per CC_id openair0
   if (UE_flag==1) {
@@ -1390,6 +1648,8 @@ int main( int argc, char **argv )
     terminate_opt();
   
   logClean();
+
+  printf("Bye.\n");
   
   return 0;
 }
diff --git a/targets/RT/USER/lte-softmodem.h b/targets/RT/USER/lte-softmodem.h
index 44e35c88a385319e896142e77ec05d5a62a9eb01..6274fc16107ca470b016608041e65f9ceb8aac8c 100644
--- a/targets/RT/USER/lte-softmodem.h
+++ b/targets/RT/USER/lte-softmodem.h
@@ -264,4 +264,14 @@ PHY_VARS_UE* init_ue_vars(LTE_DL_FRAME_PARMS *frame_parms,
                           uint8_t abstraction_flag);
 void init_eNB_afterRU(void);
 
+extern int stop_L1L2(int enb_id);
+extern int restart_L1L2(int enb_id);
+
+#ifdef FLEXRAN_AGENT_SB_IF
+#include "flexran_agent.h" // for locking
+volatile ENB_MODULE_STATE node_control_state;
+pthread_cond_t cond_node_ctrl;
+pthread_mutex_t mutex_node_ctrl;
+#endif
+
 #endif