diff --git a/ci-scripts/oai-ci-vm-tool b/ci-scripts/oai-ci-vm-tool
index c28f51415ef5690b07af79e592f2d749d67b329a..30d8912f50df66759d204003f32dffa7c08b37b7 100755
--- a/ci-scripts/oai-ci-vm-tool
+++ b/ci-scripts/oai-ci-vm-tool
@@ -69,7 +69,7 @@ VM_MEMORY=2048
 VM_CPU=4
 ARCHIVES_LOC=enb_usrp
 LOG_PATTERN=.Rel14.txt
-NB_PATTERN_FILES=4
+NB_PATTERN_FILES=7
 BUILD_OPTIONS="--eNB -w USRP"
 KEEP_VM_ALIVE=0
 RUN_OPTIONS="none"
@@ -231,7 +231,7 @@ case $key in
     VM_NAME=ci-enb-usrp
     ARCHIVES_LOC=enb_usrp
     LOG_PATTERN=.Rel14.txt
-    NB_PATTERN_FILES=4
+    NB_PATTERN_FILES=7
     BUILD_OPTIONS="--eNB -w USRP --mu"
     NBARGS=$[$NBARGS+256]
     shift
@@ -272,7 +272,7 @@ case $key in
     VM_NAME=ci-enb-ethernet
     ARCHIVES_LOC=enb_eth
     LOG_PATTERN=.Rel14.txt
-    NB_PATTERN_FILES=6
+    NB_PATTERN_FILES=8
     BUILD_OPTIONS="--eNB -t ETHERNET --noS1"
     NBARGS=$[$NBARGS+256]
     shift
@@ -281,7 +281,7 @@ case $key in
     VM_NAME=ci-ue-ethernet
     ARCHIVES_LOC=ue_eth
     LOG_PATTERN=.Rel14.txt
-    NB_PATTERN_FILES=6
+    NB_PATTERN_FILES=8
     BUILD_OPTIONS="--UE -t ETHERNET --noS1"
     NBARGS=$[$NBARGS+256]
     shift
@@ -292,7 +292,7 @@ case $key in
     VM_CPU=8
     ARCHIVES_LOC=l2_sim
     LOG_PATTERN=.Rel14.txt
-    NB_PATTERN_FILES=4
+    NB_PATTERN_FILES=6
     BUILD_OPTIONS="--eNB -t ETHERNET"
     RUN_OPTIONS="complex"
     NBARGS=$[$NBARGS+256]
@@ -314,7 +314,7 @@ case $key in
         VM_NAME=ci-enb-usrp
         ARCHIVES_LOC=enb_usrp
         LOG_PATTERN=.Rel14.txt
-        NB_PATTERN_FILES=4
+        NB_PATTERN_FILES=7
         BUILD_OPTIONS="--eNB -w USRP --mu"
         NBARGS=$[$NBARGS+256]
         ;;
@@ -351,7 +351,7 @@ case $key in
         VM_NAME=ci-enb-ethernet
         ARCHIVES_LOC=enb_eth
         LOG_PATTERN=.Rel14.txt
-        NB_PATTERN_FILES=6
+        NB_PATTERN_FILES=8
         BUILD_OPTIONS="--eNB -t ETHERNET --noS1"
         NBARGS=$[$NBARGS+256]
         ;;
@@ -359,7 +359,7 @@ case $key in
         VM_NAME=ci-ue-ethernet
         ARCHIVES_LOC=ue_eth
         LOG_PATTERN=.Rel14.txt
-        NB_PATTERN_FILES=6
+        NB_PATTERN_FILES=8
         BUILD_OPTIONS="--UE -t ETHERNET --noS1"
         NBARGS=$[$NBARGS+256]
         ;;
@@ -369,7 +369,7 @@ case $key in
         VM_CPU=8
         ARCHIVES_LOC=l2_sim
         LOG_PATTERN=.Rel14.txt
-        NB_PATTERN_FILES=4
+        NB_PATTERN_FILES=6
         BUILD_OPTIONS="--eNB -t ETHERNET"
         RUN_OPTIONS="complex"
         NBARGS=$[$NBARGS+256]
diff --git a/cmake_targets/CMakeLists.txt b/cmake_targets/CMakeLists.txt
index a1b4955b21212ae2dad2c10b37ba0d88556f25b7..3f2041089fa9cff825952499f8cc70d27ad38fc7 100644
--- a/cmake_targets/CMakeLists.txt
+++ b/cmake_targets/CMakeLists.txt
@@ -21,7 +21,7 @@
 
 # Author: laurent THOMAS, Lionel GAUTHIER
 
-cmake_minimum_required (VERSION 2.8)
+cmake_minimum_required (VERSION 3.0)
 
 #############################################
 # Base directories, compatible with legacy OAI building
@@ -169,11 +169,12 @@ endif()
 set(CMAKE_C_FLAGS
   "${CMAKE_C_FLAGS} ${C_FLAGS_PROCESSOR} -std=gnu99 -Wall -Wstrict-prototypes -fno-strict-aliasing -rdynamic -funroll-loops -Wno-packed-bitfield-compat -fPIC ")
 # add autotools definitions that were maybe used!
+set(MKVER "'MAKE_VERSION(a,b,c)=((a)*256+(b)*16+c)'")
 set(CMAKE_C_FLAGS
-  "${CMAKE_C_FLAGS} -DSTDC_HEADERS=1 -DHAVE_SYS_TYPES_H=1 -DHAVE_SYS_STAT_H=1 -DHAVE_STDLIB_H=1 -DHAVE_STRING_H=1 -DHAVE_MEMORY_H=1 -DHAVE_STRINGS_H=1 -DHAVE_INTTYPES_H=1 -DHAVE_STDINT_H=1 -DHAVE_UNISTD_H=1 -DHAVE_FCNTL_H=1 -DHAVE_ARPA_INET_H=1 -DHAVE_SYS_TIME_H=1 -DHAVE_SYS_SOCKET_H=1 -DHAVE_STRERROR=1 -DHAVE_SOCKET=1 -DHAVE_MEMSET=1 -DHAVE_GETTIMEOFDAY=1 -DHAVE_STDLIB_H=1 -DHAVE_MALLOC=1 -DHAVE_LIBSCTP -D'MAKE_VERSION(a,b,c)=((a)*256+(b)*16+c)'"
+	"${CMAKE_C_FLAGS} -DSTDC_HEADERS=1 -DHAVE_SYS_TYPES_H=1 -DHAVE_SYS_STAT_H=1 -DHAVE_STDLIB_H=1 -DHAVE_STRING_H=1 -DHAVE_MEMORY_H=1 -DHAVE_STRINGS_H=1 -DHAVE_INTTYPES_H=1 -DHAVE_STDINT_H=1 -DHAVE_UNISTD_H=1 -DHAVE_FCNTL_H=1 -DHAVE_ARPA_INET_H=1 -DHAVE_SYS_TIME_H=1 -DHAVE_SYS_SOCKET_H=1 -DHAVE_STRERROR=1 -DHAVE_SOCKET=1 -DHAVE_MEMSET=1 -DHAVE_GETTIMEOFDAY=1 -DHAVE_STDLIB_H=1 -DHAVE_MALLOC=1 -DHAVE_LIBSCTP -D${MKVER}"
 )
 set(CMAKE_CXX_FLAGS
-  "${CMAKE_CXX_FLAGS} ${C_FLAGS_PROCESSOR} -std=c++11 -D'MAKE_VERSION(a,b,c)=((a)*256+(b)*16+c)'"
+	"${CMAKE_CXX_FLAGS} ${C_FLAGS_PROCESSOR} -std=c++11 -D${MKVER}"
 )
 add_definitions("-DASN_DISABLE_OER_SUPPORT")
 
@@ -478,7 +479,8 @@ add_dependencies(X2AP_ENB rrc_flag x2_flag)
 add_list1_option(NB_ANTENNAS_RX "2" "Number of antennas in reception" "1" "2" "4")
 add_list1_option(NB_ANTENNAS_TX "4" "Number of antennas in transmission" "1" "2" "4")
 
-add_list2_option(RF_BOARD "EXMIMO" "RF head type" "None" "EXMIMO" "OAI_USRP" "OAI_BLADERF" "CPRIGW" "OAI_LMSSDR")
+add_list2_option(RF_BOARD "EXMIMO" "RF head type" "None" "EXMIMO" "OAI_USRP" "OAI_BLADERF" "CPRIGW" "OAI_LMSSDR" "OAI_SIMU")
+
 
 add_list2_option(TRANSP_PRO "None" "Transport protocol type" "None" "ETHERNET")
 #NOKIA config enhancement
@@ -586,6 +588,8 @@ set(HWLIB_TCP_BRIDGE_OAI_SOURCE
 add_library(tcp_bridge_oai MODULE ${HWLIB_TCP_BRIDGE_OAI_SOURCE} )
 set_target_properties(tcp_bridge_oai PROPERTIES COMPILE_FLAGS "-fvisibility=hidden")
 
+add_library(rfsimulator MODULE ${OPENAIR_TARGETS}/ARCH/rfsimulator/simulator.c)
+
 ##########################################################
 
 include_directories ("${OPENAIR_TARGETS}/ARCH/COMMON")
@@ -1284,7 +1288,7 @@ set(L2_SRC
   ${RLC_DIR}/rlc.c
   ${RLC_DIR}/rlc_rrc.c
   ${RLC_DIR}/rlc_mpls.c
-  ${RRC_DIR}/rrc_UE.c
+#  ${RRC_DIR}/rrc_UE.c
   ${RRC_DIR}/rrc_eNB.c
   ${RRC_DIR}/rrc_eNB_S1AP.c
   ${RRC_DIR}/rrc_eNB_UE_context.c
@@ -1950,6 +1954,8 @@ add_executable(lte-softmodem
   ${OPENAIR1_DIR}/SIMULATION/TOOLS/taus.c
   ${OPENAIR_TARGETS}/COMMON/create_tasks.c
   ${OPENAIR_TARGETS}/ARCH/COMMON/common_lib.c
+  ${OPENAIR2_DIR}/RRC/NAS/nas_config.c
+  ${OPENAIR2_DIR}/RRC/NAS/rb_config.c
   ${OPENAIR1_DIR}/SIMULATION/ETH_TRANSPORT/netlink_init.c
   ${OPENAIR1_DIR}/SIMULATION/ETH_TRANSPORT/multicast_link.c
   ${OPENAIR1_DIR}/SIMULATION/ETH_TRANSPORT/socket.c
diff --git a/cmake_targets/build_oai b/cmake_targets/build_oai
index d14bd3ec6edd36fa031d252cf2a4aea6d845a6e1..e77dbab0497ac39f9c403bb0d014e7053b71ab9b 100755
--- a/cmake_targets/build_oai
+++ b/cmake_targets/build_oai
@@ -76,7 +76,7 @@ trap handle_ctrl_c INT
 function print_help() {
   echo_info "
 This program installs OpenAirInterface Software
-You should have ubuntu 14.xx, updated, and the Linux kernel >= 3.14
+You should have ubuntu 16.xx or 18.04 updated
 Options
 -h
    This help
@@ -167,6 +167,9 @@ Options
 --basic-simulator
    Generates a basic [1 UE + 1 eNB + no channel] simulator.
    See targets/ARCH/tcp_bridge/README.tcp_bridge_oai for documentation.
+--rfsimulator
+   Generate virtual RF driver
+   to use it, set the environement variable RFSIMULATOR to \"enb\" in the eNB and to the eNB IP address in the UEs
 Usage (first build):
  NI/ETTUS B201  + COTS UE : ./build_oai -I  --eNB -x --install-system-files -w USRP
 Usage (Regular):
@@ -234,25 +237,21 @@ function main() {
             echo_info "Setting release to: $REL"
             shift 2;;
        -w | --hardware)
-            HW="$2" #"${i#*=}"
-            # Use OAI_USRP  as the key word USRP is used inside UHD driver           
-            if [ "$HW" != "BLADERF" -a  "$HW" != "USRP" -a "$HW" != "LMSSDR" -a  "$HW" != "None" -a  "$HW" != "EXMIMO" -a  "$HW" != "IRIS"  ] ; then 
-		echo_fatal "Unknown HW type $HW will exit..."		
-	    else
-		if [ "$HW" == "USRP" ] ; then 
-		    HW="OAI_USRP"
-		fi 
-		if [ "$HW" == "BLADERF" ] ; then 
-		    HW="OAI_BLADERF"
-		fi
-		if [ "$HW" == "LMSSDR" ] ; then 
-		    HW="OAI_LMSSDR"
-		fi 
-                if [ "$HW" == "IRIS" ] ; then
-                    HW="OAI_IRIS"
-                fi
-		echo_info "Setting hardware to: $HW"
-	    fi
+                # Use OAI_USRP  as the key word USRP is used inside UHD driver
+                case "$2" in
+                    "EXMIMO")
+                        HW="EXMIMO"
+                        ;;
+                    "USRP" | "BLADERF" | "LMSSDR" | "IRIS" | "SIMU")
+                        HW="OAI_"$2
+                        ;;
+                    "None")
+                        HW="None"
+                        ;;
+                    *)
+                        echo_fatal "Unknown HW type $HW: exit..."
+                esac
+	echo_info "Setting hardware to: $HW"
             shift 2;;
 	-t | --transport_protocol)
             TP="$2" #"${i#*=}"
@@ -374,6 +373,10 @@ function main() {
             BASIC_SIMULATOR=1
             echo_info "Compiling the basic simulator"
             shift 1;;
+	--rfsimulator)
+	    RFSIMULATOR=true
+	    echo_info "Compiling the RF simulator"
+	    shift 1;;
         -h | --help)
             print_help
             exit 1;;
@@ -386,56 +389,35 @@ function main() {
   
   CMAKE_CMD="$CMAKE_CMD .."
   echo_info "CMAKE_CMD=$CMAKE_CMD"
-  if [ "$eNB" = "1" ] && [ "$UE" = "1" ]; then
-    echo_error "Cannot build UE and eNB on one build_oai execution"
-    echo_error "use 2 build_oai invocations"
-    exit
-  fi  
-  #########################################################
-  # check validity of HW and TP parameters for eNB
-  #########################################################
-  # to be discussed
-  
-  if [ "$eNB" = "1" ] ; then
-      if [ "$HW" = "None" -a  "$TP" = "None" ] ; then
-	  echo_fatal "Define a local radio head (e.g. -w EXMIMO) or a transport protocol (e.g. -t ETHERNET) to communicate with a remote radio head!"
-      fi
-      if [ "$HW" = "None" ] ; then 
-	  echo_info "No radio head has been selected (HW set to $HW)"	
-      fi
-      if [ "$TP" = "None" ] ; then
-	  echo_info "No transport protocol has been selected (TP set to $TP)"	
-      fi
-  fi
-  
-  echo_info "RF HW set to $HW" 
-  #Now we set flags to enable deadline scheduler settings
-  #By default: USRP: disable, 
-  #By default: BLADERF: enable,
-  #By default: EXMIMO: enable
-  if [ "$FORCE_DEADLINE_SCHEDULER_FLAG_USER" = "" ]; then
-     if [ "$HW" = "EXMIMO" ] ; then 
-        DEADLINE_SCHEDULER_FLAG_USER="True"
-     elif [ "$HW" = "ETHERNET" ] ; then 
-        DEADLINE_SCHEDULER_FLAG_USER="False"
-     elif [ "$HW" = "OAI_USRP" ] ; then 
-        DEADLINE_SCHEDULER_FLAG_USER="False"
-     elif [ "$HW" = "OAI_BLADERF" ] ; then 
-        DEADLINE_SCHEDULER_FLAG_USER="False"
-     elif [ "$HW" = "OAI_LMSSDR" ] ; then     
-        DEADLINE_SCHEDULER_FLAG_USER="False" 
-     elif [ "$HW" = "OAI_IRIS" ] ; then
-        DEADLINE_SCHEDULER_FLAG_USER="False"
-     elif [ "$HW" = "None" ] ; then 
-        DEADLINE_SCHEDULER_FLAG_USER="False"
-     else 
-        echo_error "Unknown HW type $HW. Exiting now..."
-        exit 
-     fi
-  else
-     DEADLINE_SCHEDULER_FLAG_USER=$FORCE_DEADLINE_SCHEDULER_FLAG_USER
-  fi
-
+    #########################################################
+    # check validity of HW and TP parameters for eNB
+    #########################################################
+    # to be discussed
+    
+    if [ "$eNB" = "1" ] ; then
+	if [ "$HW" = "None" -a  "$TP" = "None" ] ; then
+            echo_fatal "Define a local radio head (e.g. -w EXMIMO) or a transport protocol (e.g. -t ETHERNET) to communicate with a remote radio head!"
+	fi
+	if [ "$HW" = "None" ] ; then 
+            echo_info "No radio head has been selected (HW set to $HW)"   
+	fi
+	if [ "$TP" = "None" ] ; then
+            echo_info "No transport protocol has been selected (TP set to $TP)"   
+	fi
+    fi
+    
+    echo_info "RF HW set to $HW" 
+    # If the user doesn't specify the Linux scheduler to use, we set a value
+    if [ "$DEADLINE_SCHEDULER_FLAG_USER" = "" ]; then
+      case "$HW" in
+ 	  "EXMIMO")
+               DEADLINE_SCHEDULER_FLAG_USER="True"
+              ;;
+ 	  *)
+              DEADLINE_SCHEDULER_FLAG_USER="False"
+              ;;
+      esac
+    fi
   #Disable CPU Affinity for deadline scheduler
   if [ "$DEADLINE_SCHEDULER_FLAG_USER" = "True" ] ; then 
      CPU_AFFINITY_FLAG_USER="False"
@@ -515,27 +497,20 @@ function main() {
   
   echo_info "3. building the compilation directives ..."
 
-  DIR=$OPENAIR_DIR/cmake_targets
-  if [ "$NOS1" =  "1" ] ; then
-      lte_build_dir=lte_noS1_build_oai
-      if [ "$eNB" = "1" ] ; then
-         lte_exec=lte-softmodem-nos1
-      fi
-      if [ "$UE" = "1" ] ; then
-         lte_exec=lte-uesoftmodem-nos1
-      fi
-  else
-      lte_build_dir=lte_build_oai
-      if [ "$eNB" = "1" ] ; then
-         lte_exec=lte-softmodem
-      fi
-      if [ "$UE" = "1" ] ; then
-         lte_exec=lte-uesoftmodem
-      fi
-  fi
-  if [ "$T_TRACER" =  "False" ] ; then
-      lte_build_dir=${lte_build_dir}_noLOG
-  fi
+    DIR=$OPENAIR_DIR/cmake_targets
+    
+    if [ "$T_TRACER" =  "False" ] ; then
+        noLOGDirsuffix="_noLOG"
+    fi
+    if [ "$NOS1" =  "1" ] ; then
+        noS1Dir="_noS1"
+        bin_suffix="-nos1"
+    else
+        lte_build_dir=lte_build_oai
+        bin_suffix=""
+    fi
+
+    lte_build_dir="lte${noS1Dir}_build_oai${noLOGDirsuffix}"
 # configuration module libraries, one currently available, using libconfig 
   config_libconfig_shlib=params_libconfig
   
@@ -580,8 +555,8 @@ function main() {
     eval $CMAKE_CMD
   fi
 
-  if [ "$eNB" = "1" -o "$UE" = "1" ] ; then
-    echo_info "Compiling $lte_exec"
+  if [ "$eNB" = "1" ] ; then
+    lte_exec=lte-softmodem${bin_suffix}
     compilations \
 	  $lte_build_dir $lte_exec \
 	  $lte_exec $dbin/$lte_exec.$REL
@@ -605,7 +580,29 @@ function main() {
     fi
   fi
 
-  if [ "$UE" = 1 -a "$NOS1" = "0" ] ; then
+  if [ "$UE" = 1  ] ; then
+        lte_exec=lte-uesoftmodem${bin_suffix}
+        compilations \
+            $lte_build_dir $lte_exec \
+            $lte_exec $dbin/$lte_exec.$REL
+        
+        # mandatory shared lib
+        compilations \
+            $lte_build_dir $config_libconfig_shlib \
+            lib$config_libconfig_shlib.so $dbin/lib$config_libconfig_shlib.so
+        compilations \
+            $lte_build_dir coding \
+            libcoding.so $dbin/libcoding.so
+        
+        if [ "$NOS1" = "1" ] ; then
+            compilations \
+                $lte_build_dir nasmesh \
+                CMakeFiles/nasmesh/nasmesh.ko $dbin/nasmesh.ko
+            compilations \
+                $lte_build_dir rb_tool \
+                rb_tool $dbin/rb_tool
+            cp $OPENAIR_DIR/cmake_targets/tools/init_nas_nos1 $dbin
+        else        
     # ue_ip driver compilation
     echo_info "Compiling UE specific part"
     compilations \
@@ -645,6 +642,7 @@ function main() {
       echo_warning "not generated UE NAS files: binaries not found"
     fi
   fi
+    fi
 
   if [ "$SIMUS_PHY" = "1" -o "$SIMUS_CORE" = "1" ] ; then
     cd $OPENAIR_DIR/cmake_targets/lte-simulators
@@ -709,103 +707,108 @@ function main() {
     cp $OPENAIR_DIR/cmake_targets/tools/init_exmimo2 $dbin
   fi
 
-
-
-  # Telnet server compilation
-  #####################
-  if [ "$BUILD_TELNETSRV" = "1" ] ; then
-              build_dir=$lte_build_dir
-              compilations \
-                  $build_dir telnetsrv \
-                  libtelnetsrv.so $dbin/libtelnetsrv.so
-
-  fi 
-  # Telnet server compilation
-  #####################
-  if [ "$MSC_GEN" = "1" ] ; then
-              build_dir=$lte_build_dir
-              compilations \
-                  $build_dir msc \
-                  libmsc.so $dbin/libmsc.so
-
-  fi  
-  # build RF device and transport protocol libraries
-  #####################################
-  if [ "$eNB" = "1" -o "$UE" = "1" ] ; then
-
-      build_dir=$lte_build_dir	  
-
-      # build RF device libraries
-      if [ "$HW" != "None" ] ; then
-	  rm -f liboai_device.so
-	  rm -f $dbin/liboai_device.so
-
-	  # link liboai_device.so with the selected RF device library
-	  if [ "$HW" == "EXMIMO" ] ; then
-	      compilations \
-		  $build_dir oai_exmimodevif \
-		  liboai_exmimodevif.so $dbin/liboai_exmimodevif.so.$REL
-
-	      ln -sf liboai_exmimodevif.so liboai_device.so
-	      ln -sf $dbin/liboai_exmimodevif.so.$REL $dbin/liboai_device.so
-	      echo_info "liboai_device.so is linked to EXMIMO device library"       
-	  elif [ "$HW" == "OAI_USRP" ] ; then
-              compilations \
-                  $build_dir oai_usrpdevif \
-                  liboai_usrpdevif.so $dbin/liboai_usrpdevif.so.$REL
-
-	      ln -sf liboai_usrpdevif.so liboai_device.so
-	      ln -sf $dbin/liboai_usrpdevif.so.$REL $dbin/liboai_device.so
-	      echo_info "liboai_device.so is linked to USRP device library"        
-	  elif [ "$HW" == "OAI_BLADERF" ] ; then
-	      if [ -f "/usr/include/libbladeRF.h" ] ; then
-		  compilations \
-		      $build_dir oai_bladerfdevif \
-		      liboai_bladerfdevif.so $dbin/liboai_bladerfdevif.so.$REL
-	      fi
-
-	      ln -sf liboai_bladerfdevif.so liboai_device.so
-	      ln -sf $dbin/liboai_bladerfdevif.so.$REL $dbin/liboai_device.so
-	      echo_info "liboai_device.so is linked to BLADERF device library"	 
-	  elif [ "$HW" == "OAI_LMSSDR" ] ; then
-#	      if [ -f "/usr/include/libbladeRF.h" ] ; then
-		  compilations \
-		      $build_dir oai_lmssdrdevif \
-		      liboai_lmssdrdevif.so $dbin/liboai_lmssdrdevif.so.$REL
-#	      fi
-
-	      ln -sf liboai_lmssdrdevif.so liboai_device.so
-	      ln -sf $dbin/liboai_lmssdrdevif.so.$REL $dbin/liboai_device.so
-	      echo_info "liboai_device.so is linked to LMSSDR device library"	 
-          elif [ "$HW" == "OAI_IRIS" ] ; then
-                  compilations \
-                      $build_dir oai_irisdevif \
-                      liboai_irisdevif.so $dbin/liboai_irisdevif.so.$REL
-
-              ln -s liboai_irisdevif.so liboai_device.so
-              ln -s $dbin/liboai_irisdevif.so.$REL $dbin/liboai_device.so
-              echo_info "liboai_device.so is linked to IRIS device library"
-	  else 
-	      echo_info "liboai_device.so is not linked to any device library"	    
-	  fi
-      fi
-      
-      # build trasport protocol libraries (currently only ETHERNET is available)
-      if [ "$TP" != "None" ] ; then
-	  rm -f liboai_transpro.so
-	  rm -f $dbin/liboai_transpro.so
-
-	  if [ "$TP" == "ETHERNET" ] ; then
-	      compilations \
-		  $build_dir oai_eth_transpro \
-		  liboai_eth_transpro.so $dbin/liboai_eth_transpro.so.$REL
-	      ln -sf liboai_eth_transpro.so liboai_transpro.so
-	      ln -sf $dbin/liboai_eth_transpro.so.$REL $dbin/liboai_transpro.so
-	      echo_info "liboai_transpro.so is linked with ETHERNET library"	 
-	  fi      
-      fi
-fi
-
+    # Telnet server compilation
+    #####################
+    if [ "$BUILD_TELNETSRV" = "1" ] ; then
+        compilations \
+            $lte_build_dir telnetsrv \
+            libtelnetsrv.so $dbin/libtelnetsrv.so
+        
+    fi
+    # msc library compilation
+    #####################
+    if [ "$MSC_GEN" = "1" ] ; then
+        compilations \
+            $lte_build_dir msc \
+            libmsc.so $dbin/libmsc.so
+        
+    fi
+    # build RF device and transport protocol libraries
+    #####################################
+    if [ "$eNB" = "1" -o "$UE" = "1" ] ; then
+        
+        # build RF device libraries
+        if [ "$HW" != "None" ] ; then
+            rm -f liboai_device.so
+            rm -f $dbin/liboai_device.so
+            
+            # link liboai_device.so with the selected RF device library
+            if [ "$HW" == "EXMIMO" ] ; then
+                compilations \
+                    $lte_build_dir oai_exmimodevif \
+                    liboai_exmimodevif.so $dbin/liboai_exmimodevif.so.$REL
+                
+                ln -sf liboai_exmimodevif.so liboai_device.so
+                ln -sf $dbin/liboai_exmimodevif.so.$REL $dbin/liboai_device.so
+                echo_info "liboai_device.so is linked to EXMIMO device library"
+            elif [ "$HW" == "OAI_USRP" ] ; then
+                compilations \
+                    $lte_build_dir oai_usrpdevif \
+                    liboai_usrpdevif.so $dbin/liboai_usrpdevif.so.$REL
+                
+                ln -sf liboai_usrpdevif.so liboai_device.so
+                ln -sf $dbin/liboai_usrpdevif.so.$REL $dbin/liboai_device.so
+                echo_info "liboai_device.so is linked to USRP device library"
+            elif [ "$HW" == "OAI_BLADERF" ] ; then
+                if [ -f "/usr/include/libbladeRF.h" ] ; then
+                    compilations \
+                        $lte_build_dir oai_bladerfdevif \
+                        liboai_bladerfdevif.so $dbin/liboai_bladerfdevif.so.$REL
+                fi
+                
+                ln -sf liboai_bladerfdevif.so liboai_device.so
+                ln -sf $dbin/liboai_bladerfdevif.so.$REL $dbin/liboai_device.so
+                echo_info "liboai_device.so is linked to BLADERF device library"
+            elif [ "$HW" == "OAI_LMSSDR" ] ; then
+                #       if [ -f "/usr/include/libbladeRF.h" ] ; then
+                compilations \
+                    $lte_build_dir oai_lmssdrdevif \
+                    liboai_lmssdrdevif.so $dbin/liboai_lmssdrdevif.so.$REL
+                #       fi
+                
+                ln -sf liboai_lmssdrdevif.so liboai_device.so
+                ln -sf $dbin/liboai_lmssdrdevif.so.$REL $dbin/liboai_device.so
+                echo_info "liboai_device.so is linked to LMSSDR device library"
+            elif [ "$HW" == "OAI_IRIS" ] ; then
+                compilations \
+                    $lte_build_dir oai_irisdevif \
+                    liboai_irisdevif.so $dbin/liboai_irisdevif.so.$REL
+                
+                ln -s liboai_irisdevif.so liboai_device.so
+                ln -s $dbin/liboai_irisdevif.so.$REL $dbin/liboai_device.so
+                echo_info "liboai_device.so is linked to IRIS device library"
+            else
+                echo_info "liboai_device.so is not linked to any device library"
+            fi
+        fi
+        
+        # build simulators devices
+        echo_info "Compiling rfsimulator"
+        compilations \
+            $lte_build_dir rfsimulator \
+            librfsimulator.so $dbin/librfsimulator.so.$REL
+        echo_info "Compiling basicsimulator"
+        compilations \
+            $lte_build_dir tcp_bridge_oai \
+            libtcp_bridge_oai.so $dbin/libtcp_bridge_oai.so.$REL
+        # build transport protocol libraries (currently only ETHERNET is available)
+
+        rm -f liboai_transpro.so
+        rm -f $dbin/liboai_transpro.so
+        compilations \
+            $lte_build_dir oai_eth_transpro \
+            liboai_eth_transpro.so $dbin/liboai_eth_transpro.so.$REL
+        ln -sf liboai_eth_transpro.so liboai_transpro.so
+        ln -sf $dbin/liboai_eth_transpro.so.$REL $dbin/liboai_transpro.so
+        echo_info "liboai_transpro.so is linked to ETHERNET transport"
+    fi
+    
+    if [ "$RFSIMULATOR" == "true" -o "$HW" == "OAI_SIMU" ] ; then
+        echo_info "Compiling rfsimulator"
+        compilations \
+            $lte_build_dir rfsimulator \
+            librfsimulator.so $dbin/librfsimulator.so.$REL
+    fi
 
   # Doxygen Support
   #####################
diff --git a/common/utils/telnetsrv/telnetsrv.c b/common/utils/telnetsrv/telnetsrv.c
index b6803ead6bb15a668928fed2458ce738f7f3e3e1..4b6def2f6dafa073470ac477a6d45c0a55a767f3 100644
--- a/common/utils/telnetsrv/telnetsrv.c
+++ b/common/utils/telnetsrv/telnetsrv.c
@@ -77,17 +77,17 @@ paramdef_t telnetoptions[] = {
   /*                                            configuration parameters for telnet utility                                                                             */
   /*   optname                     helpstr                paramflags           XXXptr                               defXXXval               type                 numelt */
   /*--------------------------------------------------------------------------------------------------------------------------------------------------------------------*/
-  {"listenaddr",    "<listen ip address>",         0,                 uptr:&telnetparams.listenaddr,        defstrval:"0.0.0.0",            TYPE_IPV4ADDR,  0 },
-  {"listenport",    "<local port>",                0,                 uptr:&(telnetparams.listenport),      defuintval:9090,                TYPE_UINT,      0 },
-  {"priority",      "<scheduling policy (0-99)",   0,                 iptr:&telnetparams.priority,          defuintval:0,                   TYPE_INT,       0 },
-  {"debug",         "<debug level>",               0,                 uptr:NULL,                            defuintval:0,                   TYPE_UINT,      0 },
-  {"loopcount",     "<loop command iterations>",   0,                 uptr:&(telnetparams.loopcount),       defuintval:10,                  TYPE_UINT,      0 },
-  {"loopdelay",     "<loop command delay (ms)>",   0,                 uptr:&(telnetparams.loopdelay),       defuintval:5000,                TYPE_UINT,      0 },
-  {"histfile",      "<history file name>",         PARAMFLAG_NOFREE,  strptr:&(telnetparams.histfile),      defstrval:"oaitelnet.history",  TYPE_STRING,    0 },
-  {"histsize",      "<history sizes>",             0,                 iptr:&(telnetparams.histsize),        defuintval:50,                  TYPE_INT,       0 },
-  {"phypbsize",     "<phy dump buff size (bytes)>",0,                 uptr:&(telnetparams.phyprntbuff_size),defuintval:65000,               TYPE_UINT,      0 },
-  {"staticmod",     "<static modules selection>",  0,                 strlistptr:NULL,                      defstrlistval:telnet_defstatmod,TYPE_STRINGLIST,(sizeof(telnet_defstatmod)/sizeof(char *))},
-  {"shrmod",        "<dynamic modules selection>", 0,                 strlistptr:NULL,                      defstrlistval:NULL,TYPE_STRINGLIST,0 }
+  {"listenaddr",    "<listen ip address>\n",         0,                 uptr:&telnetparams.listenaddr,        defstrval:"0.0.0.0",            TYPE_IPV4ADDR,  0 },
+  {"listenport",    "<local port>\n",                0,                 uptr:&(telnetparams.listenport),      defuintval:9090,                TYPE_UINT,      0 },
+  {"priority",      "<scheduling policy (0-99)\n",   0,                 iptr:&telnetparams.priority,          defuintval:0,                   TYPE_INT,       0 },
+  {"debug",         "<debug level>\n",               0,                 uptr:NULL,                            defuintval:0,                   TYPE_UINT,      0 },
+  {"loopcount",     "<loop command iterations>\n",   0,                 uptr:&(telnetparams.loopcount),       defuintval:10,                  TYPE_UINT,      0 },
+  {"loopdelay",     "<loop command delay (ms)>\n",   0,                 uptr:&(telnetparams.loopdelay),       defuintval:5000,                TYPE_UINT,      0 },
+  {"histfile",      "<history file name>\n",         PARAMFLAG_NOFREE,  strptr:&(telnetparams.histfile),      defstrval:"oaitelnet.history",  TYPE_STRING,    0 },
+  {"histsize",      "<history sizes>\n",             0,                 iptr:&(telnetparams.histsize),        defuintval:50,                  TYPE_INT,       0 },
+  {"phypbsize",     "<phy dump buff size (bytes)>\n",0,                 uptr:&(telnetparams.phyprntbuff_size),defuintval:65000,               TYPE_UINT,      0 },
+  {"staticmod",     "<static modules selection>\n",  0,                 strlistptr:NULL,                      defstrlistval:telnet_defstatmod,TYPE_STRINGLIST,(sizeof(telnet_defstatmod)/sizeof(char *))},
+  {"shrmod",        "<dynamic modules selection>\n", 0,                 strlistptr:NULL,                      defstrlistval:NULL,TYPE_STRINGLIST,0 }
 };
 
 int get_phybsize(void) {
@@ -355,7 +355,7 @@ int setgetvar(int moduleindex,char getorset,char *params) {
   char varname[TELNET_CMD_MAXSIZE];
   char *varval=NULL;
   memset(varname,0,sizeof(varname));
-  n = sscanf(params,"%19s %ms",varname,&varval);
+  n = sscanf(params,"%s %ms",varname,&varval);
 
   for ( i=0 ; telnetparams.CmdParsers[moduleindex].var[i].varvalptr != NULL ; i++) {
     if ( strncasecmp(telnetparams.CmdParsers[moduleindex].var[i].varname,varname,strlen(telnetparams.CmdParsers[moduleindex].var[i].varname)) == 0) {
@@ -475,7 +475,7 @@ int process_command(char *buf) {
   memset(cmdb,0,sizeof(cmdb));
   bufbck=strdup(buf);
   rt=CMDSTATUS_NOTFOUND;
-  j = sscanf(buf,"%9s %9s %2000[^\t\n]",modulename,cmd,cmdb);
+  j = sscanf(buf,"%9s %9s %[^\t\n]",modulename,cmd,cmdb);
 
   if (telnetparams.telnetdbg > 0)
     printf("process_command: %i words, module=%s cmd=%s, parameters= %s\n",j,modulename,cmd,cmdb);
diff --git a/common/utils/telnetsrv/telnetsrv_ltemeasur_def.h b/common/utils/telnetsrv/telnetsrv_ltemeasur_def.h
new file mode 100644
index 0000000000000000000000000000000000000000..2f479d8ee6f9e5f59b06720e751df617d871e3bb
--- /dev/null
+++ b/common/utils/telnetsrv/telnetsrv_ltemeasur_def.h
@@ -0,0 +1,127 @@
+/*
+ * 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.1  (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 common/utils/telnetsrv/telnetsrv_ltemeasur_def.h
+ * \brief: definitions of macro used to initialize the telnet_ltemeasurdef_t
+ * \        strucures arrays which are then used by the display functions
+ * \        in telnetsrv_measurements.c. 
+ * \author Francois TABURET
+ * \date 2019
+ * \version 0.1
+ * \company NOKIA BellLabs France
+ * \email: francois.taburet@nokia-bell-labs.com
+ * \note
+ * \warning
+ */
+
+
+#define LTEMAC_MEASURE \
+{ \
+  {"total_num_bcch_pdu",   &(macstatptr->total_num_bcch_pdu),TELNET_VARTYPE_INT32,0},\
+  {"bcch_buffer",	   &(macstatptr->bcch_buffer),TELNET_VARTYPE_INT32,0},\
+  {"total_bcch_buffer",	   &(macstatptr->total_bcch_buffer),TELNET_VARTYPE_INT32,0},\
+  {"bcch_mcs",	           &(macstatptr->bcch_mcs),TELNET_VARTYPE_INT32,0},\
+  {"total_num_ccch_pdu",   &(macstatptr->total_num_ccch_pdu),TELNET_VARTYPE_INT32,0},\
+  {"ccch_buffer",	   &(macstatptr->ccch_buffer),TELNET_VARTYPE_INT32,0},\
+  {"total_ccch_buffer",	   &(macstatptr->total_ccch_buffer),TELNET_VARTYPE_INT32,0},\
+  {"ccch_mcs",	           &(macstatptr->ccch_mcs),TELNET_VARTYPE_INT32,0},\
+  {"total_num_pcch_pdu",   &(macstatptr->total_num_pcch_pdu),TELNET_VARTYPE_INT32,0},\
+  {"pcch_buffer",	   &(macstatptr->pcch_buffer),TELNET_VARTYPE_INT32,0},\
+  {"total_pcch_buffer",	   &(macstatptr->total_pcch_buffer),TELNET_VARTYPE_INT32,0},\
+  {"pcch_mcs",	           &(macstatptr->pcch_mcs),TELNET_VARTYPE_INT32,0},\
+  {"num_dlactive_UEs",	   &(macstatptr->num_dlactive_UEs),TELNET_VARTYPE_INT16,0},\
+  {"available_prbs",	   &(macstatptr->available_prbs),TELNET_VARTYPE_INT16,0},\
+  {"total_available_prbs", &(macstatptr->total_available_prbs),TELNET_VARTYPE_INT32,0},\
+  {"available_ncces",	   &(macstatptr->available_ncces),TELNET_VARTYPE_INT16,0},\
+  {"dlsch_bitrate",	   &(macstatptr->dlsch_bitrate),TELNET_VARTYPE_INT32,0},\
+  {"dlsch_bytes_tx",	   &(macstatptr->dlsch_bytes_tx),TELNET_VARTYPE_INT32,0},\
+  {"dlsch_pdus_tx",	   &(macstatptr->dlsch_pdus_tx),TELNET_VARTYPE_INT32,0},\
+  {"total_dlsch_bitrate",  &(macstatptr->total_dlsch_bitrate),TELNET_VARTYPE_INT32,0},\
+  {"total_dlsch_bytes_tx", &(macstatptr->total_dlsch_bytes_tx),TELNET_VARTYPE_INT32,0},\
+  {"total_dlsch_pdus_tx",  &(macstatptr->total_dlsch_pdus_tx),TELNET_VARTYPE_INT32,0},\
+  {"ulsch_bitrate",	   &(macstatptr->ulsch_bitrate),TELNET_VARTYPE_INT32,0},\
+  {"ulsch_bytes_rx",	   &(macstatptr->ulsch_bytes_rx),TELNET_VARTYPE_INT32,0},\
+  {"ulsch_pdus_rx",	   &(macstatptr->ulsch_pdus_rx),TELNET_VARTYPE_INT32,0},\
+  {"total_ulsch_bitrate",  &(macstatptr->total_ulsch_bitrate),TELNET_VARTYPE_INT32,0},\
+  {"total_ulsch_bytes_rx", &(macstatptr->total_ulsch_bytes_rx),TELNET_VARTYPE_INT32,0},\
+  {"total_ulsch_pdus_rx",  &(macstatptr->total_ulsch_pdus_rx),TELNET_VARTYPE_INT32,0},\
+  {"sched_decisions",	   &(macstatptr->sched_decisions),TELNET_VARTYPE_INT32,0},\
+  {"missed_deadlines",	   &(macstatptr->missed_deadlines),TELNET_VARTYPE_INT32,0},\
+}
+
+#define LTEMAC_UEMEASURE \
+{ \
+  {"dlsch_mcs1",	   &(macuestatptr->dlsch_mcs1),TELNET_VARTYPE_INT8,0},\
+  {"dlsch_mcs2",	   &(macuestatptr->dlsch_mcs2),TELNET_VARTYPE_INT8,0},\
+  {"rbs_used",	           &(macuestatptr->rbs_used),TELNET_VARTYPE_INT32,0},\
+  {"rbs_used_retx",	   &(macuestatptr->rbs_used_retx),TELNET_VARTYPE_INT16,0},\
+  {"total_rbs_used",	   &(macuestatptr->total_rbs_used),TELNET_VARTYPE_INT16,0},\
+  {"ncce_used",	           &(macuestatptr->ncce_used),TELNET_VARTYPE_INT16,0},\
+  {"ncce_used_retx",	   &(macuestatptr->ncce_used_retx),TELNET_VARTYPE_INT16,0},\
+  {"TBS",	           &(macuestatptr->TBS),TELNET_VARTYPE_INT32,0},\
+  {"total_pdu_bytes",	   &(macuestatptr->total_pdu_bytes),TELNET_VARTYPE_INT64,0},\
+  {"total_num_pdus",	   &(macuestatptr->total_num_pdus),TELNET_VARTYPE_INT32,0},\
+  {"overhead_bytes",	   &(macuestatptr->overhead_bytes),TELNET_VARTYPE_INT64,0},\
+  {"crnti",	           &(macuestatptr->crnti),TELNET_VARTYPE_INT16,0},\
+  {"normalized_rx_power",  &(macuestatptr->normalized_rx_power),TELNET_VARTYPE_INT32,0},\
+  {"target_rx_power",	   &(macuestatptr->target_rx_power),TELNET_VARTYPE_INT32,0},\
+  {"ulsch_mcs1",	   &(macuestatptr->ulsch_mcs1),TELNET_VARTYPE_INT8,0},\
+  {"ulsch_mcs2",	   &(macuestatptr->ulsch_mcs2),TELNET_VARTYPE_INT8,0},\
+  {"rbs_used_rx",	   &(macuestatptr->rbs_used_rx),TELNET_VARTYPE_INT32,0},\
+  {"rbs_used_retx_rx",	   &(macuestatptr->rbs_used_retx_rx),TELNET_VARTYPE_INT32,0},\
+  {"total_rbs_used_rx",	   &(macuestatptr->total_rbs_used_rx),TELNET_VARTYPE_INT32,0},\
+  {"ulsch_TBS",	           &(macuestatptr->ulsch_TBS),TELNET_VARTYPE_INT32,0},\
+  {"total_pdu_bytes_rx",   &(macuestatptr->total_pdu_bytes_rx),TELNET_VARTYPE_INT64,0},\
+  {"total_num_pdus_rx",	   &(macuestatptr->total_num_pdus_rx),TELNET_VARTYPE_INT32,0},\
+  {"num_errors_rx",	   &(macuestatptr->num_errors_rx),TELNET_VARTYPE_INT32,0},\
+}
+
+#define LTE_RLCMEASURE \
+{ \
+  {"rlc_mode",                        NULL, TELNET_VARTYPE_UINT, 0},\
+  {"tx_pdcp_sdu",                     NULL, TELNET_VARTYPE_UINT, 0},\
+  {"tx_pdcp_bytes",                   NULL, TELNET_VARTYPE_UINT, 0},\
+  {"tx_pdcp_sdu_discarded",           NULL, TELNET_VARTYPE_UINT, 0},\
+  {"tx_pdcp_bytes_discarded",         NULL, TELNET_VARTYPE_UINT, 0},\
+  {"tx_data_pdu",                     NULL, TELNET_VARTYPE_UINT, 0},\
+  {"tx_data_bytes",                   NULL, TELNET_VARTYPE_UINT, 0},\
+  {"tx_retransmit_pdu_by_status",     NULL, TELNET_VARTYPE_UINT, 0},\
+  {"tx_retransmit_bytes_by_status",   NULL, TELNET_VARTYPE_UINT, 0},\
+  {"tx_retransmit_pdu",               NULL, TELNET_VARTYPE_UINT, 0},\
+  {"tx_retransmit_bytes",             NULL, TELNET_VARTYPE_UINT, 0},\
+  {"tx_control_pdu",                  NULL, TELNET_VARTYPE_UINT, 0},\
+  {"tx_control_bytes",                NULL, TELNET_VARTYPE_UINT, 0},\
+  {"rx_pdcp_sdu",                     NULL, TELNET_VARTYPE_UINT, 0},\
+  {"rx_pdcp_bytes",                   NULL, TELNET_VARTYPE_UINT, 0},\
+  {"rx_data_pdus_duplicate",          NULL, TELNET_VARTYPE_UINT, 0},\
+  {"rx_data_bytes_duplicate",         NULL, TELNET_VARTYPE_UINT, 0},\
+  {"rx_data_pdu",                     NULL, TELNET_VARTYPE_UINT, 0},\
+  {"rx_data_bytes",                   NULL, TELNET_VARTYPE_UINT, 0},\
+  {"rx_data_pdu_dropped",             NULL, TELNET_VARTYPE_UINT, 0},\
+  {"rx_data_bytes_dropped",           NULL, TELNET_VARTYPE_UINT, 0},\
+  {"rx_data_pdu_out_of_window",       NULL, TELNET_VARTYPE_UINT, 0},\
+  {"rx_data_bytes_out_of_window",     NULL, TELNET_VARTYPE_UINT, 0},\
+  {"rx_control_pdu",                  NULL, TELNET_VARTYPE_UINT, 0},\
+  {"rx_control_bytes",                NULL, TELNET_VARTYPE_UINT, 0},\
+  {"timer_reorder_tout",              NULL, TELNET_VARTYPE_UINT, 0},\
+  {"timer_poll_retrans_tout",         NULL, TELNET_VARTYPE_UINT, 0},\
+  {"timer_status_prohibit_tout",      NULL, TELNET_VARTYPE_UINT, 0},\
+}
diff --git a/common/utils/telnetsrv/telnetsrv_phycmd.c b/common/utils/telnetsrv/telnetsrv_phycmd.c
index 35554a77a6109cd062959f4d695eace094cb2be8..c60126f1c741e4d9d93323e761862d0f7458e561 100644
--- a/common/utils/telnetsrv/telnetsrv_phycmd.c
+++ b/common/utils/telnetsrv/telnetsrv_phycmd.c
@@ -29,7 +29,7 @@
  * \note
  * \warning
  */
-#define _GNU_SOURCE
+#define _GNU_SOURCE 
 #include <string.h>
 #include <pthread.h>
 
@@ -39,88 +39,104 @@
 #define TELNETSRV_PHYCMD_MAIN
 #include "telnetsrv_phycmd.h"
 char *prnbuff;
-extern int dump_eNB_l2_stats(char *buffer, int length);
-
-void init_phytelnet(void) {
-  prnbuff=malloc(get_phybsize() );
-
-  if (prnbuff == NULL) {
-    fprintf(stderr,"Error %s on malloc in init_phytelnet()\n",strerror(errno));
-  }
+extern int dump_eNB_stats(PHY_VARS_eNB *eNB, char* buffer, int length);
+
+void init_phytelnet(void)
+{
+prnbuff=malloc(get_phybsize() );
+if (prnbuff == NULL)
+   {
+   fprintf(stderr,"Error %s on malloc in init_phytelnet()\n",strerror(errno));
+   }
 }
 
-void display_uestatshead( telnet_printfunc_t prnt) {
-  prnt("cc  ue  rnti Dmcs Umcs tao  tau   Dbr  Dtb   \n");
+void display_uestatshead( telnet_printfunc_t prnt)
+{
+prnt("cc  ue  rnti Dmcs Umcs tao  tau   Dbr  Dtb   \n");
 }
 
-void dump_uestats(int debug, telnet_printfunc_t prnt, uint8_t prntflag) {
-  int p;
-  prnbuff=malloc(20480);
-  p=dump_eNB_l2_stats( prnbuff, 20480);
+void dump_uestats(int debug, telnet_printfunc_t prnt, uint8_t prntflag)
+{
+
+int p;
 
-  if(prntflag>=1)
-    prnt("%s\n",prnbuff);
+        p=dump_eNB_l2_stats( prnbuff, 0);
+	if(prntflag>=1)
+	   prnt("%s\n",prnbuff);
+	if(debug>=1)
+	   prnt("%i bytes printed\n",p);	   
 
-  if(debug>=1)
-    prnt("%i bytes printed\n",p);
 
-  free(prnbuff);
 }
 
-void display_uestats(int debug, telnet_printfunc_t prnt, int ue) {
-  for (int cc=0; cc<1 ; cc++) {
-  }
+void display_uestats(int debug, telnet_printfunc_t prnt, int ue)
+{
+   for (int cc=0; cc<1 ; cc++)
+       {
+ 
+ 
+       }
 }
 
-void display_phycounters(char *buf, int debug, telnet_printfunc_t prnt) {
-  prnt("  DLSCH kb      DLSCH kb/s\n");
-  dump_uestats(debug, prnt,0);
+void display_phycounters(char *buf, int debug, telnet_printfunc_t prnt)
+{    
+   prnt("  DLSCH kb      DLSCH kb/s\n");
+
+   dump_uestats(debug, prnt,0);
+
 }
 
-int dump_phyvars(char *buf, int debug, telnet_printfunc_t prnt) {
-  if (debug > 0)
-    prnt("phy interface module received %s\n",buf);
-
-  if (strcasestr(buf,"phycnt") != NULL) {
-    display_phycounters(buf, debug, prnt);
-  }
-
-  if (strcasestr(buf,"uestat") != NULL) {
-    char *cptr=strcasestr(buf+sizeof("uestat"),"UE");
-    display_uestatshead(prnt);
-
-    if (cptr != NULL) {
-      int ueidx = strtol( cptr+sizeof("UE"), NULL, 10);
-
-      if (ueidx < NUMBER_OF_UE_MAX && ueidx >= 0) {
-        display_uestats(debug, prnt,ueidx);
-      }
-    } /* if cptr != NULL */
-    else {
-      for (int ue=0; ue<NUMBER_OF_UE_MAX ; ue++) {
-        display_uestats(debug, prnt,ue);
-      }
-    } /* else cptr != NULL */
-  } /* uestat */
-
-  if (strcasestr(buf,"uedump") != NULL) {
-    dump_uestats(debug, prnt,1);
-  }
-
-  return 0;
+int dump_phyvars(char *buf, int debug, telnet_printfunc_t prnt)
+{
+   
+   
+
+   if (debug > 0)
+       prnt("phy interface module received %s\n",buf);
+   if (strcasestr(buf,"phycnt") != NULL)
+       {
+       display_phycounters(buf, debug, prnt);
+       }
+   if (strcasestr(buf,"uestat") != NULL)
+      {
+      char *cptr=strcasestr(buf+sizeof("uestat"),"UE");
+      display_uestatshead(prnt);
+      if (cptr != NULL)
+         {
+	 int ueidx = strtol( cptr+sizeof("UE"), NULL, 10);
+	 if (ueidx < NUMBER_OF_UE_MAX && ueidx >= 0)
+	    {
+	    display_uestats(debug, prnt,ueidx);
+	    }
+	 } /* if cptr != NULL */
+      else
+         {
+	 for (int ue=0; ue<NUMBER_OF_UE_MAX ; ue++)
+	     {
+	     display_uestats(debug, prnt,ue);
+	     }
+	 } /* else cptr != NULL */
+      } /* uestat */
+   if (strcasestr(buf,"uedump") != NULL)
+       {
+       dump_uestats(debug, prnt,1);
+       }           
+   return 0;
 }
 
 
 
 telnetshell_cmddef_t phy_cmdarray[] = {
-  {"disp","[phycnt,uedump,uestat UE<x>]", dump_phyvars},
+   {"disp","[phycnt,uedump,uestat UE<x>]", dump_phyvars},
 
-  {"","",NULL},
+   {"","",NULL},
 };
 
 
 /*-------------------------------------------------------------------------------------*/
-void add_phy_cmds(void) {
-  init_phytelnet();
-  add_telnetcmd("phy", phy_vardef, phy_cmdarray);
+void add_phy_cmds(void)
+{
+
+   init_phytelnet();
+   add_telnetcmd("phy", phy_vardef, phy_cmdarray);
 }
diff --git a/common/utils/telnetsrv/telnetsrv_proccmd.c b/common/utils/telnetsrv/telnetsrv_proccmd.c
index 3b423bd4655e47d15e711e972c4b5d722dbcafec..9dd512091d73331c73940a4bf604018a50e56577 100644
--- a/common/utils/telnetsrv/telnetsrv_proccmd.c
+++ b/common/utils/telnetsrv/telnetsrv_proccmd.c
@@ -183,7 +183,7 @@ struct dirent *entry;
         {
         if(entry->d_name[0] == '.')
             continue;
-	snprintf(aname, sizeof(aname), "/proc/%d/task/%s/stat", getpid(),entry->d_name);    
+	snprintf(aname, sizeof(aname), "/proc/%d/task/%.*s/stat", getpid(),(int)(sizeof(aname)-24),entry->d_name);    
         read_statfile(aname,debug,prnt);      
         } /* while entry != NULL */
 	closedir(proc_dir);
diff --git a/openair1/PHY/INIT/lte_param_init.c b/openair1/PHY/INIT/lte_param_init.c
index dd8c2e54dba3f4229fae2c3eb9f1e24076364c33..1be5f6d520d65846817ae33d01646983645bc55e 100644
--- a/openair1/PHY/INIT/lte_param_init.c
+++ b/openair1/PHY/INIT/lte_param_init.c
@@ -33,31 +33,29 @@
 #include "phy_init.h"
 #include "PHY/LTE_REFSIG/lte_refsig.h"
 #include "PHY/LTE_TRANSPORT/transport_common_proto.h"
-
+#include "targets/RT/USER/lte-softmodem.h"
 extern PHY_VARS_eNB *eNB;
 extern PHY_VARS_UE *UE;
 extern RU_t *ru;
-extern void  phy_init_RU(RU_t*);
+extern void  phy_init_RU(RU_t *);
 
 void lte_param_init(PHY_VARS_eNB **eNBp,
-		    PHY_VARS_UE **UEp,
-		    RU_t **rup,
-		    unsigned char N_tx_port_eNB,
+                    PHY_VARS_UE **UEp,
+                    RU_t **rup,
+                    unsigned char N_tx_port_eNB,
                     unsigned char N_tx_phy,
-		    unsigned char N_rx_ru,
+                    unsigned char N_rx_ru,
                     unsigned char N_rx_ue,
-		    unsigned char transmission_mode,
-		    uint8_t extended_prefix_flag,
-		    frame_t frame_type,
-		    uint16_t Nid_cell,
-		    uint8_t tdd_config,
-		    uint8_t N_RB_DL,
-		    uint8_t pa,
-		    uint8_t threequarter_fs,
+                    unsigned char transmission_mode,
+                    uint8_t extended_prefix_flag,
+                    frame_t frame_type,
+                    uint16_t Nid_cell,
+                    uint8_t tdd_config,
+                    uint8_t N_RB_DL,
+                    uint8_t pa,
+                    uint8_t threequarter_fs,
                     uint8_t osf,
-		    uint32_t perfect_ce)
-{
-
+                    uint32_t perfect_ce) {
   LTE_DL_FRAME_PARMS *frame_parms;
   int i;
   PHY_VARS_eNB *eNB;
@@ -71,23 +69,16 @@ void lte_param_init(PHY_VARS_eNB **eNBp,
   UE  = *UEp;
   ru  = *rup;
   printf("eNB %p, UE %p, ru %p\n",eNB,UE,ru);
-
-
-
-  memset((void*)eNB,0,sizeof(PHY_VARS_eNB));
-  memset((void*)UE,0,sizeof(PHY_VARS_UE));
-  memset((void*)ru,0,sizeof(RU_t));
-
+  memset((void *)eNB,0,sizeof(PHY_VARS_eNB));
+  memset((void *)UE,0,sizeof(PHY_VARS_UE));
+  memset((void *)ru,0,sizeof(RU_t));
   ru->eNB_list[0] = eNB;
   eNB->RU_list[0] = ru;
   ru->num_eNB=1;
-
   srand(0);
   randominit(0);
   set_taus_seed(0);
-
   frame_parms = &(eNB->frame_parms);
-
   frame_parms->N_RB_DL            = N_RB_DL;   //50 for 10MHz and 25 for 5 MHz
   frame_parms->N_RB_UL            = N_RB_DL;
   frame_parms->threequarter_fs    = threequarter_fs;
@@ -106,13 +97,9 @@ void lte_param_init(PHY_VARS_eNB **eNBp,
   //  frame_parms->Bsrs = 0;
   //  frame_parms->kTC = 0;44
   //  frame_parms->n_RRC = 0;
-
   init_frame_parms(frame_parms,osf);
-
   //copy_lte_parms_to_phy_framing(frame_parms, &(PHY_config->PHY_framing));
-
   //  phy_init_top(frame_parms); //allocation
-
   UE->is_secondary_ue = 0;
   UE->frame_parms = *frame_parms;
   UE->frame_parms.nb_antennas_rx=N_rx_ue;
@@ -121,14 +108,10 @@ void lte_param_init(PHY_VARS_eNB **eNBp,
   ru->nb_tx = N_tx_phy;
   ru->nb_rx = N_rx_ru;
   ru->if_south = LOCAL_RF;
-
   eNB->configured=1;
-
   eNB->transmission_mode[0] = transmission_mode;
   UE->transmission_mode[0] = transmission_mode;
-
   dump_frame_parms(frame_parms);
-
   UE->measurements.n_adj_cells=0;
   UE->measurements.adj_cell_id[0] = Nid_cell+1;
   UE->measurements.adj_cell_id[1] = Nid_cell+2;
@@ -144,7 +127,6 @@ void lte_param_init(PHY_VARS_eNB **eNBp,
   phy_init_RU(ru);
   generate_pcfich_reg_mapping(&UE->frame_parms);
   generate_phich_reg_mapping(&UE->frame_parms);
-
   // DL power control init
   //if (transmission_mode == 1) {
   UE->pdsch_config_dedicated->p_a  = pa;
@@ -166,17 +148,13 @@ void lte_param_init(PHY_VARS_eNB **eNBp,
     if      (eNB->frame_parms.N_RB_DL == 100) ru->N_TA_offset = 624;
     else if (eNB->frame_parms.N_RB_DL == 50)  ru->N_TA_offset = 624/2;
     else if (eNB->frame_parms.N_RB_DL == 25)  ru->N_TA_offset = 624/4;
-  }
-  else ru->N_TA_offset=0;
+  } else ru->N_TA_offset=0;
 
-#if BASIC_SIMULATOR
-  /* this is required for the basic simulator in TDD mode
-   * TODO: find a proper cleaner solution
-   */
-  UE->N_TA_offset = 0;
-#endif
+  if (IS_SOFTMODEM_BASICSIM)
+    /* this is required for the basic simulator in TDD mode
+     * TODO: find a proper cleaner solution
+     */
+    UE->N_TA_offset = 0;
 
   printf("Done lte_param_init\n");
-
-
 }
diff --git a/openair1/PHY/LTE_TRANSPORT/dci.c b/openair1/PHY/LTE_TRANSPORT/dci.c
index 6b5863edc96e0acbb620272b0e583f9b2ae0f231..edd063a09093639533fcc5bb9640bb757723b51c 100644
--- a/openair1/PHY/LTE_TRANSPORT/dci.c
+++ b/openair1/PHY/LTE_TRANSPORT/dci.c
@@ -45,7 +45,7 @@
 #include "common/utils/LOG/vcd_signal_dumper.h"
 #include "PHY/LTE_TRANSPORT/transport_extern.h"
 #include "PHY/LTE_REFSIG/lte_refsig.h"
-
+#include "targets/RT/USER/lte-softmodem.h"
 //#define DEBUG_DCI_ENCODING 1
 //#define DEBUG_DCI_DECODING 1
 //#define DEBUG_PHY
@@ -64,35 +64,26 @@ void dci_encoding(uint8_t *a,
                   uint8_t A,
                   uint16_t E,
                   uint8_t *e,
-                  uint16_t rnti)
-{
-
-
+                  uint16_t rnti) {
   uint8_t D = (A + 16);
   uint32_t RCC;
   uint8_t d[3*(MAX_DCI_SIZE_BITS + 16) + 96];
   uint8_t w[3*3*(MAX_DCI_SIZE_BITS+16)];
-
 #ifdef DEBUG_DCI_ENCODING
   int32_t i;
 #endif
   // encode dci
-
 #ifdef DEBUG_DCI_ENCODING
   printf("Doing DCI encoding for %d bits, e %p, rnti %x, E %d\n",A,e,rnti,E);
 #endif
-
   memset((void *)d,LTE_NULL,96);
-
   ccodelte_encode(A,2,a,d+96,rnti);
-
 #ifdef DEBUG_DCI_ENCODING
 
   for (i=0; i<16+A; i++)
     printf("%d : (%d,%d,%d)\n",i,*(d+96+(3*i)),*(d+97+(3*i)),*(d+98+(3*i)));
 
 #endif
-
 #ifdef DEBUG_DCI_ENCODING
   printf("Doing DCI interleaving for %d coded bits, e %p\n",D*3,e);
 #endif
@@ -100,27 +91,24 @@ void dci_encoding(uint8_t *a,
 
   //#ifdef DEBUG_DCI_ENCODING
   if (E>1000) printf("Doing DCI rate matching for %d channel bits, RCC %d, e %p\n",E,RCC,e);
+
   //#endif
   lte_rate_matching_cc(RCC,E,w,e);
-
-
-
 }
 
 
 uint8_t *generate_dci0(uint8_t *dci,
                        uint8_t *e,
                        uint8_t DCI_LENGTH,
-		       uint16_t coded_bits,
-                       uint16_t rnti)
-{
-
+                       uint16_t coded_bits,
+                       uint16_t rnti) {
   uint8_t dci_flip[8];
+#ifdef DEBUG_DCI_ENCODING
 
-  #ifdef DEBUG_DCI_ENCODING
-  for (int i=0;i<1+((DCI_LENGTH+16)/8);i++)
+  for (int i=0; i<1+((DCI_LENGTH+16)/8); i++)
     printf("i %d : %x\n",i,dci[i]);
-  #endif
+
+#endif
 
   if (DCI_LENGTH<=32) {
     dci_flip[0] = dci[3];
@@ -129,8 +117,7 @@ uint8_t *generate_dci0(uint8_t *dci,
     dci_flip[3] = dci[0];
 #ifdef DEBUG_DCI_ENCODING
     printf("DCI => %x,%x,%x,%x\n",
-	   dci_flip[0],dci_flip[1],dci_flip[2],dci_flip[3]);
-
+           dci_flip[0],dci_flip[1],dci_flip[2],dci_flip[3]);
 #endif
   } else {
     dci_flip[0] = dci[7];
@@ -143,13 +130,12 @@ uint8_t *generate_dci0(uint8_t *dci,
     dci_flip[7] = dci[0];
 #ifdef DEBUG_DCI_ENCODING
     printf("DCI => %x,%x,%x,%x,%x,%x,%x,%x\n",
-        dci_flip[0],dci_flip[1],dci_flip[2],dci_flip[3],
-        dci_flip[4],dci_flip[5],dci_flip[6],dci_flip[7]);
+           dci_flip[0],dci_flip[1],dci_flip[2],dci_flip[3],
+           dci_flip[4],dci_flip[5],dci_flip[6],dci_flip[7]);
 #endif
   }
 
   dci_encoding(dci_flip,DCI_LENGTH,coded_bits,e,rnti);
-
   return(e+coded_bits);
 }
 
@@ -160,9 +146,7 @@ uint8_t *generate_dci0(uint8_t *dci,
 
 
 
-void pdcch_interleaving(LTE_DL_FRAME_PARMS *frame_parms,int32_t **z, int32_t **wbar,uint8_t n_symbols_pdcch,uint8_t mi)
-{
-
+void pdcch_interleaving(LTE_DL_FRAME_PARMS *frame_parms,int32_t **z, int32_t **wbar,uint8_t n_symbols_pdcch,uint8_t mi) {
   int32_t *wptr,*wptr2,*zptr;
   uint32_t Mquad = get_nquad(n_symbols_pdcch,frame_parms,mi);
   uint32_t RCC = (Mquad>>5), ND;
@@ -180,7 +164,6 @@ void pdcch_interleaving(LTE_DL_FRAME_PARMS *frame_parms,int32_t **z, int32_t **w
 
   Kpi = (RCC<<5);
   ND = Kpi - Mquad;
-
   k=0;
 
   for (col=0; col<32; col++) {
@@ -191,12 +174,9 @@ void pdcch_interleaving(LTE_DL_FRAME_PARMS *frame_parms,int32_t **z, int32_t **w
       if (index>=ND) {
         for (a=0; a<frame_parms->nb_antenna_ports_eNB; a++) {
           //printf("a %d k %d\n",a,k);
-
           wptr = &wtemp[a][k<<2];
           zptr = &z[a][(index-ND)<<2];
-
           //printf("wptr=%p, zptr=%p\n",wptr,zptr);
-
           wptr[0] = zptr[0];
           wptr[1] = zptr[1];
           wptr[2] = zptr[2];
@@ -212,9 +192,7 @@ void pdcch_interleaving(LTE_DL_FRAME_PARMS *frame_parms,int32_t **z, int32_t **w
 
   // permutation
   for (i=0; i<Mquad; i++) {
-
     for (a=0; a<frame_parms->nb_antenna_ports_eNB; a++) {
-
       //wptr  = &wtemp[a][i<<2];
       //wptr2 = &wbar[a][((i+frame_parms->Nid_cell)%Mquad)<<2];
       wptr = &wtemp[a][((i+frame_parms->Nid_cell)%Mquad)<<2];
@@ -230,17 +208,13 @@ void pdcch_interleaving(LTE_DL_FRAME_PARMS *frame_parms,int32_t **z, int32_t **w
 void pdcch_scrambling(LTE_DL_FRAME_PARMS *frame_parms,
                       uint8_t subframe,
                       uint8_t *e,
-                      uint32_t length)
-{
+                      uint32_t length) {
   int i;
   uint8_t reset;
   uint32_t x1, x2, s=0;
-
   //LOG_D(PHY, "%s(fp, subframe:%d, e, length:%d)\n", __FUNCTION__, subframe, length);
-
   reset = 1;
   // x1 is set in lte_gold_generic
-
   x2 = (subframe<<9) + frame_parms->Nid_cell; //this is c_init in 36.211 Sec 6.8.2
 
   for (i=0; i<length; i++) {
@@ -257,16 +231,13 @@ void pdcch_scrambling(LTE_DL_FRAME_PARMS *frame_parms,
 }
 
 uint8_t generate_dci_top(uint8_t num_pdcch_symbols,
-			 uint8_t num_dci,
+                         uint8_t num_dci,
                          DCI_ALLOC_t *dci_alloc,
                          uint32_t n_rnti,
                          int16_t amp,
                          LTE_DL_FRAME_PARMS *frame_parms,
                          int32_t **txdataF,
-                         uint32_t subframe)
-{
-
-
+                         uint32_t subframe) {
   uint8_t *e_ptr;
   int8_t L;
   uint32_t i, lprime;
@@ -276,46 +247,42 @@ uint8_t generate_dci_top(uint8_t num_pdcch_symbols,
   uint8_t e[DCI_BITS_MAX];
   uint32_t Msymb=(DCI_BITS_MAX/2);
   int32_t yseq0[Msymb],yseq1[Msymb],wbar0[Msymb],wbar1[Msymb];
-
   int32_t *y[2];
   int32_t *wbar[2];
-
   int nushiftmod3 = frame_parms->nushift%3;
-
   int Msymb2;
   int split_flag=0;
 
   switch (frame_parms->N_RB_DL) {
-  case 100:
-    Msymb2 = Msymb;
-    break;
+    case 100:
+      Msymb2 = Msymb;
+      break;
 
-  case 75:
-    Msymb2 = 3*Msymb/4;
-    break;
+    case 75:
+      Msymb2 = 3*Msymb/4;
+      break;
 
-  case 50:
-    Msymb2 = Msymb>>1;
-    break;
+    case 50:
+      Msymb2 = Msymb>>1;
+      break;
 
-  case 25:
-    Msymb2 = Msymb>>2;
-    break;
+    case 25:
+      Msymb2 = Msymb>>2;
+      break;
 
-  case 15:
-    Msymb2 = Msymb*15/100;
-    break;
+    case 15:
+      Msymb2 = Msymb*15/100;
+      break;
 
-  case 6:
-    Msymb2 = Msymb*6/100;
-    break;
+    case 6:
+      Msymb2 = Msymb*6/100;
+      break;
 
-  default:
-    Msymb2 = Msymb>>2;
-    break;
+    default:
+      Msymb2 = Msymb>>2;
+      break;
   }
 
-
   VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_GENERATE_PCFICH,1);
   generate_pcfich(num_pdcch_symbols,
                   amp,
@@ -328,42 +295,37 @@ uint8_t generate_dci_top(uint8_t num_pdcch_symbols,
   y[0] = &yseq0[0];
   y[1] = &yseq1[0];
 
-#if BASIC_SIMULATOR
-  /* this should be the normal case
-   * but it has to be validated for all the various cases
-   * so let's just do it for the basic simulator
-   */
-  memset(e, 2, DCI_BITS_MAX);
-#else
-#if 1
-  // reset all bits to <NIL>, here we set <NIL> elements as 2
-  // memset(e, 2, DCI_BITS_MAX);
-  // here we interpret NIL as a random QPSK sequence. That makes power estimation easier.
-  for (i=0; i<DCI_BITS_MAX; i++)
-    e[i]=taus()&1;
-#endif
-
-  /* clear all bits, the above code may generate too much false detections
-   * (not sure about this, to be checked somehow)
-   */
-  //memset(e, 0, DCI_BITS_MAX);
-#endif /* BASIC_SIMULATOR */
+  if (IS_SOFTMODEM_BASICSIM) {
+    /* this should be the normal case
+     * but it has to be validated for all the various cases
+     * so let's just do it for the basic simulator
+     */
+    //  memset(e, 2, DCI_BITS_MAX);
+  } else {
+    // reset all bits to <NIL>, here we set <NIL> elements as 2
+    // memset(e, 2, DCI_BITS_MAX);
+    // here we interpret NIL as a random QPSK sequence. That makes power estimation easier.
+    for (i=0; i<DCI_BITS_MAX; i++)
+      e[i]=taus()&1;
+
+    /* clear all bits, the above code may generate too much false detections
+     * (not sure about this, to be checked somehow)
+     */
+    //memset(e, 0, DCI_BITS_MAX);
+  }/* BASIC_SIMULATOR */
 
   e_ptr = e;
-
   VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_GENERATE_DCI0,1);
 
   // generate DCIs in order of decreasing aggregation level, then common/ue spec
   // MAC is assumed to have ordered the UE spec DCI according to the RNTI-based randomization
   for (L=8; L>=1; L>>=1) {
     for (i=0; i<num_dci; i++) {
-
       if (dci_alloc[i].L == (uint8_t)L) {
-
         LOG_D(PHY,"Generating DCI %d/%d (nCCE %d) of length %d, aggregation %d (%x), rnti %x\n",
               i,num_dci,dci_alloc[i].firstCCE,dci_alloc[i].dci_length,dci_alloc[i].L,
-		*(unsigned int*)dci_alloc[i].dci_pdu,
-		dci_alloc[i].rnti);
+              *(unsigned int *)dci_alloc[i].dci_pdu,
+              dci_alloc[i].rnti);
 
         if (dci_alloc[i].firstCCE>=0) {
           e_ptr = generate_dci0(dci_alloc[i].dci_pdu,
@@ -375,14 +337,13 @@ uint8_t generate_dci_top(uint8_t num_pdcch_symbols,
       }
     }
   }
-  VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_GENERATE_DCI0,0);
 
+  VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_GENERATE_DCI0,0);
   // Scrambling
 #ifdef DEBUG_DCI_ENCODING
   printf("pdcch scrambling\n");
 #endif
   //LOG_D(PHY, "num_pdcch_symbols:%d mi:%d nquad:%d\n", num_pdcch_symbols, mi, get_nquad(num_pdcch_symbols, frame_parms, mi));
-
   VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_PDCCH_SCRAMBLING,1);
   pdcch_scrambling(frame_parms,
                    subframe,
@@ -390,11 +351,8 @@ uint8_t generate_dci_top(uint8_t num_pdcch_symbols,
                    8*get_nquad(num_pdcch_symbols, frame_parms, mi));
   VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_PDCCH_SCRAMBLING,0);
   //72*get_nCCE(num_pdcch_symbols,frame_parms,mi));
-
-
-
-
   VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_PDCCH_MODULATION,1);
+
   // Now do modulation
   if (frame_parms->nb_antenna_ports_eNB==1)
     gain_lin_QPSK = (int16_t)((amp*ONE_OVER_SQRT2_Q15)>>15);
@@ -402,7 +360,6 @@ uint8_t generate_dci_top(uint8_t num_pdcch_symbols,
     gain_lin_QPSK = amp/2;
 
   e_ptr = e;
-
 #ifdef DEBUG_DCI_ENCODING
   printf(" PDCCH Modulation, Msymb %d, Msymb2 %d,gain_lin_QPSK %d\n",Msymb,Msymb2,gain_lin_QPSK);
 #endif
@@ -410,91 +367,73 @@ uint8_t generate_dci_top(uint8_t num_pdcch_symbols,
   //LOG_D(PHY,"%s() Msymb2:%d\n", __FUNCTION__, Msymb2);
 
   if (frame_parms->nb_antenna_ports_eNB==1) { //SISO
-
-
     for (i=0; i<Msymb2; i++) {
-
       //((int16_t*)(&(y[0][i])))[0] = (*e_ptr == 1) ? -gain_lin_QPSK : gain_lin_QPSK;
       //((int16_t*)(&(y[1][i])))[0] = (*e_ptr == 1) ? -gain_lin_QPSK : gain_lin_QPSK;
-      ((int16_t*)(&(y[0][i])))[0] = (*e_ptr == 2) ? 0 : (*e_ptr == 1) ? -gain_lin_QPSK : gain_lin_QPSK;
-      ((int16_t*)(&(y[1][i])))[0] = (*e_ptr == 2) ? 0 : (*e_ptr == 1) ? -gain_lin_QPSK : gain_lin_QPSK;
+      ((int16_t *)(&(y[0][i])))[0] = (*e_ptr == 2) ? 0 : (*e_ptr == 1) ? -gain_lin_QPSK : gain_lin_QPSK;
+      ((int16_t *)(&(y[1][i])))[0] = (*e_ptr == 2) ? 0 : (*e_ptr == 1) ? -gain_lin_QPSK : gain_lin_QPSK;
       e_ptr++;
       //((int16_t*)(&(y[0][i])))[1] = (*e_ptr == 1) ? -gain_lin_QPSK : gain_lin_QPSK;
       //((int16_t*)(&(y[1][i])))[1] = (*e_ptr == 1) ? -gain_lin_QPSK : gain_lin_QPSK;
-      ((int16_t*)(&(y[0][i])))[1] = (*e_ptr == 2) ? 0 : (*e_ptr == 1) ? -gain_lin_QPSK : gain_lin_QPSK;
-      ((int16_t*)(&(y[1][i])))[1] = (*e_ptr == 2) ? 0 : (*e_ptr == 1) ? -gain_lin_QPSK : gain_lin_QPSK;
-
+      ((int16_t *)(&(y[0][i])))[1] = (*e_ptr == 2) ? 0 : (*e_ptr == 1) ? -gain_lin_QPSK : gain_lin_QPSK;
+      ((int16_t *)(&(y[1][i])))[1] = (*e_ptr == 2) ? 0 : (*e_ptr == 1) ? -gain_lin_QPSK : gain_lin_QPSK;
       e_ptr++;
     }
   } else { //ALAMOUTI
-
-
     for (i=0; i<Msymb2; i+=2) {
-
 #ifdef DEBUG_DCI_ENCODING
       printf(" PDCCH Modulation (TX diversity): REG %d\n",i>>2);
 #endif
       // first antenna position n -> x0
-      ((int16_t*)&y[0][i])[0] = (*e_ptr==2) ? 0 : (*e_ptr == 1) ? -gain_lin_QPSK : gain_lin_QPSK;
+      ((int16_t *)&y[0][i])[0] = (*e_ptr==2) ? 0 : (*e_ptr == 1) ? -gain_lin_QPSK : gain_lin_QPSK;
       e_ptr++;
-      ((int16_t*)&y[0][i])[1] = (*e_ptr==2) ? 0 : (*e_ptr == 1) ? -gain_lin_QPSK : gain_lin_QPSK;
+      ((int16_t *)&y[0][i])[1] = (*e_ptr==2) ? 0 : (*e_ptr == 1) ? -gain_lin_QPSK : gain_lin_QPSK;
       e_ptr++;
-
       // second antenna position n -> -x1*
-      ((int16_t*)&y[1][i])[0] = (*e_ptr==2) ? 0 : (*e_ptr == 1) ? gain_lin_QPSK : -gain_lin_QPSK;
+      ((int16_t *)&y[1][i])[0] = (*e_ptr==2) ? 0 : (*e_ptr == 1) ? gain_lin_QPSK : -gain_lin_QPSK;
       e_ptr++;
-      ((int16_t*)&y[1][i])[1] = (*e_ptr==2) ? 0 : (*e_ptr == 1) ? -gain_lin_QPSK : gain_lin_QPSK;
+      ((int16_t *)&y[1][i])[1] = (*e_ptr==2) ? 0 : (*e_ptr == 1) ? -gain_lin_QPSK : gain_lin_QPSK;
       e_ptr++;
-
       // fill in the rest of the ALAMOUTI precoding
-      ((int16_t*)&y[0][i+1])[0] = -((int16_t*)&y[1][i])[0];
-      ((int16_t*)&y[0][i+1])[1] = ((int16_t*)&y[1][i])[1];
-      ((int16_t*)&y[1][i+1])[0] = ((int16_t*)&y[0][i])[0];
-      ((int16_t*)&y[1][i+1])[1] = -((int16_t*)&y[0][i])[1];
-
+      ((int16_t *)&y[0][i+1])[0] = -((int16_t *)&y[1][i])[0];
+      ((int16_t *)&y[0][i+1])[1] = ((int16_t *)&y[1][i])[1];
+      ((int16_t *)&y[1][i+1])[0] = ((int16_t *)&y[0][i])[0];
+      ((int16_t *)&y[1][i+1])[1] = -((int16_t *)&y[0][i])[1];
     }
   }
-  VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_PDCCH_MODULATION,0);
-
 
+  VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_PDCCH_MODULATION,0);
 #ifdef DEBUG_DCI_ENCODING
   printf(" PDCCH Interleaving\n");
 #endif
-
   VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_PDCCH_INTERLEAVING,1);
   //  printf("y %p (%p,%p), wbar %p (%p,%p)\n",y,y[0],y[1],wbar,wbar[0],wbar[1]);
   // This is the interleaving procedure defined in 36-211, first part of Section 6.8.5
   pdcch_interleaving(frame_parms,&y[0],&wbar[0],num_pdcch_symbols,mi);
   VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_PDCCH_INTERLEAVING,0);
-
   VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_PDCCH_TX,1);
   mprime=0;
   nsymb = (frame_parms->Ncp==0) ? 14:12;
   re_offset = frame_parms->first_carrier_offset;
-
   // This is the REG allocation algorithm from 36-211, second part of Section 6.8.5
   //  printf("DCI (SF %d) : txdataF %p (0 %p)\n",subframe,&txdataF[0][512*14*subframe],&txdataF[0][0]);
 #ifdef DEBUG_DCI_ENCODING
   printf("kprime loop - N_RB_DL:%d lprime:num_pdcch_symbols:%d Ncp:%d pcfich:%02x,%02x,%02x,%02x ofdm_symbol_size:%d first_carrier_offset:%d nb_antenna_ports_eNB:%d\n",
-  frame_parms->N_RB_DL, num_pdcch_symbols,frame_parms->Ncp,
-  frame_parms->pcfich_reg[0],
-  frame_parms->pcfich_reg[1],
-  frame_parms->pcfich_reg[2],
-  frame_parms->pcfich_reg[3],
-  frame_parms->ofdm_symbol_size,
-  frame_parms->first_carrier_offset,
-  frame_parms->nb_antenna_ports_eNB
-  );
+         frame_parms->N_RB_DL, num_pdcch_symbols,frame_parms->Ncp,
+         frame_parms->pcfich_reg[0],
+         frame_parms->pcfich_reg[1],
+         frame_parms->pcfich_reg[2],
+         frame_parms->pcfich_reg[3],
+         frame_parms->ofdm_symbol_size,
+         frame_parms->first_carrier_offset,
+         frame_parms->nb_antenna_ports_eNB
+        );
 #endif
+
   for (kprime=0; kprime<frame_parms->N_RB_DL*12; kprime++) {
     for (lprime=0; lprime<num_pdcch_symbols; lprime++) {
-
       symbol_offset = (uint32_t)frame_parms->ofdm_symbol_size*(lprime+(subframe*nsymb));
-
-
-
       tti_offset = symbol_offset + re_offset;
-
       (re_offset==(frame_parms->ofdm_symbol_size-2)) ? (split_flag=1) : (split_flag=0);
 
       //            printf("kprime %d, lprime %d => REG %d (symbol %d)\n",kprime,lprime,(lprime==0)?(kprime/6) : (kprime>>2),symbol_offset);
@@ -505,16 +444,13 @@ uint8_t generate_dci_top(uint8_t num_pdcch_symbols,
 #endif
       } else {
         // Copy REG to TX buffer
-
         if ((lprime == 0)||
             ((lprime==1)&&(frame_parms->nb_antenna_ports_eNB == 4))) {
           // first symbol, or second symbol+4 TX antennas skip pilots
-
           kprime_mod12 = kprime%12;
 
           if ((kprime_mod12 == 0) || (kprime_mod12 == 6)) {
             // kprime represents REG
-
             for (i=0; i<6; i++) {
               if ((i!=(nushiftmod3))&&(i!=(nushiftmod3+3))) {
                 txdataF[0][tti_offset+i] = wbar[0][mprime];
@@ -523,9 +459,8 @@ uint8_t generate_dci_top(uint8_t num_pdcch_symbols,
                   txdataF[1][tti_offset+i] = wbar[1][mprime];
 
 #ifdef DEBUG_DCI_ENCODING
-                printf(" PDCCH mapping mprime %d => %d (symbol %d re %d) -> (%d,%d)\n",mprime,tti_offset,symbol_offset,re_offset+i,*(short*)&wbar[0][mprime],*(1+(short*)&wbar[0][mprime]));
+                printf(" PDCCH mapping mprime %d => %d (symbol %d re %d) -> (%d,%d)\n",mprime,tti_offset,symbol_offset,re_offset+i,*(short *)&wbar[0][mprime],*(1+(short *)&wbar[0][mprime]));
 #endif
-
                 mprime++;
               }
             }
@@ -543,7 +478,7 @@ uint8_t generate_dci_top(uint8_t num_pdcch_symbols,
                   txdataF[1][tti_offset+i] = wbar[1][mprime];
 
 #ifdef DEBUG_DCI_ENCODING
-                LOG_I(PHY," PDCCH mapping mprime %d => %d (symbol %d re %d) -> (%d,%d)\n",mprime,tti_offset,symbol_offset,re_offset+i,*(short*)&wbar[0][mprime],*(1+(short*)&wbar[0][mprime]));
+                LOG_I(PHY," PDCCH mapping mprime %d => %d (symbol %d re %d) -> (%d,%d)\n",mprime,tti_offset,symbol_offset,re_offset+i,*(short *)&wbar[0][mprime],*(1+(short *)&wbar[0][mprime]));
 #endif
                 mprime++;
               }
@@ -554,7 +489,7 @@ uint8_t generate_dci_top(uint8_t num_pdcch_symbols,
                 txdataF[1][tti_offset+0] = wbar[1][mprime];
 
 #ifdef DEBUG_DCI_ENCODING
-              printf(" PDCCH mapping mprime %d => %d (symbol %d re %d) -> (%d,%d)\n",mprime,tti_offset,symbol_offset,re_offset,*(short*)&wbar[0][mprime],*(1+(short*)&wbar[0][mprime]));
+              printf(" PDCCH mapping mprime %d => %d (symbol %d re %d) -> (%d,%d)\n",mprime,tti_offset,symbol_offset,re_offset,*(short *)&wbar[0][mprime],*(1+(short *)&wbar[0][mprime]));
 #endif
               mprime++;
               txdataF[0][tti_offset+1] = wbar[0][mprime];
@@ -563,7 +498,7 @@ uint8_t generate_dci_top(uint8_t num_pdcch_symbols,
                 txdataF[1][tti_offset+1] = wbar[1][mprime];
 
 #ifdef DEBUG_DCI_ENCODING
-              printf("PDCCH mapping mprime %d => %d (symbol %d re %d) -> (%d,%d)\n",mprime,tti_offset,symbol_offset,re_offset+1,*(short*)&wbar[0][mprime],*(1+(short*)&wbar[0][mprime]));
+              printf("PDCCH mapping mprime %d => %d (symbol %d re %d) -> (%d,%d)\n",mprime,tti_offset,symbol_offset,re_offset+1,*(short *)&wbar[0][mprime],*(1+(short *)&wbar[0][mprime]));
 #endif
               mprime++;
               txdataF[0][tti_offset-frame_parms->ofdm_symbol_size+3] = wbar[0][mprime];
@@ -572,8 +507,8 @@ uint8_t generate_dci_top(uint8_t num_pdcch_symbols,
                 txdataF[1][tti_offset-frame_parms->ofdm_symbol_size+3] = wbar[1][mprime];
 
 #ifdef DEBUG_DCI_ENCODING
-              printf(" PDCCH mapping mprime %d => %d (symbol %d re %d) -> (%d,%d)\n",mprime,tti_offset,symbol_offset,re_offset-frame_parms->ofdm_symbol_size+3,*(short*)&wbar[0][mprime],
-                    *(1+(short*)&wbar[0][mprime]));
+              printf(" PDCCH mapping mprime %d => %d (symbol %d re %d) -> (%d,%d)\n",mprime,tti_offset,symbol_offset,re_offset-frame_parms->ofdm_symbol_size+3,*(short *)&wbar[0][mprime],
+                     *(1+(short *)&wbar[0][mprime]));
 #endif
               mprime++;
               txdataF[0][tti_offset-frame_parms->ofdm_symbol_size+4] = wbar[0][mprime];
@@ -582,11 +517,10 @@ uint8_t generate_dci_top(uint8_t num_pdcch_symbols,
                 txdataF[1][tti_offset-frame_parms->ofdm_symbol_size+4] = wbar[1][mprime];
 
 #ifdef DEBUG_DCI_ENCODING
-              printf(" PDCCH mapping mprime %d => %d (symbol %d re %d) -> (%d,%d)\n",mprime,tti_offset,symbol_offset,re_offset-frame_parms->ofdm_symbol_size+4,*(short*)&wbar[0][mprime],
-                    *(1+(short*)&wbar[0][mprime]));
+              printf(" PDCCH mapping mprime %d => %d (symbol %d re %d) -> (%d,%d)\n",mprime,tti_offset,symbol_offset,re_offset-frame_parms->ofdm_symbol_size+4,*(short *)&wbar[0][mprime],
+                     *(1+(short *)&wbar[0][mprime]));
 #endif
               mprime++;
-
             }
           }
         }
@@ -594,7 +528,6 @@ uint8_t generate_dci_top(uint8_t num_pdcch_symbols,
         if (mprime>=Msymb2)
           return(num_pdcch_symbols);
       } // check_phich_reg
-
     } //lprime loop
 
     re_offset++;
@@ -602,8 +535,8 @@ uint8_t generate_dci_top(uint8_t num_pdcch_symbols,
     if (re_offset == (frame_parms->ofdm_symbol_size))
       re_offset = 1;
   } // kprime loop
-  VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_PDCCH_TX,0);
 
+  VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_PDCCH_TX,0);
   return(num_pdcch_symbols);
 }
 
diff --git a/openair1/PHY/LTE_TRANSPORT/pss.c b/openair1/PHY/LTE_TRANSPORT/pss.c
index 33bd5cc7e8246f06b49ec8e85b30072cd4d10f33..9ebd841430927e1c165d14234099948f37f0793b 100644
--- a/openair1/PHY/LTE_TRANSPORT/pss.c
+++ b/openair1/PHY/LTE_TRANSPORT/pss.c
@@ -38,72 +38,65 @@
 //#include "defs.h"
 #include "PHY/defs_eNB.h"
 #include "PHY/phy_extern.h"
+#include "targets/RT/USER/lte-softmodem.h"
 
 int generate_pss(int32_t **txdataF,
                  short amp,
                  LTE_DL_FRAME_PARMS *frame_parms,
                  unsigned short symbol,
-                 unsigned short slot_offset)
-{
-
+                 unsigned short slot_offset) {
   unsigned int Nsymb;
   unsigned short k,m,aa,a;
   uint8_t Nid2;
   short *primary_sync;
-
-
   Nid2 = frame_parms->Nid_cell % 3;
 
   switch (Nid2) {
-  case 0:
-    primary_sync = primary_synch0;
-    break;
+    case 0:
+      primary_sync = primary_synch0;
+      break;
 
-  case 1:
-    primary_sync = primary_synch1;
-    break;
+    case 1:
+      primary_sync = primary_synch1;
+      break;
 
-  case 2:
-    primary_sync = primary_synch2;
-    break;
+    case 2:
+      primary_sync = primary_synch2;
+      break;
 
-  default:
-    LOG_E(PHY,"[PSS] eNb_id has to be 0,1,2\n");
-    return(-1);
+    default:
+      LOG_E(PHY,"[PSS] eNb_id has to be 0,1,2\n");
+      return(-1);
   }
 
   a = (frame_parms->nb_antenna_ports_eNB == 1) ? amp: (amp*ONE_OVER_SQRT2_Q15)>>15;
   //printf("[PSS] amp=%d, a=%d\n",amp,a);
 
-#if BASIC_SIMULATOR
-  /* a hack to remove at some point (the UE doesn't synch with 100 RBs) */
-  a = (frame_parms->nb_antenna_ports_eNB == 1) ? 4*amp: (amp*ONE_OVER_SQRT2_Q15)>>15;
-#endif
+  if (IS_SOFTMODEM_BASICSIM)
+    /* a hack to remove at some point (the UE doesn't synch with 100 RBs) */
+    a = (frame_parms->nb_antenna_ports_eNB == 1) ? 4*amp: (amp*ONE_OVER_SQRT2_Q15)>>15;
 
   Nsymb = (frame_parms->Ncp==NORMAL)?14:12;
 
   for (aa=0; aa<frame_parms->nb_antenna_ports_eNB; aa++) {
     //  aa = 0;
-
     // The PSS occupies the inner 6 RBs, which start at
     k = frame_parms->ofdm_symbol_size-3*12+5;
 
     //printf("[PSS] k = %d\n",k);
     for (m=5; m<67; m++) {
-      ((short*)txdataF[aa])[2*(slot_offset*Nsymb/2*frame_parms->ofdm_symbol_size +
-                               symbol*frame_parms->ofdm_symbol_size + k)] =
-                                 (a * primary_sync[2*m]) >> 15;
-      ((short*)txdataF[aa])[2*(slot_offset*Nsymb/2*frame_parms->ofdm_symbol_size +
-                               symbol*frame_parms->ofdm_symbol_size + k) + 1] =
-                                 (a * primary_sync[2*m+1]) >> 15;
-
+      ((short *)txdataF[aa])[2*(slot_offset*Nsymb/2*frame_parms->ofdm_symbol_size +
+                                symbol*frame_parms->ofdm_symbol_size + k)] =
+                                  (a * primary_sync[2*m]) >> 15;
+      ((short *)txdataF[aa])[2*(slot_offset*Nsymb/2*frame_parms->ofdm_symbol_size +
+                                symbol*frame_parms->ofdm_symbol_size + k) + 1] =
+                                  (a * primary_sync[2*m+1]) >> 15;
       k+=1;
 
       if (k >= frame_parms->ofdm_symbol_size) {
         k++; //skip DC
         k-=frame_parms->ofdm_symbol_size;
       }
-
     }
   }
 
diff --git a/openair1/SIMULATION/ETH_TRANSPORT/netlink_init.c b/openair1/SIMULATION/ETH_TRANSPORT/netlink_init.c
index 358a561c21ca9d52e9471c047287546e4591a435..5a5f9852b101f5a6b4881dd1d3c8ad10ac5c32c6 100644
--- a/openair1/SIMULATION/ETH_TRANSPORT/netlink_init.c
+++ b/openair1/SIMULATION/ETH_TRANSPORT/netlink_init.c
@@ -63,7 +63,6 @@ struct msghdr nas_msg_rx;
 
 #define GRAAL_NETLINK_ID 31
 
-
 static int tun_alloc(char *dev) {
   struct ifreq ifr;
   int fd, err;
@@ -93,12 +92,12 @@ static int tun_alloc(char *dev) {
   return fd;
 }
 
-int netlink_init_tun(void) {
+int netlink_init_tun(char *ifprefix) {
   int ret;
   char ifname[64];
 
   for (int i = 0; i < NUMBER_OF_UE_MAX; i++) {
-    sprintf(ifname, "oaitun_ue%d",i+1);
+    sprintf(ifname, "oaitun_%.3s%d",ifprefix,i+1);
     nas_sock_fd[i] = tun_alloc(ifname);
 
     if (nas_sock_fd[i] == -1) {
diff --git a/openair1/SIMULATION/ETH_TRANSPORT/proto.h b/openair1/SIMULATION/ETH_TRANSPORT/proto.h
index 6d54bfb24cd9d3a2f2c682c93a8001ef54c40fb9..d84322da31faacc25cacf54aa954b2a8642a1ab1 100644
--- a/openair1/SIMULATION/ETH_TRANSPORT/proto.h
+++ b/openair1/SIMULATION/ETH_TRANSPORT/proto.h
@@ -62,6 +62,6 @@ int multicast_link_read_data_from_sock(uint8_t eNB_flag);
 void clear_eNB_transport_info(uint8_t);
 void clear_UE_transport_info(uint8_t);
 int netlink_init(void);
-int netlink_init_tun(void);
+int netlink_init_tun(char *ifsuffix);
 
 #endif /* EMU_PROTO_H_ */
diff --git a/openair1/SIMULATION/LTE_PHY/dlsim.c b/openair1/SIMULATION/LTE_PHY/dlsim.c
index 64a41e829867e18e47d6aac515843822b20cfaa5..c7916b8dfc22a631251abe49f7838d4bdda748df 100644
--- a/openair1/SIMULATION/LTE_PHY/dlsim.c
+++ b/openair1/SIMULATION/LTE_PHY/dlsim.c
@@ -782,13 +782,15 @@ int main(int argc, char **argv) {
         break;
 
       case 'u':
-        dual_stream_UE=1; 
-	if (UE != NULL)
-           UE->use_ia_receiver = 1;
+        dual_stream_UE=1;
+
+        if (UE != NULL)
+          UE->use_ia_receiver = 1;
         else {
           printf("UE  is NULL\n");
-          exit(-1);	
-	}
+          exit(-1);
+        }
+
         if ((n_tx_port!=2) || (transmission_mode!=5)) {
           printf("IA receiver only supported for TM5!");
           exit(-1);
@@ -951,8 +953,8 @@ int main(int argc, char **argv) {
         fl_set_object_label(form_ue->button_0, "IA Receiver ON");
         fl_set_object_color(form_ue->button_0, FL_GREEN, FL_GREEN);
       } else {
-          printf("UE  is NULL\n");
-          exit(-1);	
+        printf("UE  is NULL\n");
+        exit(-1);
       }
     }
   }
@@ -2139,5 +2141,7 @@ int main(int argc, char **argv) {
   else
     return(0);
 }
-
-
+/* temporary dummy implem of get_softmodem_optmask, till basic simulators implemented as device */
+uint64_t get_softmodem_optmask(void) {
+  return 0;
+}
diff --git a/openair1/SIMULATION/LTE_PHY/ulsim.c b/openair1/SIMULATION/LTE_PHY/ulsim.c
index 0c17e21acc647ea7489860fed86e7fd73a3ffd22..3e9623dc2fa5059d9fec9a26315c0baebe9b60b7 100644
--- a/openair1/SIMULATION/LTE_PHY/ulsim.c
+++ b/openair1/SIMULATION/LTE_PHY/ulsim.c
@@ -1211,9 +1211,7 @@ int main(int argc, char **argv) {
               }
 
               dump_ulsch(eNB,eNB->proc.frame_rx,subframe,0,round);
-
               round=5;
-              
             }
 
             if (n_frames==1) printf("round %d errors %u/%u\n",round,errs[round],trials);
@@ -1509,5 +1507,7 @@ int main(int argc, char **argv) {
   return(0);
 }
 
-
-
+/* temporary dummy implem of get_softmodem_optmask, till basic simulators implemented as device */
+uint64_t get_softmodem_optmask(void) {
+  return 0;
+}
diff --git a/openair2/LAYER2/PDCP_v10.1.0/pdcp.c b/openair2/LAYER2/PDCP_v10.1.0/pdcp.c
index 76e36dca9a0438a951d6718ed30515ead6140656..99736939c49c0b07dece41b82b25a0378becb734 100644
--- a/openair2/LAYER2/PDCP_v10.1.0/pdcp.c
+++ b/openair2/LAYER2/PDCP_v10.1.0/pdcp.c
@@ -51,7 +51,7 @@
 #include "targets/COMMON/openairinterface5g_limits.h"
 #include "SIMULATION/ETH_TRANSPORT/proto.h"
 #include "UTIL/OSA/osa_defs.h"
-
+#include "openair2/RRC/NAS/nas_config.h"
 # include "intertask_interface.h"
 
 
@@ -440,7 +440,6 @@ pdcp_data_ind(
   uint32_t    rx_hfn_for_count;
   int         pdcp_sn_for_count;
   int         security_ok;
-
   VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_PDCP_DATA_IND,VCD_FUNCTION_IN);
   LOG_DUMPMSG(PDCP,DEBUG_PDCP,(char *)sdu_buffer_pP->data,sdu_buffer_sizeP,
               "[MSG] PDCP UL %s PDU on rb_id %d\n", (srb_flagP)? "CONTROL" : "DATA", rb_idP);
@@ -567,6 +566,7 @@ pdcp_data_ind(
     }
 
 #if 0
+
     /* Removed by Cedric */
     if (pdcp_is_rx_seq_number_valid(sequence_number, pdcp_p, srb_flagP) == TRUE) {
       LOG_T(PDCP, "Incoming PDU has a sequence number (%d) in accordance with RX window\n", sequence_number);
@@ -588,6 +588,7 @@ pdcp_data_ind(
       free_mem_block(sdu_buffer_pP, __func__);
       return FALSE;
     }
+
 #endif
 
     // SRB1/2: control-plane data
@@ -678,158 +679,156 @@ pdcp_data_ind(
     payload_offset=pdcp_header_len;// PDCP_USER_PLANE_DATA_PDU_LONG_SN_HEADER_SIZE;
 
     switch (pdcp_p->rlc_mode) {
-    case RLC_MODE_AM: {
-      /* process as described in 36.323 5.1.2.1.2 */
-      int reordering_window;
-
-      if (pdcp_p->seq_num_size == 7)
-        reordering_window = REORDERING_WINDOW_SN_7BIT;
-      else
-        reordering_window = REORDERING_WINDOW_SN_12BIT;
-
-      if (sequence_number - pdcp_p->last_submitted_pdcp_rx_sn > reordering_window ||
-          (pdcp_p->last_submitted_pdcp_rx_sn - sequence_number >= 0 &&
-           pdcp_p->last_submitted_pdcp_rx_sn - sequence_number < reordering_window)) {
-        /* TODO: specs say to decipher and do header decompression */
-        LOG_W(PDCP,
-              PROTOCOL_PDCP_CTXT_FMT"discard PDU, out of\n",
-              PROTOCOL_PDCP_CTXT_ARGS(ctxt_pP, pdcp_p));
-        LOG_W(PDCP, "Ignoring PDU...\n");
-        free_mem_block(sdu_buffer_pP, __func__);
-        /* TODO: indicate integrity verification failure to upper layer */
-        return FALSE;
-
-      } else if (pdcp_p->next_pdcp_rx_sn - sequence_number > reordering_window) {
-        pdcp_p->rx_hfn++;
-        rx_hfn_for_count  = pdcp_p->rx_hfn;
-        pdcp_sn_for_count = sequence_number;
-        pdcp_p->next_pdcp_rx_sn = sequence_number + 1;
+      case RLC_MODE_AM: {
+        /* process as described in 36.323 5.1.2.1.2 */
+        int reordering_window;
 
-      } else if (sequence_number - pdcp_p->next_pdcp_rx_sn >= reordering_window) {
-        rx_hfn_for_count  = pdcp_p->rx_hfn - 1;
-        pdcp_sn_for_count = sequence_number;
-
-      } else if (sequence_number >= pdcp_p->next_pdcp_rx_sn) {
-        rx_hfn_for_count  = pdcp_p->rx_hfn;
-        pdcp_sn_for_count = sequence_number;
-        pdcp_p->next_pdcp_rx_sn = sequence_number + 1;
-        if (pdcp_p->next_pdcp_rx_sn > pdcp_p->maximum_pdcp_rx_sn) {
-          pdcp_p->next_pdcp_rx_sn = 0;
+        if (pdcp_p->seq_num_size == 7)
+          reordering_window = REORDERING_WINDOW_SN_7BIT;
+        else
+          reordering_window = REORDERING_WINDOW_SN_12BIT;
+
+        if (sequence_number - pdcp_p->last_submitted_pdcp_rx_sn > reordering_window ||
+            (pdcp_p->last_submitted_pdcp_rx_sn - sequence_number >= 0 &&
+             pdcp_p->last_submitted_pdcp_rx_sn - sequence_number < reordering_window)) {
+          /* TODO: specs say to decipher and do header decompression */
+          LOG_W(PDCP,
+                PROTOCOL_PDCP_CTXT_FMT"discard PDU, out of\n",
+                PROTOCOL_PDCP_CTXT_ARGS(ctxt_pP, pdcp_p));
+          LOG_W(PDCP, "Ignoring PDU...\n");
+          free_mem_block(sdu_buffer_pP, __func__);
+          /* TODO: indicate integrity verification failure to upper layer */
+          return FALSE;
+        } else if (pdcp_p->next_pdcp_rx_sn - sequence_number > reordering_window) {
           pdcp_p->rx_hfn++;
+          rx_hfn_for_count  = pdcp_p->rx_hfn;
+          pdcp_sn_for_count = sequence_number;
+          pdcp_p->next_pdcp_rx_sn = sequence_number + 1;
+        } else if (sequence_number - pdcp_p->next_pdcp_rx_sn >= reordering_window) {
+          rx_hfn_for_count  = pdcp_p->rx_hfn - 1;
+          pdcp_sn_for_count = sequence_number;
+        } else if (sequence_number >= pdcp_p->next_pdcp_rx_sn) {
+          rx_hfn_for_count  = pdcp_p->rx_hfn;
+          pdcp_sn_for_count = sequence_number;
+          pdcp_p->next_pdcp_rx_sn = sequence_number + 1;
+
+          if (pdcp_p->next_pdcp_rx_sn > pdcp_p->maximum_pdcp_rx_sn) {
+            pdcp_p->next_pdcp_rx_sn = 0;
+            pdcp_p->rx_hfn++;
+          }
+        } else { /* sequence_number < pdcp_p->next_pdcp_rx_sn */
+          rx_hfn_for_count  = pdcp_p->rx_hfn;
+          pdcp_sn_for_count = sequence_number;
         }
 
-      } else { /* sequence_number < pdcp_p->next_pdcp_rx_sn */
-        rx_hfn_for_count  = pdcp_p->rx_hfn;
-        pdcp_sn_for_count = sequence_number;
-      }
-
-      if (pdcp_p->security_activated == 1) {
-        if (ctxt_pP->enb_flag == ENB_FLAG_NO) {
-          start_meas(&eNB_pdcp_stats[ctxt_pP->module_id].validate_security);
-        } else {
-          start_meas(&UE_pdcp_stats[ctxt_pP->module_id].validate_security);
-        }
+        if (pdcp_p->security_activated == 1) {
+          if (ctxt_pP->enb_flag == ENB_FLAG_NO) {
+            start_meas(&eNB_pdcp_stats[ctxt_pP->module_id].validate_security);
+          } else {
+            start_meas(&UE_pdcp_stats[ctxt_pP->module_id].validate_security);
+          }
 
-        security_ok = pdcp_validate_security(ctxt_pP,
-                                             pdcp_p,
-                                             srb_flagP,
-                                             rb_idP,
-                                             pdcp_header_len,
-                                             rx_hfn_for_count,
-                                             pdcp_sn_for_count,
-                                             sdu_buffer_pP->data,
-                                             sdu_buffer_sizeP - pdcp_tailer_len) == 0;
+          security_ok = pdcp_validate_security(ctxt_pP,
+                                               pdcp_p,
+                                               srb_flagP,
+                                               rb_idP,
+                                               pdcp_header_len,
+                                               rx_hfn_for_count,
+                                               pdcp_sn_for_count,
+                                               sdu_buffer_pP->data,
+                                               sdu_buffer_sizeP - pdcp_tailer_len) == 0;
 
-        if (ctxt_pP->enb_flag == ENB_FLAG_NO) {
-          stop_meas(&eNB_pdcp_stats[ctxt_pP->module_id].validate_security);
+          if (ctxt_pP->enb_flag == ENB_FLAG_NO) {
+            stop_meas(&eNB_pdcp_stats[ctxt_pP->module_id].validate_security);
+          } else {
+            stop_meas(&UE_pdcp_stats[ctxt_pP->module_id].validate_security);
+          }
         } else {
-          stop_meas(&UE_pdcp_stats[ctxt_pP->module_id].validate_security);
+          security_ok = 1;
         }
-      } else {
-        security_ok = 1;
-      }
 
-      if (security_ok == 0) {
-        LOG_W(PDCP,
-              PROTOCOL_PDCP_CTXT_FMT"security not validated for incoming PDPC DRB RLC/AM PDU\n",
-              PROTOCOL_PDCP_CTXT_ARGS(ctxt_pP, pdcp_p));
-        LOG_W(PDCP, "Ignoring PDU...\n");
-        free_mem_block(sdu_buffer_pP, __func__);
-        /* TODO: indicate integrity verification failure to upper layer */
-        return FALSE;
-      }
+        if (security_ok == 0) {
+          LOG_W(PDCP,
+                PROTOCOL_PDCP_CTXT_FMT"security not validated for incoming PDPC DRB RLC/AM PDU\n",
+                PROTOCOL_PDCP_CTXT_ARGS(ctxt_pP, pdcp_p));
+          LOG_W(PDCP, "Ignoring PDU...\n");
+          free_mem_block(sdu_buffer_pP, __func__);
+          /* TODO: indicate integrity verification failure to upper layer */
+          return FALSE;
+        }
 
-      /* TODO: specs say we have to store this PDU in a list and then deliver
-       *       stored packets to upper layers according to a well defined
-       *       procedure. The code below that deals with delivery is today
-       *       too complex to do this properly, so we only send the current
-       *       received packet. This is not correct and has to be fixed
-       *       some day.
-       *       In the meantime, let's pretend the last submitted PDCP SDU
-       *       is the current one.
-       * TODO: we also have to deal with re-establishment PDU (control PDUs)
-       *       that contain no SDU.
-       */
+        /* TODO: specs say we have to store this PDU in a list and then deliver
+         *       stored packets to upper layers according to a well defined
+         *       procedure. The code below that deals with delivery is today
+         *       too complex to do this properly, so we only send the current
+         *       received packet. This is not correct and has to be fixed
+         *       some day.
+         *       In the meantime, let's pretend the last submitted PDCP SDU
+         *       is the current one.
+         * TODO: we also have to deal with re-establishment PDU (control PDUs)
+         *       that contain no SDU.
+         */
+        pdcp_p->last_submitted_pdcp_rx_sn = sequence_number;
+        break;
+        } /* case RLC_MODE_AM */
 
-      pdcp_p->last_submitted_pdcp_rx_sn = sequence_number;
+      case RLC_MODE_UM:
 
-      break;
-    } /* case RLC_MODE_AM */
+        /* process as described in 36.323 5.1.2.1.3 */
+        if (sequence_number < pdcp_p->next_pdcp_rx_sn) {
+          pdcp_p->rx_hfn++;
+        }
 
-    case RLC_MODE_UM:
-      /* process as described in 36.323 5.1.2.1.3 */
-      if (sequence_number < pdcp_p->next_pdcp_rx_sn) {
-        pdcp_p->rx_hfn++;
-      }
-      rx_hfn_for_count  = pdcp_p->rx_hfn;
-      pdcp_sn_for_count = sequence_number;
-      pdcp_p->next_pdcp_rx_sn = sequence_number + 1;
-      if (pdcp_p->next_pdcp_rx_sn > pdcp_p->maximum_pdcp_rx_sn) {
-        pdcp_p->next_pdcp_rx_sn = 0;
-        pdcp_p->rx_hfn++;
-      }
+        rx_hfn_for_count  = pdcp_p->rx_hfn;
+        pdcp_sn_for_count = sequence_number;
+        pdcp_p->next_pdcp_rx_sn = sequence_number + 1;
 
-      if (pdcp_p->security_activated == 1) {
-        if (ctxt_pP->enb_flag == ENB_FLAG_NO) {
-          start_meas(&eNB_pdcp_stats[ctxt_pP->module_id].validate_security);
-        } else {
-          start_meas(&UE_pdcp_stats[ctxt_pP->module_id].validate_security);
+        if (pdcp_p->next_pdcp_rx_sn > pdcp_p->maximum_pdcp_rx_sn) {
+          pdcp_p->next_pdcp_rx_sn = 0;
+          pdcp_p->rx_hfn++;
         }
 
-        security_ok = pdcp_validate_security(ctxt_pP,
-                                             pdcp_p,
-                                             srb_flagP,
-                                             rb_idP,
-                                             pdcp_header_len,
-                                             rx_hfn_for_count,
-                                             pdcp_sn_for_count,
-                                             sdu_buffer_pP->data,
-                                             sdu_buffer_sizeP - pdcp_tailer_len) == 0;
+        if (pdcp_p->security_activated == 1) {
+          if (ctxt_pP->enb_flag == ENB_FLAG_NO) {
+            start_meas(&eNB_pdcp_stats[ctxt_pP->module_id].validate_security);
+          } else {
+            start_meas(&UE_pdcp_stats[ctxt_pP->module_id].validate_security);
+          }
 
-        if (ctxt_pP->enb_flag == ENB_FLAG_NO) {
-          stop_meas(&eNB_pdcp_stats[ctxt_pP->module_id].validate_security);
+          security_ok = pdcp_validate_security(ctxt_pP,
+                                               pdcp_p,
+                                               srb_flagP,
+                                               rb_idP,
+                                               pdcp_header_len,
+                                               rx_hfn_for_count,
+                                               pdcp_sn_for_count,
+                                               sdu_buffer_pP->data,
+                                               sdu_buffer_sizeP - pdcp_tailer_len) == 0;
+
+          if (ctxt_pP->enb_flag == ENB_FLAG_NO) {
+            stop_meas(&eNB_pdcp_stats[ctxt_pP->module_id].validate_security);
+          } else {
+            stop_meas(&UE_pdcp_stats[ctxt_pP->module_id].validate_security);
+          }
         } else {
-          stop_meas(&UE_pdcp_stats[ctxt_pP->module_id].validate_security);
+          security_ok = 1;
         }
-      } else {
-        security_ok = 1;
-      }
 
-      if (security_ok == 0) {
-        LOG_W(PDCP,
-              PROTOCOL_PDCP_CTXT_FMT"security not validated for incoming PDPC DRB RLC/UM PDU\n",
-              PROTOCOL_PDCP_CTXT_ARGS(ctxt_pP, pdcp_p));
-        LOG_W(PDCP, "Ignoring PDU...\n");
-        free_mem_block(sdu_buffer_pP, __func__);
-        /* TODO: indicate integrity verification failure to upper layer */
-        return FALSE;
-      }
+        if (security_ok == 0) {
+          LOG_W(PDCP,
+                PROTOCOL_PDCP_CTXT_FMT"security not validated for incoming PDPC DRB RLC/UM PDU\n",
+                PROTOCOL_PDCP_CTXT_ARGS(ctxt_pP, pdcp_p));
+          LOG_W(PDCP, "Ignoring PDU...\n");
+          free_mem_block(sdu_buffer_pP, __func__);
+          /* TODO: indicate integrity verification failure to upper layer */
+          return FALSE;
+        }
 
-      break;
+        break;
 
-    default:
-      LOG_E(PDCP, "bad RLC mode, cannot happen.\n");
-      exit(1);
+      default:
+        LOG_E(PDCP, "bad RLC mode, cannot happen.\n");
+        exit(1);
     } /* switch (pdcp_p->rlc_mode) */
   } else { /* MBMS_flagP == 0 */
     payload_offset=0;
@@ -1145,7 +1144,8 @@ pdcp_run (
   } while(msg_p != NULL);
 
   // IP/NAS -> PDCP traffic : TX, read the pkt from the upper layer buffer
-  if (LINK_ENB_PDCP_TO_GTPV1U && ctxt_pP->enb_flag == ENB_FLAG_NO) {
+  //  if (LINK_ENB_PDCP_TO_GTPV1U && ctxt_pP->enb_flag == ENB_FLAG_NO) {
+  if (!EPC_MODE_ENABLED || ctxt_pP->enb_flag == ENB_FLAG_NO ) {
     pdcp_fifo_read_input_sdus(ctxt_pP);
   }
 
@@ -2027,9 +2027,6 @@ rrc_pdcp_config_req (
   }
 }
 
-
-//-----------------------------------------------------------------------------
-
 uint64_t pdcp_module_init( uint64_t pdcp_optmask ) {
   /* temporary enforce netlink when UE_NAS_USE_TUN is set,
      this is while switching from noS1 as build option
@@ -2044,9 +2041,17 @@ uint64_t pdcp_module_init( uint64_t pdcp_optmask ) {
         ((PDCP_USE_NETLINK)?"usenetlink":""));
 
   if (PDCP_USE_NETLINK) {
+    nas_getparams();
+
     if(UE_NAS_USE_TUN) {
-      netlink_init_tun();
+      netlink_init_tun("ue");
+      LOG_I(PDCP, "UE pdcp will use tun interface\n");
+    } else if(ENB_NAS_USE_TUN) {
+      netlink_init_tun("enb");
+      nas_config(1, 1, 1, "enb");
+      LOG_I(PDCP, "ENB pdcp will use tun interface\n");
     } else {
+      LOG_I(PDCP, "pdcp will use kernel modules\n");
       netlink_init();
     }
   }
@@ -2054,6 +2059,7 @@ uint64_t pdcp_module_init( uint64_t pdcp_optmask ) {
   return pdcp_params.optmask ;
 }
 
+
 //-----------------------------------------------------------------------------
 void
 pdcp_free (
diff --git a/openair2/LAYER2/PDCP_v10.1.0/pdcp.h b/openair2/LAYER2/PDCP_v10.1.0/pdcp.h
index 8f30608cd8a8504a21953606834aaa0279227f1a..cf8d1a1fd617c4b62ef37d82e9700b66d8a8dcf3 100644
--- a/openair2/LAYER2/PDCP_v10.1.0/pdcp.h
+++ b/openair2/LAYER2/PDCP_v10.1.0/pdcp.h
@@ -55,6 +55,7 @@
 #define LINK_ENB_PDCP_TO_IP_DRIVER_BIT  (1<< 13)
 #define LINK_ENB_PDCP_TO_GTPV1U_BIT     (1<< 14)
 #define UE_NAS_USE_TUN_BIT              (1<< 15)
+#define ENB_NAS_USE_TUN_BIT             (1<< 16)
 typedef struct {
   uint64_t optmask;
 } pdcp_params_t;
@@ -63,6 +64,7 @@ typedef struct {
 #define LINK_ENB_PDCP_TO_IP_DRIVER  ( get_pdcp_optmask() & LINK_ENB_PDCP_TO_IP_DRIVER_BIT)
 #define LINK_ENB_PDCP_TO_GTPV1U     ( get_pdcp_optmask() & LINK_ENB_PDCP_TO_GTPV1U_BIT)
 #define UE_NAS_USE_TUN              ( get_pdcp_optmask() & UE_NAS_USE_TUN_BIT)
+#define ENB_NAS_USE_TUN             ( get_pdcp_optmask() & ENB_NAS_USE_TUN_BIT)
 uint64_t get_pdcp_optmask(void);
 
 extern pthread_t       pdcp_thread;
diff --git a/openair2/LAYER2/PDCP_v10.1.0/pdcp_fifo.c b/openair2/LAYER2/PDCP_v10.1.0/pdcp_fifo.c
index a55cf906a0f94593ab9e9a55c2d8b02b4c8729ec..4ac866cd6658ed1b8766ccea6451a211b78fa4e3 100644
--- a/openair2/LAYER2/PDCP_v10.1.0/pdcp_fifo.c
+++ b/openair2/LAYER2/PDCP_v10.1.0/pdcp_fifo.c
@@ -125,7 +125,9 @@ int pdcp_fifo_flush_sdus(const protocol_ctxt_t *const  ctxt_pP) {
                    sizeof(sidelink_pc5s_element), 0, (struct sockaddr *)&prose_pdcp_addr,sizeof(prose_pdcp_addr) );
     } else if (UE_NAS_USE_TUN) {
       ret = write(nas_sock_fd[ctxt_pP->module_id], &(sdu_p->data[sizeof(pdcp_data_ind_header_t)]),sizeToWrite );
-    } else if (PDCP_USE_NETLINK) {//UE_NAS_USE_TUN
+    } else if (ENB_NAS_USE_TUN) {
+      ret = write(nas_sock_fd[0], &(sdu_p->data[sizeof(pdcp_data_ind_header_t)]),sizeToWrite );
+    } else if (PDCP_USE_NETLINK) {
       memcpy(NLMSG_DATA(nas_nlh_tx), (uint8_t *) sdu_p->data,  sizeToWrite);
       nas_nlh_tx->nlmsg_len = sizeToWrite;
       ret = sendmsg(nas_sock_fd[0],&nas_msg_tx,0);
@@ -144,7 +146,7 @@ int pdcp_fifo_flush_sdus(const protocol_ctxt_t *const  ctxt_pP) {
 int pdcp_fifo_read_input_sdus (const protocol_ctxt_t *const  ctxt_pP) {
   pdcp_data_req_header_t pdcp_read_header_g;
 
-  if (UE_NAS_USE_TUN) {
+  if (UE_NAS_USE_TUN || ENB_NAS_USE_TUN) {
     protocol_ctxt_t ctxt = *ctxt_pP;
     hash_key_t key = HASHTABLE_NOT_A_KEY_VALUE;
     hashtable_rc_t h_rc;
@@ -155,20 +157,29 @@ int pdcp_fifo_read_input_sdus (const protocol_ctxt_t *const  ctxt_pP) {
     do {
       VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME( VCD_SIGNAL_DUMPER_FUNCTIONS_PDCP_FIFO_READ, 1 );
       VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME( VCD_SIGNAL_DUMPER_FUNCTIONS_PDCP_FIFO_READ_BUFFER, 1 );
-      len = read(nas_sock_fd[ctxt_pP->module_id], &nl_rx_buf, NL_MAX_PAYLOAD);
+      len = read(UE_NAS_USE_TUN?nas_sock_fd[ctxt_pP->module_id]:nas_sock_fd[0], &nl_rx_buf, NL_MAX_PAYLOAD);
       VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME( VCD_SIGNAL_DUMPER_FUNCTIONS_PDCP_FIFO_READ_BUFFER, 0 );
 
       if (len<=0) continue;
 
+      if (UE_NAS_USE_TUN) {
+        key = PDCP_COLL_KEY_DEFAULT_DRB_VALUE(ctxt.module_id, ctxt.rnti, ctxt.enb_flag);
+        h_rc = hashtable_get(pdcp_coll_p, key, (void **)&pdcp_p);
+      } else {
+        ctxt.rnti=pdcp_eNB_UE_instance_to_rnti[0];
+        ctxt.enb_flag=ENB_FLAG_YES;
+        ctxt.module_id=0;
+        key = PDCP_COLL_KEY_VALUE(ctxt.module_id, ctxt.rnti, ctxt.enb_flag, rab_id, SRB_FLAG_YES);
+        h_rc = hashtable_get(pdcp_coll_p, key, (void **)&pdcp_p);
+      }
+
       LOG_D(PDCP, "PDCP_COLL_KEY_DEFAULT_DRB_VALUE(module_id=%d, rnti=%x, enb_flag=%d)\n",
             ctxt.module_id, ctxt.rnti, ctxt.enb_flag);
-      key = PDCP_COLL_KEY_DEFAULT_DRB_VALUE(ctxt.module_id, ctxt.rnti, ctxt.enb_flag);
-      h_rc = hashtable_get(pdcp_coll_p, key, (void **)&pdcp_p);
 
       if (h_rc == HASH_TABLE_OK) {
         LOG_D(PDCP, "[FRAME %5u][UE][NETLINK][IP->PDCP] INST %d: Received socket with length %d on Rab %d \n",
               ctxt.frame, ctxt.instance, len, rab_id);
-        LOG_D(PDCP, "[FRAME %5u][UE][IP][INSTANCE %u][RB %u][--- PDCP_DATA_REQ / %d Bytes --->][PDCP][MOD %u][UE %u][RB %u]\n",
+        LOG_D(PDCP, "[FRAME %5u][UE][IP][INSTANCE %u][RB %u][--- PDCP_DATA_REQ / %d Bytes --->][PDCP][MOD %u][UE %04x][RB %u]\n",
               ctxt.frame, ctxt.instance, rab_id, len, ctxt.module_id,
               ctxt.rnti, rab_id);
         MSC_LOG_RX_MESSAGE((ctxt_pP->enb_flag == ENB_FLAG_YES) ? MSC_PDCP_ENB:MSC_PDCP_UE,
@@ -192,7 +203,7 @@ int pdcp_fifo_read_input_sdus (const protocol_ctxt_t *const  ctxt_pP) {
           MSC_AS_TIME_ARGS(ctxt_pP),
           ctxt.instance, rab_id, rab_id, len);
         LOG_D(PDCP,
-              "[FRAME %5u][UE][IP][INSTANCE %u][RB %u][--- PDCP_DATA_REQ / %d Bytes ---X][PDCP][MOD %u][UE %u][RB %u] NON INSTANCIATED INSTANCE key 0x%"PRIx64", DROPPED\n",
+              "[FRAME %5u][UE][IP][INSTANCE %u][RB %u][--- PDCP_DATA_REQ / %d Bytes ---X][PDCP][MOD %u][UE %04x][RB %u] NON INSTANCIATED INSTANCE key 0x%"PRIx64", DROPPED\n",
               ctxt.frame, ctxt.instance, rab_id, len, ctxt.module_id,
               ctxt.rnti, rab_id, key);
       }
diff --git a/openair2/LAYER2/RLC/rlc.c b/openair2/LAYER2/RLC/rlc.c
index 309facf34bba27d22f14c742ece2a8cf5ea9373b..38d78f18fd86acc12d49a912518ecfa16810bf3d 100644
--- a/openair2/LAYER2/RLC/rlc.c
+++ b/openair2/LAYER2/RLC/rlc.c
@@ -584,14 +584,12 @@ void rlc_data_ind     (
   const sdu_size_t  sdu_sizeP,
   mem_block_t      *sdu_pP) {
   //-----------------------------------------------------------------------------
-#if defined(TRACE_RLC_PAYLOAD)
   LOG_D(RLC, PROTOCOL_CTXT_FMT"[%s %u] Display of rlc_data_ind: size %u\n",
         PROTOCOL_CTXT_ARGS(ctxt_pP),
         (srb_flagP) ? "SRB" : "DRB",
         rb_idP,
         sdu_sizeP);
   rlc_util_print_hex_octets(RLC, (unsigned char *)sdu_pP->data, sdu_sizeP);
-#endif
 #if T_TRACER
 
   if (ctxt_pP->enb_flag)
diff --git a/openair2/NETWORK_DRIVER/MESH/constant.h b/openair2/NETWORK_DRIVER/MESH/constant.h
index 1c756765c6c1a0e86201332f5ef77bc8cca6333e..5347c5a78499f968d6d576689c3776b51fd28976 100644
--- a/openair2/NETWORK_DRIVER/MESH/constant.h
+++ b/openair2/NETWORK_DRIVER/MESH/constant.h
@@ -47,7 +47,8 @@
 #define NAS_INET6_ADDRSTRLEN 46
 #define NAS_INET_ADDRSTRLEN 16
 
-#define NAS_CX_MAX 128 // 32  //Identical to RRC constant
+#define NAS_CX_MAX 32 //128   //Identical to RRC constant: no you cannot
+/* increase to 128  without risking stack problems: KEEP ATTENTION TO COMPILATION WARNINGS */
 //#define NAS_CX_MULTICAST_ALLNODE 2
 
 #define NAS_RETRY_LIMIT_DEFAULT 5
diff --git a/openair2/NETWORK_DRIVER/MESH/ioctl.h b/openair2/NETWORK_DRIVER/MESH/ioctl.h
index ffa9b4e79b7ed4c02a091fc117b2c2243e612796..904105b1d1c1d680d5b4ced361952233d349c919 100644
--- a/openair2/NETWORK_DRIVER/MESH/ioctl.h
+++ b/openair2/NETWORK_DRIVER/MESH/ioctl.h
@@ -64,7 +64,8 @@
 // Max number of entry of a message list
 #define NAS_LIST_CX_MAX 32
 #define NAS_LIST_RB_MAX 32
-#define NAS_LIST_CLASS_MAX  32
+#define NAS_LIST_CLASS_MAX 16 // 32 is too high!!:
+/* risk of  stack problems: KEEP ATTENTION TO COMPILATION WARNINGS */
 
 typedef unsigned short nasMsgType_t;
 
diff --git a/openair2/RRC/LTE/rrc_UE.c b/openair2/RRC/LTE/rrc_UE.c
index cddd409922bf7676c325083593bb626a49f1f5c4..a00bc5375928859fc566afda17f261142729bb47 100644
--- a/openair2/RRC/LTE/rrc_UE.c
+++ b/openair2/RRC/LTE/rrc_UE.c
@@ -801,7 +801,6 @@ rrc_ue_establish_drb(
   (void)ip_addr_offset4;
   LOG_I(RRC,"[UE %d] Frame %d: processing RRCConnectionReconfiguration: reconfiguring DRB %ld/LCID %d\n",
         ue_mod_idP, frameP, DRB_config->drb_Identity, (int)*DRB_config->logicalChannelIdentity);
-
   /*
   rrc_pdcp_config_req (ue_mod_idP+NB_eNB_INST, frameP, 0, CONFIG_ACTION_ADD,
                              (eNB_index * NB_RB_MAX) + *DRB_config->logicalChannelIdentity, UNDEF_SECURITY_MODE);
@@ -810,34 +809,34 @@ rrc_ue_establish_drb(
                     (eNB_index * NB_RB_MAX) + *DRB_config->logicalChannelIdentity,
                     RADIO_ACCESS_BEARER,Rlc_info_um);
    */
-  if(PDCP_USE_NETLINK) {
-#   if !defined(OAI_NW_DRIVER_TYPE_ETHERNET) && !defined(EXMIMO) && !defined(OAI_USRP) && !defined(OAI_BLADERF) && !defined(ETHERNET) && !defined(LINK_ENB_PDCP_TO_GTPV1U)
-    ip_addr_offset3 = 0;
-    ip_addr_offset4 = 1;
-    LOG_I(OIP,"[UE %d] trying to bring up the OAI interface oai%d, IP 10.0.%d.%d\n", ue_mod_idP, ip_addr_offset3+ue_mod_idP,
-          ip_addr_offset3+ue_mod_idP+1,ip_addr_offset4+ue_mod_idP+1);
-    oip_ifup=nas_config(ip_addr_offset3+ue_mod_idP,   // interface_id
-                        ip_addr_offset3+ue_mod_idP+1, // third_octet
-                        ip_addr_offset4+ue_mod_idP+1); // fourth_octet
-
-    if (oip_ifup == 0 ) { // interface is up --> send a config the DRB
-      LOG_I(OIP,"[UE %d] Config the oai%d to send/receive pkt on DRB %ld to/from the protocol stack\n",
-            ue_mod_idP,
-            ip_addr_offset3+ue_mod_idP,
-            (long int)((eNB_index * maxDRB) + DRB_config->drb_Identity));
-      rb_conf_ipv4(0,//add
-                   ue_mod_idP,//cx align with the UE index
-                   ip_addr_offset3+ue_mod_idP,//inst num_enb+ue_index
-                   (eNB_index * maxDRB) + DRB_config->drb_Identity,//rb
-                   0,//dscp
-                   ipv4_address(ip_addr_offset3+ue_mod_idP+1,ip_addr_offset4+ue_mod_idP+1),//saddr
-                   ipv4_address(ip_addr_offset3+ue_mod_idP+1,eNB_index+1));//daddr
-      LOG_D(RRC,"[UE %d] State = Attached (eNB %d)\n",ue_mod_idP,eNB_index);
-    }
-
-#    endif
+  //  if(!EPC_MODE_ENABLED) {
+  //#   if !defined(OAI_NW_DRIVER_TYPE_ETHERNET) && !defined(EXMIMO) && !defined(OAI_USRP) && !defined(OAI_BLADERF) && !defined(ETHERNET) && !defined(LINK_ENB_PDCP_TO_GTPV1U)
+  ip_addr_offset3 = 0;
+  ip_addr_offset4 = 1;
+  LOG_I(OIP,"[UE %d] trying to bring up the OAI interface oip%d, IP 10.0.%d.%d\n", ue_mod_idP, ip_addr_offset3+ue_mod_idP,
+        ip_addr_offset3+ue_mod_idP+1,ip_addr_offset4+ue_mod_idP+1);
+  oip_ifup=nas_config(ip_addr_offset3+ue_mod_idP+1,   // interface_id
+                      ip_addr_offset3+ue_mod_idP+1, // third_octet
+                      ip_addr_offset4+ue_mod_idP+1, // fourth_octet
+                      "oip");                        // interface suffix
+
+  if (oip_ifup == 0 && (!UE_NAS_USE_TUN)) { // interface is up --> send a config the DRB
+    LOG_I(OIP,"[UE %d] Config the ue net interface %d to send/receive pkt on DRB %ld to/from the protocol stack\n",
+          ue_mod_idP,
+          ip_addr_offset3+ue_mod_idP,
+          (long int)((eNB_index * LTE_maxDRB) + DRB_config->drb_Identity));
+    rb_conf_ipv4(0,//add
+                 ue_mod_idP,//cx align with the UE index
+                 ip_addr_offset3+ue_mod_idP,//inst num_enb+ue_index
+                 (eNB_index * LTE_maxDRB) + DRB_config->drb_Identity,//rb
+                 0,//dscp
+                 ipv4_address(ip_addr_offset3+ue_mod_idP+1,ip_addr_offset4+ue_mod_idP+1),//saddr
+                 ipv4_address(ip_addr_offset3+ue_mod_idP+1,eNB_index+1));//daddr
+    LOG_D(RRC,"[UE %d] State = Attached (eNB %d)\n",ue_mod_idP,eNB_index);
   }
 
+  //#    endif
+  //  }
   return(0);
 }
 
@@ -1930,7 +1929,7 @@ rrc_ue_process_rrcConnectionReconfiguration(
 
           for (i=0; (
                  i<rrcConnectionReconfiguration->criticalExtensions.choice.c1.choice.rrcConnectionReconfiguration_r8.radioResourceConfigDedicated->drb_ToAddModList->list.count)
-               && (i < maxDRB); i++) {
+               && (i < LTE_maxDRB); i++) {
             // why minus 1 in RRC code for drb_identity ?
             connection_reestablishment_ind.drb_id[i]   =
               rrcConnectionReconfiguration->criticalExtensions.choice.c1.choice.rrcConnectionReconfiguration_r8.radioResourceConfigDedicated->drb_ToAddModList->list.array[i]->drb_Identity;
@@ -2241,7 +2240,7 @@ rrc_ue_decode_dcch(
 
                 for (i=0; (
                        i<dl_dcch_msg->message.choice.c1.choice.rrcConnectionReconfiguration.criticalExtensions.choice.c1.choice.rrcConnectionReconfiguration_r8.radioResourceConfigDedicated->drb_ToAddModList->list.count)
-                     && (i < maxDRB); i++) {
+                     && (i < LTE_maxDRB); i++) {
                   // why minus 1 in RRC code for drb_identity ?
                   connection_reconfiguration_ho_ind.drb_id[i]   =
                     dl_dcch_msg->message.choice.c1.choice.rrcConnectionReconfiguration.criticalExtensions.choice.c1.choice.rrcConnectionReconfiguration_r8.radioResourceConfigDedicated->drb_ToAddModList->list.array[i]->drb_Identity;
@@ -2295,7 +2294,7 @@ rrc_ue_decode_dcch(
 
                 for (i=0; (
                        i<dl_dcch_msg->message.choice.c1.choice.rrcConnectionReconfiguration.criticalExtensions.choice.c1.choice.rrcConnectionReconfiguration_r8.radioResourceConfigDedicated->drb_ToAddModList->list.count)
-                     && (i < maxDRB); i++) {
+                     && (i < LTE_maxDRB); i++) {
                   // why minus 1 in RRC code for drb_identity ?
                   connection_reconfiguration_ind.drb_id[i]   =
                     dl_dcch_msg->message.choice.c1.choice.rrcConnectionReconfiguration.criticalExtensions.choice.c1.choice.rrcConnectionReconfiguration_r8.radioResourceConfigDedicated->drb_ToAddModList->list.array[i]->drb_Identity;
diff --git a/openair2/RRC/LTE/rrc_eNB.c b/openair2/RRC/LTE/rrc_eNB.c
index 95048d763ea079ab28fd02129d8d697c4e8d28a6..c69888b0c1868ee749ba6fc57107c1a89d8525f3 100644
--- a/openair2/RRC/LTE/rrc_eNB.c
+++ b/openair2/RRC/LTE/rrc_eNB.c
@@ -6027,9 +6027,6 @@ rrc_eNB_process_RRCConnectionReconfigurationComplete(
   int                                 i, drb_id;
   int                                 oip_ifup = 0;
   int                                 dest_ip_offset = 0;
-  /* avoid gcc warnings */
-  (void)oip_ifup;
-  (void)dest_ip_offset;
   uint8_t                            *kRRCenc = NULL;
   uint8_t                            *kRRCint = NULL;
   uint8_t                            *kUPenc = NULL;
@@ -6150,16 +6147,15 @@ rrc_eNB_process_RRCConnectionReconfigurationComplete(
                 "[eNB %d] Frame %d: Establish RLC UM Bidirectional, DRB %d Active\n",
                 ctxt_pP->module_id, ctxt_pP->frame, (int)DRB_configList->list.array[i]->drb_Identity);
 
-          if (PDCP_USE_NETLINK && (!LINK_ENB_PDCP_TO_GTPV1U)) {
-            // can mean also IPV6 since ether -> ipv6 autoconf
-#   if !defined(OAI_NW_DRIVER_TYPE_ETHERNET) && !defined(EXMIMO) && !defined(OAI_USRP) && !defined(OAI_BLADERF) && !defined(ETHERNET)
+          if (!EPC_MODE_ENABLED && !ENB_NAS_USE_TUN) {
             LOG_I(OIP, "[eNB %d] trying to bring up the OAI interface oai%d\n",
                   ctxt_pP->module_id,
                   ctxt_pP->module_id);
             oip_ifup = nas_config(
                          ctxt_pP->module_id,   // interface index
-                         ctxtReportConfigToAddMod__reportConfig_PR_reportConfigEUTRA_pP->module_id + 1,   // thrid octet
-                         ctxt_pP->module_id + 1);  // fourth octet
+                         ctxt_pP->module_id + 1,   // thrid octet
+                         ctxt_pP->module_id + 1,   // fourth octet
+                         "oai");
 
             if (oip_ifup == 0) {    // interface is up --> send a config the DRB
               module_id_t ue_module_id;
@@ -6167,21 +6163,19 @@ rrc_eNB_process_RRCConnectionReconfigurationComplete(
               LOG_I(OIP,
                     "[eNB %d] Config the oai%d to send/receive pkt on DRB %ld to/from the protocol stack\n",
                     ctxt_pP->module_id, ctxt_pP->module_id,
-                    (long int)((ue_context_pP->local_uid * maxDRB) + DRB_configList->list.array[i]->drb_Identity));
+                    (long int)((ue_context_pP->local_uid * LTE_maxDRB) + DRB_configList->list.array[i]->drb_Identity));
               ue_module_id = oai_emulation.info.eNB_ue_local_uid_to_ue_module_id[ctxt_pP->module_id][ue_context_pP->local_uid];
               rb_conf_ipv4(0, //add
                            ue_module_id,  //cx
                            ctxt_pP->module_id,    //inst
-                           (ue_module_id * maxDRB) + DRB_configList->list.array[i]->drb_Identity, // RB
+                           (ue_module_id * LTE_maxDRB) + DRB_configList->list.array[i]->drb_Identity, // RB
                            0,    //dscp
                            ipv4_address(ctxt_pP->module_id + 1, ctxt_pP->module_id + 1),  //saddr
                            ipv4_address(ctxt_pP->module_id + 1, dest_ip_offset + ue_module_id + 1));  //daddr
               LOG_D(RRC, "[eNB %d] State = Attached (UE rnti %x module id %u)\n",
                     ctxt_pP->module_id, ue_context_pP->ue_context.rnti, ue_module_id);
-            }
-
-#   endif
-          }
+            } /* oip_ifup */
+          } /* !EPC_MODE_ENABLED && ENB_NAS_USE_TUN*/
 
           LOG_D(RRC,
                 PROTOCOL_RRC_CTXT_UE_FMT" RRC_eNB --- MAC_CONFIG_REQ  (DRB) ---> MAC_eNB\n",
diff --git a/openair2/RRC/NAS/nas_config.c b/openair2/RRC/NAS/nas_config.c
index c0f6d622aad6e20d30d63541eb470b968339dd3c..61909df5ec4c744be1684a88347181188aa20eb5 100644
--- a/openair2/RRC/NAS/nas_config.c
+++ b/openair2/RRC/NAS/nas_config.c
@@ -44,48 +44,56 @@
 
 #include "nas_config.h"
 #include "common/utils/LOG/log.h"
-
+#include "targets/RT/USER/lte-softmodem.h"
+#include "common/config/config_userapi.h"
 
 //default values according to the examples,
 
-char *baseNetAddress = "10.0" ;
-char *netMask = "255.255.255.0" ;
-char *broadcastAddr = "10.0.255.255" ;
-
+char *baseNetAddress ;
+char *netMask ;
+char *broadcastAddr ;
+#define NASHLP_NETPREFIX "<NAS network prefix, two first bytes of network addresses>\n"
+#define NASHLP_NETMASK   "<NAS network mask>\n"
+#define NASHLP_BROADCASTADDR   "<NAS network broadcast address>\n"
+void nas_getparams(void) {
+  paramdef_t nasoptions[] = {
+    /*--------------------------------------------------------------------------------------------------------------------------------------------------------------------*/
+    /*                                            configuration parameters for netlink, includes network parameters when running in noS1 mode                             */
+    /*   optname                     helpstr                paramflags           XXXptr                               defXXXval               type                 numelt */
+    /*--------------------------------------------------------------------------------------------------------------------------------------------------------------------*/
+    {"NetworkPrefix",    NASHLP_NETPREFIX,         0,              strptr:&baseNetAddress,        defstrval:"10.0",            TYPE_STRING,  0 },
+    {"NetworkMask",      NASHLP_NETMASK,         0,              strptr:&netMask,               defstrval:"255.255.255.0",   TYPE_STRING,  0 },
+    {"BroadcastAddr",    NASHLP_BROADCASTADDR,         0,              strptr:&broadcastAddr,         defstrval:"10.0.255.255",    TYPE_STRING,  0 },
+  };
+  config_get( nasoptions,sizeof(nasoptions)/sizeof(paramdef_t),"nas.noS1");
+}
 
-void setBaseNetAddress (char* baseAddr)
-{
+void setBaseNetAddress (char *baseAddr) {
   strcpy(baseNetAddress,baseAddr);
 }
 
-char* getBaseNetAddress (void)
-{
+char *getBaseNetAddress (void) {
   return baseNetAddress;
 }
 
-void setNetMask (char* baseAddr)
-{
+void setNetMask (char *baseAddr) {
   strcpy(netMask,baseAddr);
 }
 
-char* getNetMask  (void)
-{
+char *getNetMask  (void) {
   return netMask;
 }
 
-void setBroadcastAddress (char* baseAddr)
-{
+void setBroadcastAddress (char *baseAddr) {
   strcpy(broadcastAddr, baseAddr);
 }
 
-char* getBroadcastAddress (void)
-{
+char *getBroadcastAddress (void) {
   return broadcastAddr;
 }
 
 //Add Gateway to the interface
-int set_gateway(char *interfaceName, char *gateway)
-{
+int set_gateway(char *interfaceName, char *gateway) {
   int sock_fd;
   struct rtentry rt;
   struct sockaddr_in addr;
@@ -96,20 +104,16 @@ int set_gateway(char *interfaceName, char *gateway)
   }
 
   memset (&rt, 0, sizeof (rt));
-
   addr.sin_family = AF_INET;
   /*set Destination addr*/
   inet_aton("0.0.0.0",&addr.sin_addr);
   memcpy(&rt.rt_dst, &addr, sizeof(struct sockaddr_in));
-
   /*set gateway addr*/
   inet_aton(gateway,&addr.sin_addr);
   memcpy(&rt.rt_gateway, &addr, sizeof(struct sockaddr_in));
-
   /*set genmask addr*/
   inet_aton("0.0.0.0",&addr.sin_addr);
   memcpy(&rt.rt_genmask, &addr, sizeof(struct sockaddr_in));
-
   rt.rt_dev = interfaceName;
   //rt.rt_flags = RTF_UP|RTF_GATEWAY|RTF_DEFAULT;
   /* SR: rt_flags on 16 bits but RTF_DEFAULT = 0x00010000
@@ -129,19 +133,16 @@ int set_gateway(char *interfaceName, char *gateway)
       LOG_I(OIP,"set_gateway OK!\n");
       return 0;
     }
-
   }
 
   close(sock_fd);
-
   LOG_D(OIP,"Set Gateway OK!\n");
   return 0;
 }
 
 // sets a genneric interface parameter
 // (SIOCSIFADDR, SIOCSIFNETMASK, SIOCSIFBRDADDR, SIOCSIFFLAGS)
-int setInterfaceParameter(char *interfaceName, char *settingAddress, int operation)
-{
+int setInterfaceParameter(char *interfaceName, char *settingAddress, int operation) {
   int sock_fd;
   struct ifreq ifr;
   struct sockaddr_in addr;
@@ -154,10 +155,8 @@ int setInterfaceParameter(char *interfaceName, char *settingAddress, int operati
 
   memset(&ifr, 0, sizeof(ifr));
   strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name)-1);
-
   memset(&addr, 0, sizeof(struct sockaddr_in));
   addr.sin_family = AF_INET;
-
   inet_aton(settingAddress,&addr.sin_addr);
   memcpy(&ifr.ifr_ifru.ifru_addr,&addr,sizeof(struct sockaddr_in));
 
@@ -169,15 +168,13 @@ int setInterfaceParameter(char *interfaceName, char *settingAddress, int operati
   }
 
   close(sock_fd);
-
   //    printf("Set OK!\n");
   return 0;
 }
 
 // sets a genneric interface parameter
 // (SIOCSIFADDR, SIOCSIFNETMASK, SIOCSIFBRDADDR, SIOCSIFFLAGS)
-int bringInterfaceUp(char *interfaceName, int up)
-{
+int bringInterfaceUp(char *interfaceName, int up) {
   int sock_fd;
   struct ifreq ifr;
 
@@ -213,8 +210,7 @@ int bringInterfaceUp(char *interfaceName, int up)
   return 0;
 }
 // non blocking full configuration of the interface (address, net mask, and broadcast mask)
-int NAS_config(char *interfaceName, char *ipAddress, char *networkMask, char *broadcastAddress)
-{
+int NAS_config(char *interfaceName, char *ipAddress, char *networkMask, char *broadcastAddress) {
   bringInterfaceUp(interfaceName, 0);
   // sets the machine address
   int returnValue= setInterfaceParameter(interfaceName, ipAddress,SIOCSIFADDR);
@@ -229,26 +225,21 @@ int NAS_config(char *interfaceName, char *ipAddress, char *networkMask, char *br
 
   //  if(!returnValue)
   //  returnValue=set_gateway(interfaceName, broadcastAddress);
-
   bringInterfaceUp(interfaceName, 1);
-
   return returnValue;
 }
 
 // non blocking full configuration of the interface (address, and the two lest octets of the address)
-int nas_config(int interface_id, int thirdOctet, int fourthOctet)
-{
+int nas_config(int interface_id, int thirdOctet, int fourthOctet, char *ifname) {
   //char buf[5];
   char ipAddress[20];
   char broadcastAddress[20];
-  char interfaceName[8];
+  char interfaceName[20];
   int returnValue;
   sprintf(ipAddress, "10.0.%d.%d", thirdOctet,fourthOctet);
-
   sprintf(broadcastAddress, "10.0.%d.255", thirdOctet);
-
-  sprintf(interfaceName, "oai%d", interface_id);
-
+  sprintf(interfaceName, "%s%s%d", (UE_NAS_USE_TUN || ENB_NAS_USE_TUN)?"oaitun_":ifname,
+          UE_NAS_USE_TUN?"ue": (ENB_NAS_USE_TUN?"enb":""),interface_id);
   bringInterfaceUp(interfaceName, 0);
   // sets the machine address
   returnValue= setInterfaceParameter(interfaceName, ipAddress,SIOCSIFADDR);
@@ -262,18 +253,13 @@ int nas_config(int interface_id, int thirdOctet, int fourthOctet)
     returnValue= setInterfaceParameter(interfaceName, broadcastAddress,SIOCSIFBRDADDR);
 
   bringInterfaceUp(interfaceName, 1);
-
   return returnValue;
-
 }
 
 // Blocking full configuration of the interface (address, net mask, and broadcast mask)
-int blocking_NAS_config(char *interfaceName, char *ipAddress, char *networkMask, char *broadcastAddress)
-{
-
+int blocking_NAS_config(char *interfaceName, char *ipAddress, char *networkMask, char *broadcastAddress) {
   char command[200];
   command[0]='\0';
-
   strcat(command, "ifconfig ");
   strncat(command, interfaceName, sizeof(command) - strlen(command) - 1);
   strncat(command, " ", sizeof(command) - strlen(command) - 1);
@@ -282,16 +268,13 @@ int blocking_NAS_config(char *interfaceName, char *ipAddress, char *networkMask,
   strncat(command, networkMask, sizeof(command) - strlen(command) - 1);
   strncat(command, " broadcast ", sizeof(command) - strlen(command) - 1);
   strncat(command, broadcastAddress, sizeof(command) - strlen(command) - 1);
-
   // ifconfig nasmesh0 10.0.1.1 networkMask 255.255.255.0 broadcast 10.0.1.255
   int i = system (command);
-
   return i;
 }
 
 // program help
-void helpOptions(char **argv)
-{
+void helpOptions(char **argv) {
   printf("Help for %s\n",  argv[0]);
   printf("  -i <interfaceName>\n");
   printf("  -a <IP address>\n");
@@ -303,13 +286,11 @@ void helpOptions(char **argv)
   printf("    IP Address: 10.0.1.1\n");
   printf("    Net mask: 255.255.255.0\n");
   printf("    Broadcast address: [Beginning of the IP address].255\n");
-
   exit(1);
 }
 
 // creates the broadcast address if it wasn't set before
-void createBroadcast(char *broadcastAddress)
-{
+void createBroadcast(char *broadcastAddress) {
   int pos=strlen(broadcastAddress)-1;
 
   while(broadcastAddress[pos]!='.')
@@ -331,7 +312,6 @@ int main(int argc,char **argv)
   char ipAddress[100];
   char networkMask[100];
   char broadcastAddress[100];
-
   strcpy(interfaceName, "oai0");
   strcpy(ipAddress, "10.0.1.1");
   strcpy(networkMask, "255.255.255.0");
@@ -339,38 +319,38 @@ int main(int argc,char **argv)
 
   while ((c = getopt (argc, argv, "i:a:n:b:h")) != -1)
     switch (c) {
-    case 'h':
-      helpOptions(argv);
-      break;
-
-    case 'i':
-      strcpy(interfaceName,optarg);
-      break;
-
-    case 'a':
-      strcpy(ipAddress,optarg);
-      break;
-
-    case 'n':
-      strcpy(networkMask,optarg);
-      break;
-
-    case 'b':
-      strcpy(broadcastAddress,optarg);
-      break;
-
-    case '?':
-      if (isprint (optopt))
-        fprintf (stderr, "Unknown option `-%c'.\n", optopt);
-      else
-        fprintf (stderr,
-                 "Unknown option character `\\x%x'.\n",
-                 optopt);
-
-      return 1;
-
-    default:
-      abort ();
+      case 'h':
+        helpOptions(argv);
+        break;
+
+      case 'i':
+        strcpy(interfaceName,optarg);
+        break;
+
+      case 'a':
+        strcpy(ipAddress,optarg);
+        break;
+
+      case 'n':
+        strcpy(networkMask,optarg);
+        break;
+
+      case 'b':
+        strcpy(broadcastAddress,optarg);
+        break;
+
+      case '?':
+        if (isprint (optopt))
+          fprintf (stderr, "Unknown option `-%c'.\n", optopt);
+        else
+          fprintf (stderr,
+                   "Unknown option character `\\x%x'.\n",
+                   optopt);
+
+        return 1;
+
+      default:
+        abort ();
     }
 
   if(strlen(broadcastAddress)==0) {
@@ -383,7 +363,6 @@ int main(int argc,char **argv)
   //test
   //     setBaseNetAddress("11.11");
   //     nas_config(interfaceName, 33, 44);
-
 }
 
 #endif
diff --git a/openair2/RRC/NAS/nas_config.h b/openair2/RRC/NAS/nas_config.h
index 4426ca9a1aabfd2eb9be65ffb2bb9886f72534fe..fdc3c98f1b0a3ccef3dc881f95c0beca926c2112 100644
--- a/openair2/RRC/NAS/nas_config.h
+++ b/openair2/RRC/NAS/nas_config.h
@@ -31,6 +31,13 @@
 
 #include <netinet/in.h>
 
+/*! \fn void void nas_getparams(void)(void)
+ * \brief This function get parameters used to configure network interface when running in noS1 mode
+ * \note
+ * @ingroup  ?????
+ */
+void nas_getparams(void);
+
 /*! \fn int  NAS_config(char*, char*, char*, char*)
  * \brief This function initializes the nasmesh interface
  * \param[in] interfaceName, the name of the interface, e.g. nasmesh0 or nasmesh1
@@ -54,7 +61,7 @@ int NAS_config(char *interfaceName, char *ipAddress, char *networkMask, char *br
  * \note
  * @ingroup  ?????
  */
-int nas_config(int interface_id, int thirdOctet, int fourthOctet);
+int nas_config(int interface_id, int thirdOctet, int fourthOctet, char *ifsuffix);
 
 /*! \fn int  blocking_NAS_config(char*, char*, char*, char*)
  * \brief This function initializes the nasmesh interface, in a blocking way,
@@ -98,7 +105,7 @@ int set_gateway(char *interfaceName, char *gateway);
  * \note
  * @ingroup  ?????
  */
-void setBaseNetAddress(char* baseAddr);
+void setBaseNetAddress(char *baseAddr);
 
 /*! \fn char*  getBaseNetAddress()
  * \brief This function returns the basic network address used
@@ -106,7 +113,7 @@ void setBaseNetAddress(char* baseAddr);
  * \note
  * @ingroup  ?????
  */
-char* getBaseNetAddress(void);
+char *getBaseNetAddress(void);
 
 /*! \fn void  setNetMask(char*)
  * \brief This function sets the new default network mask used
@@ -114,7 +121,7 @@ char* getBaseNetAddress(void);
  * \note
  * @ingroup  ?????
  */
-void setNetMask(char* baseAddr);
+void setNetMask(char *baseAddr);
 
 /*! \fn char*  getNetMask()
  * \brief This function returns the network mask address in use
@@ -122,7 +129,7 @@ void setNetMask(char* baseAddr);
  * \note
  * @ingroup  ?????
  */
-char* getNetMask(void);
+char *getNetMask(void);
 
 /*! \fn coid setBroadcastAddress(char*)
  * \brief This function sets the new broadcast address used
@@ -130,7 +137,7 @@ char* getNetMask(void);
  * \note
  * @ingroup  ?????
  */
-void setBroadcastAddress(char* baseAddr);
+void setBroadcastAddress(char *baseAddr);
 
 /*! \fn char*  getBroadcastAddress()
  * \brief This function returns the broadcast address in use
@@ -138,7 +145,7 @@ void setBroadcastAddress(char* baseAddr);
  * \note
  * @ingroup  ?????
  */
-char* getBroadcastAddress(void);
+char *getBroadcastAddress(void);
 
 int bringInterfaceUp(char *interfaceName, int up);
 
diff --git a/targets/ARCH/COMMON/common_lib.c b/targets/ARCH/COMMON/common_lib.c
index b62eb9d2dfe3853101aaee71fe082bb5f71cd764..3f81816aa1022de2a623cb8bc865cadb0f9e74cd 100644
--- a/targets/ARCH/COMMON/common_lib.c
+++ b/targets/ARCH/COMMON/common_lib.c
@@ -19,8 +19,8 @@
  *      contact@openairinterface.org
  */
 
-/*! \file common_lib.c 
- * \brief common APIs for different RF frontend device 
+/*! \file common_lib.c
+ * \brief common APIs for different RF frontend device
  * \author HongliangXU, Navid Nikaein
  * \date 2015
  * \version 0.2
@@ -37,108 +37,124 @@
 
 #include "common_lib.h"
 #include "common/utils/load_module_shlib.h"
+#include "targets/RT/USER/lte-softmodem.h"
 
 int set_device(openair0_device *device) {
-
   switch (device->type) {
-    
-  case EXMIMO_DEV:
-    printf("[%s] has loaded EXPRESS MIMO device.\n",((device->host_type == RAU_HOST) ? "RAU": "RRU"));
-    break;
-  case USRP_B200_DEV:
-    printf("[%s] has loaded USRP B200 device.\n",((device->host_type == RAU_HOST) ? "RAU": "RRU")); 
-    break;
-  case USRP_X300_DEV:
-    printf("[%s] has loaded USRP X300 device.\n",((device->host_type == RAU_HOST) ? "RAU": "RRU")); 
-    break;
-  case BLADERF_DEV:
-    printf("[%s] has loaded BLADERF device.\n",((device->host_type == RAU_HOST) ? "RAU": "RRU")); 
-    break;
-  case LMSSDR_DEV:
-    printf("[%s] has loaded LMSSDR device.\n",((device->host_type == RAU_HOST) ? "RAU": "RRU")); 
-    break;
-  case IRIS_DEV:
-    printf("[%s] has loaded Iris device.\n",((device->host_type == RAU_HOST) ? "RAU": "RRU"));
-    break;  
-  case NONE_DEV:
-    printf("[%s] has not loaded a HW device.\n",((device->host_type == RAU_HOST) ? "RAU": "RRU"));
-    break;    
-  default:
-    printf("[%s] invalid HW device.\n",((device->host_type == RAU_HOST) ? "RAU": "RRU")); 
-    return -1;
+    case EXMIMO_DEV:
+      printf("[%s] has loaded EXPRESS MIMO device.\n",((device->host_type == RAU_HOST) ? "RAU": "RRU"));
+      break;
+
+    case USRP_B200_DEV:
+      printf("[%s] has loaded USRP B200 device.\n",((device->host_type == RAU_HOST) ? "RAU": "RRU"));
+      break;
+
+    case USRP_X300_DEV:
+      printf("[%s] has loaded USRP X300 device.\n",((device->host_type == RAU_HOST) ? "RAU": "RRU"));
+      break;
+
+    case BLADERF_DEV:
+      printf("[%s] has loaded BLADERF device.\n",((device->host_type == RAU_HOST) ? "RAU": "RRU"));
+      break;
+
+    case LMSSDR_DEV:
+      printf("[%s] has loaded LMSSDR device.\n",((device->host_type == RAU_HOST) ? "RAU": "RRU"));
+      break;
+
+    case IRIS_DEV:
+      printf("[%s] has loaded Iris device.\n",((device->host_type == RAU_HOST) ? "RAU": "RRU"));
+      break;
+
+    case NONE_DEV:
+      printf("[%s] has not loaded a HW device.\n",((device->host_type == RAU_HOST) ? "RAU": "RRU"));
+      break;
+
+    default:
+      printf("[%s] invalid HW device.\n",((device->host_type == RAU_HOST) ? "RAU": "RRU"));
+      return -1;
   }
+
   return 0;
 }
 
 int set_transport(openair0_device *device) {
-
   switch (device->transp_type) {
-    
-  case ETHERNET_TP:
-    printf("[%s] has loaded ETHERNET trasport protocol.\n",((device->host_type == RAU_HOST) ? "RAU": "RRU"));
-    return 0;     
-    break;
-  case NONE_TP:
-    printf("[%s] has not loaded a transport protocol.\n",((device->host_type == RAU_HOST) ? "RAU": "RRU"));
-    return 0; 
-    break;    
-  default:
-    printf("[%s] invalid transport protocol.\n",((device->host_type == RAU_HOST) ? "RAU": "RRU")); 
-    return -1;
-    break;
+    case ETHERNET_TP:
+      printf("[%s] has loaded ETHERNET trasport protocol.\n",((device->host_type == RAU_HOST) ? "RAU": "RRU"));
+      return 0;
+      break;
+
+    case NONE_TP:
+      printf("[%s] has not loaded a transport protocol.\n",((device->host_type == RAU_HOST) ? "RAU": "RRU"));
+      return 0;
+      break;
+
+    default:
+      printf("[%s] invalid transport protocol.\n",((device->host_type == RAU_HOST) ? "RAU": "RRU"));
+      return -1;
+      break;
   }
-  
 }
 typedef int(*devfunc_t)(openair0_device *, openair0_config_t *, eth_params_t *);
 /* look for the interface library and load it */
-int load_lib(openair0_device *device, openair0_config_t *openair0_cfg, eth_params_t * cfg, uint8_t flag) {
-  
+int load_lib(openair0_device *device, openair0_config_t *openair0_cfg, eth_params_t *cfg, uint8_t flag) {
   loader_shlibfunc_t shlib_fdesc[1];
   int ret=0;
   char *libname;
-  if (flag == RAU_LOCAL_RADIO_HEAD) {
-      libname=OAI_RF_LIBNAME;
-      shlib_fdesc[0].fname="device_init";
-    } else {
-      libname=OAI_TP_LIBNAME;
-      shlib_fdesc[0].fname="transport_init";      
-    } 
+
+  if ( IS_SOFTMODEM_BASICSIM ) {
+    libname=OAI_BASICSIM_LIBNAME;
+    shlib_fdesc[0].fname="device_init";
+  } else if ( IS_SOFTMODEM_RFSIM ) {
+    libname=OAI_RFSIM_LIBNAME;
+    shlib_fdesc[0].fname="device_init";
+  } else if (flag == RAU_LOCAL_RADIO_HEAD) {
+    libname=OAI_RF_LIBNAME;
+    shlib_fdesc[0].fname="device_init";
+  } else {
+    libname=OAI_TP_LIBNAME;
+    shlib_fdesc[0].fname="transport_init";
+  }
+
   ret=load_module_shlib(libname,shlib_fdesc,1,NULL);
+
   if (ret < 0) {
-       fprintf(stderr,"Library %s couldn't be loaded\n",libname);
+    fprintf(stderr,"Library %s couldn't be loaded\n",libname);
   } else {
-       ret=((devfunc_t)shlib_fdesc[0].fptr)(device,openair0_cfg,cfg);
-  }    
-  return ret; 	       
+    ret=((devfunc_t)shlib_fdesc[0].fptr)(device,openair0_cfg,cfg);
+  }
+
+  return ret;
 }
 
 
 
 int openair0_device_load(openair0_device *device, openair0_config_t *openair0_cfg) {
-  
   int rc=0;
   rc=load_lib(device, openair0_cfg, NULL,RAU_LOCAL_RADIO_HEAD );
 
-  if ( rc >= 0) {       
-	if ( set_device(device) < 0) {
+  if ( rc >= 0) {
+    if ( set_device(device) < 0) {
       fprintf(stderr, "%s %d:Unsupported radio head\n",__FILE__, __LINE__);
-      return -1;		   
-    }   
+      return -1;
+    }
   }
+
   return rc;
 }
 
-int openair0_transport_load(openair0_device *device, openair0_config_t *openair0_cfg, eth_params_t * eth_params) {
+int openair0_transport_load(openair0_device *device, openair0_config_t *openair0_cfg, eth_params_t *eth_params) {
   int rc;
   rc=load_lib(device, openair0_cfg, eth_params, RAU_REMOTE_RADIO_HEAD);
-  if ( rc >= 0) {       
+
+  if ( rc >= 0) {
     if ( set_transport(device) < 0) {
       fprintf(stderr, "%s %d:Unsupported transport protocol\n",__FILE__, __LINE__);
-      return -1;		   
-      }   
+      return -1;
+    }
   }
-  return rc;
 
+  return rc;
 }
 
 
diff --git a/targets/ARCH/COMMON/common_lib.h b/targets/ARCH/COMMON/common_lib.h
index 084ef9fcd9fbc629e6381f2d4a5ef025696f06ec..0af6fa9c5edb89be8dfd193c1692a0f072ea5f90 100644
--- a/targets/ARCH/COMMON/common_lib.h
+++ b/targets/ARCH/COMMON/common_lib.h
@@ -19,8 +19,8 @@
  *      contact@openairinterface.org
  */
 
-/*! \file common_lib.h 
- * \brief common APIs for different RF frontend device 
+/*! \file common_lib.h
+ * \brief common APIs for different RF frontend device
  * \author HongliangXU, Navid Nikaein
  * \date 2015
  * \version 0.2
@@ -39,19 +39,22 @@
 #define OAI_RF_LIBNAME        "oai_device"
 /* name of shared library implementing the transport */
 #define OAI_TP_LIBNAME        "oai_transpro"
-
+/* name of shared library implementing the basic/rf simulator */
+#define OAI_RFSIM_LIBNAME        "rfsimulator"
+/* name of shared library implementing the basic/rf simulator */
+#define OAI_BASICSIM_LIBNAME        "tcp_bridge_oai"
 /* flags for BBU to determine whether the attached radio head is local or remote */
 #define RAU_LOCAL_RADIO_HEAD  0
 #define RAU_REMOTE_RADIO_HEAD 1
 
 #ifndef MAX_CARDS
-#define MAX_CARDS 8
+  #define MAX_CARDS 8
 #endif
 
 typedef int64_t openair0_timestamp;
 typedef volatile int64_t openair0_vtimestamp;
 
- 
+
 /*!\brief structrue holds the parameters to configure USRP devices*/
 typedef struct openair0_device_t openair0_device;
 
@@ -120,16 +123,16 @@ typedef enum {
 /*!\brief  openair0 device host type */
 typedef enum {
   MIN_HOST_TYPE = 0,
- /*!\brief device functions within a RAU */
+  /*!\brief device functions within a RAU */
   RAU_HOST,
- /*!\brief device functions within a RRU */
+  /*!\brief device functions within a RRU */
   RRU_HOST,
   MAX_HOST_TYPE
 
-}host_type_t;
+} host_type_t;
 
 
-/*! \brief RF Gain clibration */ 
+/*! \brief RF Gain clibration */
 typedef struct {
   //! Frequency for which RX chain was calibrated
   double freq;
@@ -157,7 +160,7 @@ typedef struct {
   duplex_mode_t duplex_mode;
   //! number of downlink resource blocks
   int num_rb_dl;
-  //! number of samples per frame 
+  //! number of samples per frame
   unsigned int  samples_per_frame;
   //! the sample rate for both transmit and receive.
   double sample_rate;
@@ -172,9 +175,9 @@ typedef struct {
   //! number of TX channels (=TX antennas)
   int tx_num_channels;
   //! \brief RX base addresses for mmapped_dma
-  int32_t* rxbase[4];
+  int32_t *rxbase[4];
   //! \brief TX base addresses for mmapped_dma
-  int32_t* txbase[4];
+  int32_t *txbase[4];
   //! \brief Center frequency in Hz for RX.
   //! index: [0..rx_num_channels[
   double rx_freq[4];
@@ -185,7 +188,7 @@ typedef struct {
   //! \brief Pointer to Calibration table for RX gains
   rx_gain_calib_table_t *rx_gain_calib_table;
 
-  //! mode for rxgain (ExpressMIMO2) 
+  //! mode for rxgain (ExpressMIMO2)
   rx_gain_t rxg_mode[4];
   //! \brief Gain for RX in dB.
   //! index: [0..rx_num_channels]
@@ -199,14 +202,14 @@ typedef struct {
   double rx_bw;
   //! TX bandwidth in Hz
   double tx_bw;
-  //! clock source 
+  //! clock source
   clock_source_t clock_source;
   //! Manual SDR IP address
   char *sdr_addrs;
   //! Auto calibration flag
   int autocal[4];
   //! rf devices work with x bits iqs when oai have its own iq format
-  //! the two following parameters are used to convert iqs 
+  //! the two following parameters are used to convert iqs
   int iq_txshift;
   int iq_rxrescale;
   //! Configuration file for LMS7002M
@@ -219,10 +222,10 @@ typedef struct {
   unsigned int   sf_read_delay;     // read delay in replay mode
   unsigned int   sf_write_delay;    // write delay in replay mode
   unsigned int   eth_mtu;           // ethernet MTU
-#endif  
+#endif
 } openair0_config_t;
 
-/*! \brief RF mapping */ 
+/*! \brief RF mapping */
 typedef struct {
   //! card id
   int card;
@@ -269,14 +272,14 @@ struct openair0_device_t {
 
   /*!brief Component Carrier ID of this device */
   int CC_id;
-  
+
   /*!brief Type of this device */
   dev_type_t type;
 
   /*!brief Transport protocol type that the device suppports (in case I/Q samples need to be transported) */
   transport_type_t transp_type;
 
-   /*!brief Type of the device's host (RAU/RRU) */
+  /*!brief Type of the device's host (RAU/RRU) */
   host_type_t host_type;
 
   /* !brief RF frontend parameters set by application */
@@ -298,25 +301,25 @@ struct openair0_device_t {
   /*! \brief Called to send a request message between RAU-RRU on control port
       @param device pointer to the device structure specific to the RF hardware target
       @param msg pointer to the message structure passed between RAU-RRU
-      @param msg_len length of the message  
-  */  
+      @param msg_len length of the message
+  */
   int (*trx_ctlsend_func)(openair0_device *device, void *msg, ssize_t msg_len);
 
   /*! \brief Called to receive a reply  message between RAU-RRU on control port
       @param device pointer to the device structure specific to the RF hardware target
       @param msg pointer to the message structure passed between RAU-RRU
-      @param msg_len length of the message  
-  */  
+      @param msg_len length of the message
+  */
   int (*trx_ctlrecv_func)(openair0_device *device, void *msg, ssize_t msg_len);
 
   /*! \brief Called to send samples to the RF target
       @param device pointer to the device structure specific to the RF hardware target
-      @param timestamp The timestamp at whicch the first sample MUST be sent 
+      @param timestamp The timestamp at whicch the first sample MUST be sent
       @param buff Buffer which holds the samples
       @param nsamps number of samples to be sent
       @param antenna_id index of the antenna if the device has multiple anteannas
       @param flags flags must be set to TRUE if timestamp parameter needs to be applied
-  */   
+  */
   int (*trx_write_func)(openair0_device *device, openair0_timestamp timestamp, void **buff, int nsamps,int antenna_id, int flags);
 
   /*! \brief Receive samples from hardware.
@@ -332,55 +335,55 @@ struct openair0_device_t {
    */
   int (*trx_read_func)(openair0_device *device, openair0_timestamp *ptimestamp, void **buff, int nsamps,int antenna_id);
 
-  /*! \brief print the device statistics  
+  /*! \brief print the device statistics
    * \param device the hardware to use
    * \returns  0 on success
    */
   int (*trx_get_stats_func)(openair0_device *device);
 
-  /*! \brief Reset device statistics  
+  /*! \brief Reset device statistics
    * \param device the hardware to use
-   * \returns 0 in success 
+   * \returns 0 in success
    */
   int (*trx_reset_stats_func)(openair0_device *device);
 
-  /*! \brief Terminate operation of the transceiver -- free all associated resources 
+  /*! \brief Terminate operation of the transceiver -- free all associated resources
    * \param device the hardware to use
    */
   void (*trx_end_func)(openair0_device *device);
 
-  /*! \brief Stop operation of the transceiver 
+  /*! \brief Stop operation of the transceiver
    */
   int (*trx_stop_func)(openair0_device *device);
 
   /* Functions API related to UE*/
 
-  /*! \brief Set RX feaquencies 
+  /*! \brief Set RX feaquencies
    * \param device the hardware to use
    * \param openair0_cfg RF frontend parameters set by application
-   * \param exmimo_dump_config  dump EXMIMO configuration 
-   * \returns 0 in success 
+   * \param exmimo_dump_config  dump EXMIMO configuration
+   * \returns 0 in success
    */
-  int (*trx_set_freq_func)(openair0_device* device, openair0_config_t *openair0_cfg,int exmimo_dump_config);
-  
+  int (*trx_set_freq_func)(openair0_device *device, openair0_config_t *openair0_cfg,int exmimo_dump_config);
+
   /*! \brief Set gains
    * \param device the hardware to use
    * \param openair0_cfg RF frontend parameters set by application
-   * \returns 0 in success 
+   * \returns 0 in success
    */
-  int (*trx_set_gains_func)(openair0_device* device, openair0_config_t *openair0_cfg);
+  int (*trx_set_gains_func)(openair0_device *device, openair0_config_t *openair0_cfg);
 
   /*! \brief RRU Configuration callback
    * \param idx RU index
    * \param arg pointer to capabilities or configuration
    */
-  void (*configure_rru)(int idx, void* arg);
+  void (*configure_rru)(int idx, void *arg);
 };
 
 /* type of device init function, implemented in shared lib */
 typedef int(*oai_device_initfunc_t)(openair0_device *device, openair0_config_t *openair0_cfg);
 /* type of transport init function, implemented in shared lib */
-typedef int(*oai_transport_initfunc_t)(openair0_device *device, openair0_config_t *openair0_cfg, eth_params_t * eth_params);
+typedef int(*oai_transport_initfunc_t)(openair0_device *device, openair0_config_t *openair0_cfg, eth_params_t *eth_params);
 
 #ifdef __cplusplus
 extern "C"
@@ -388,23 +391,23 @@ extern "C"
 #endif
 
 
-  /*! \brief Initialize openair RF target. It returns 0 if OK */
-  int openair0_device_load(openair0_device *device, openair0_config_t *openair0_cfg);  
-  /*! \brief Initialize transport protocol . It returns 0 if OK */
-  int openair0_transport_load(openair0_device *device, openair0_config_t *openair0_cfg, eth_params_t * eth_params);
+/*! \brief Initialize openair RF target. It returns 0 if OK */
+int openair0_device_load(openair0_device *device, openair0_config_t *openair0_cfg);
+/*! \brief Initialize transport protocol . It returns 0 if OK */
+int openair0_transport_load(openair0_device *device, openair0_config_t *openair0_cfg, eth_params_t *eth_params);
 
-  
- /*! \brief Get current timestamp of USRP
-  * \param device the hardware to use
-  */
-  openair0_timestamp get_usrp_time(openair0_device *device);
 
- /*! \brief Set RX frequencies 
-  * \param device the hardware to use
-  * \param openair0_cfg RF frontend parameters set by application
-  * \returns 0 in success 
-  */
-  int openair0_set_rx_frequencies(openair0_device* device, openair0_config_t *openair0_cfg);
+/*! \brief Get current timestamp of USRP
+ * \param device the hardware to use
+ */
+openair0_timestamp get_usrp_time(openair0_device *device);
+
+/*! \brief Set RX frequencies
+ * \param device the hardware to use
+ * \param openair0_cfg RF frontend parameters set by application
+ * \returns 0 in success
+ */
+int openair0_set_rx_frequencies(openair0_device *device, openair0_config_t *openair0_cfg);
 
 /*@}*/
 
diff --git a/targets/ARCH/ETHERNET/USERSPACE/LIB/eth_raw.c b/targets/ARCH/ETHERNET/USERSPACE/LIB/eth_raw.c
index acb4c2ec9bfb7a8a7d6708c283356842f181ecf6..2c8e55d14f0bbe43961965aeaee161627701b921 100644
--- a/targets/ARCH/ETHERNET/USERSPACE/LIB/eth_raw.c
+++ b/targets/ARCH/ETHERNET/USERSPACE/LIB/eth_raw.c
@@ -138,7 +138,7 @@ int eth_socket_init_raw(openair0_device *device) {
  return 0;
 }
 
-
+/* 09/03/2019: fix obvious inconsistencies, but this code hasn't be tested for sure */
 int trx_eth_write_raw(openair0_device *device, openair0_timestamp timestamp, void **buff, int nsamps,int cc, int flags) {
   
   int bytes_sent=0;
@@ -148,7 +148,12 @@ int trx_eth_write_raw(openair0_device *device, openair0_timestamp timestamp, voi
   //sendto_flag|=flags;
 
   eth->tx_nsamps=nsamps;
-  
+  int pktsize;
+  if (eth->compression == ALAW_COMPRESS) {
+    pktsize = RAW_PACKET_SIZE_BYTES_ALAW(nsamps);
+  } else {
+    pktsize = RAW_PACKET_SIZE_BYTES(nsamps);
+  }   
   for (i=0;i<cc;i++) {	
     /* buff[i] points to the position in tx buffer where the payload to be sent is
        buff2 points to the position in tx buffer where the packet header will be placed */
@@ -162,44 +167,27 @@ int trx_eth_write_raw(openair0_device *device, openair0_timestamp timestamp, voi
     bytes_sent = 0;
     memcpy(buff2,(void*)&eth->ehd,MAC_HEADER_SIZE_BYTES);
     *(int16_t *)(buff2 + MAC_HEADER_SIZE_BYTES + sizeof(int16_t))=1+(i<<1);
-    *(openair0_timestamp *)(buff2 + MAC_HEADER_SIZE_BYTES + sizeof(int32_t)) = timestamp;
-  
-    int sent_byte;
-    
+    *(openair0_timestamp *)(buff2 + MAC_HEADER_SIZE_BYTES + sizeof(int32_t)) = timestamp;  
 
     /*printf("[RRU]write mod_%d %d , len %d, buff %p \n",
       Mod_id,eth->sockfd[Mod_id],RAW_PACKET_SIZE_BYTES(nsamps), buff2);*/
     
-    while(bytes_sent < sent_byte) {
-#if DEBUG   
-      printf("------- TX ------: buff2 current position=%d remaining_bytes=%d  bytes_sent=%d \n",
-	     (void *)(buff2+bytes_sent), 
-	     sent_byte - bytes_sent,
-	     bytes_sent);
-#endif
+    while(bytes_sent < pktsize) {
+
       /* Send packet */
 
       bytes_sent += send(eth->sockfdd,
 			 buff2, 
-			 sent_byte,
+			 pktsize,
 			 sendto_flag);
       if ( bytes_sent == -1) {
 	eth->num_tx_errors++;
 	perror("ETHERNET WRITE: ");
 	exit(-1);
       } else {
-#if DEBUG
-	printf("------- TX ------: nu=%x an_id=%d ts%d bytes_sent=%d\n",
-	       *(uint8_t *)(buff2+ETH_ALEN),
-	       *(int16_t *)(buff2 + MAC_HEADER_SIZE_BYTES + sizeof(int16_t)),
-	       *(openair0_timestamp *)(buff2 + MAC_HEADER_SIZE_BYTES + sizeof(int32_t)), 
-	       bytes_sent);
-
-    dump_packet((device->host_type == RAU_HOST)? "RAU":"RRU", buff2, sent_byte, TX_FLAG);
 
-#endif
-    eth->tx_actual_nsamps=bytes_sent>>2;
-    eth->tx_count++;
+      eth->tx_actual_nsamps=bytes_sent>>2;
+      eth->tx_count++;
       }
     }    			    
     
diff --git a/targets/ARCH/rfsimulator/README.md b/targets/ARCH/rfsimulator/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..89964decd50e77c4f514c3207eefd3ae7612b747
--- /dev/null
+++ b/targets/ARCH/rfsimulator/README.md
@@ -0,0 +1,68 @@
+#General
+This is a RF simulator that allows to test OAI without a RF board.
+It replaces a actual RF board driver.
+
+As much as possible, it works like a RF board, but not in realtime: it can run faster than realtime if there is enough CPU or slower (it is CPU bound instead of real time RF sampling bound)
+
+#build
+
+## From build_oai
+You can build it the same way, and together with actual RF driver
+
+Example:
+```bash
+./build_oai --ue-nas-use-tun --UE --eNB -w SIMU
+```
+It is also possible to build actual RF and use choose on each run:
+```bash
+./build_oai --ue-nas-use-tun --UE --eNB -w USRP --rfsimulator
+```
+Will build both the eNB (lte-softmodem) and the UE (lte-uesoftmodem)
+We recommend to use the option --ue-nas-use-tun that is much simpler to use than the OAI kernel driver.
+
+## Add the rfsimulator after initial build
+After any regular build, you can compile the driver
+```bash
+cd <the_compilation_dir_from_bouild_oai_script>/build
+make rfsimulator
+```
+Then, you can use it freely
+
+# Usage
+Setting the env variable RFSIMULATOR enables the RF board simulator
+It should the set to "enb" in the eNB
+
+## 4G case
+For the UE, it should be set to the IP address of the eNB
+example: 
+```bash
+sudo RFSIMULATOR=192.168.2.200 ./lte-uesoftmodem -C 2685000000 -r 50 
+```
+Except this, the UE and the eNB can be used as it the RF is real
+
+If you reach 'RA not active' on UE, be careful to generate a valid SIM
+```bash
+$OPENAIR_DIR/targets/bin/conf2uedata -c $OPENAIR_DIR/openair3/NAS/TOOLS/ue_eurecom_test_sfr.conf -o .
+```
+## 5G case
+After regular build, add the simulation driver
+(don't use ./build_oai -w SIMU until we merge 4G and 5G branches)
+```bash
+cd ran_build/build
+make rfsimulator
+```
+### Launch gNB in one window
+```bash
+sudo RFSIMULATOR=enb ./nr-softmodem -O ../../../targets/PROJECTS/GENERIC-LTE-EPC/CONF/gnb.band78.tm1.106PRB.usrpn300.conf --parallel-config PARALLEL_SINGLE_THREAD
+```
+### Launch UE in another window
+```bash
+sudo RFSIMULATOR=127.0.0.1 ./nr-uesoftmodem --numerology 1 -r 106 -C 3510000000 
+```
+Of course, set the gNB machine IP address if the UE and the gNB are not on the same machine
+In UE, you can add "-d" to get the softscope
+
+#Caveacts
+Still issues in power control: txgain, rxgain are not used
+
+no S1 mode is currently broken, so we were not able to test the simulator in noS1 mode
diff --git a/targets/ARCH/rfsimulator/simulator.c b/targets/ARCH/rfsimulator/simulator.c
new file mode 100644
index 0000000000000000000000000000000000000000..a17327b03ecc5791cadc7cef76fbecc9d3205da8
--- /dev/null
+++ b/targets/ARCH/rfsimulator/simulator.c
@@ -0,0 +1,475 @@
+/*
+  Author: Laurent THOMAS, Open Cells for Nokia
+  copyleft: OpenAirInterface Software Alliance and it's licence
+*/
+
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <arpa/inet.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+#include <stdbool.h>
+#include <errno.h>
+#include <sys/epoll.h>
+#include <string.h>
+
+#include <common/utils/assertions.h>
+#include <common/utils/LOG/log.h>
+#include "common_lib.h"
+#include <openair1/PHY/defs_eNB.h>
+#include "openair1/PHY/defs_UE.h"
+
+#define PORT 4043 //TCP port for this simulator
+#define CirSize 3072000 // 100ms is enough
+#define sample_t uint32_t // 2*16 bits complex number
+#define sampleToByte(a,b) ((a)*(b)*sizeof(sample_t))
+#define byteToSample(a,b) ((a)/(sizeof(sample_t)*(b)))
+#define MAGICeNB 0xA5A5A5A5A5A5A5A5
+#define MAGICUE  0x5A5A5A5A5A5A5A5A
+
+typedef struct {
+  uint64_t magic;
+  uint32_t size;
+  uint32_t nbAnt;
+  uint64_t timestamp;
+} transferHeader;
+
+typedef struct buffer_s {
+  int conn_sock;
+  bool alreadyRead;
+  uint64_t lastReceivedTS;
+  bool headerMode;
+  transferHeader th;
+  char *transferPtr;
+  uint64_t remainToTransfer;
+  char *circularBufEnd;
+  sample_t *circularBuf;
+} buffer_t;
+
+typedef struct {
+  int listen_sock, epollfd;
+  uint64_t nextTimestamp;
+  uint64_t typeStamp;
+  uint64_t initialAhead;
+  char *ip;
+  buffer_t buf[FD_SETSIZE];
+} rfsimulator_state_t;
+
+void allocCirBuf(rfsimulator_state_t *bridge, int sock) {
+  buffer_t *ptr=&bridge->buf[sock];
+  AssertFatal ( (ptr->circularBuf=(sample_t *) malloc(sampleToByte(CirSize,1))) != NULL, "");
+  ptr->circularBufEnd=((char *)ptr->circularBuf)+sampleToByte(CirSize,1);
+  ptr->conn_sock=sock;
+  ptr->headerMode=true;
+  ptr->transferPtr=(char *)&ptr->th;
+  ptr->remainToTransfer=sizeof(transferHeader);
+  int sendbuff=1000*1000*10;
+  AssertFatal ( setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &sendbuff, sizeof(sendbuff)) == 0, "");
+  struct epoll_event ev= {0};
+  ev.events = EPOLLIN | EPOLLRDHUP;
+  ev.data.fd = sock;
+  AssertFatal(epoll_ctl(bridge->epollfd, EPOLL_CTL_ADD,  sock, &ev) != -1, "");
+}
+
+void removeCirBuf(rfsimulator_state_t *bridge, int sock) {
+  AssertFatal( epoll_ctl(bridge->epollfd, EPOLL_CTL_DEL,  sock, NULL) != -1, "");
+  close(sock);
+  free(bridge->buf[sock].circularBuf);
+  memset(&bridge->buf[sock], 0, sizeof(buffer_t));
+  bridge->buf[sock].conn_sock=-1;
+}
+
+void socketError(rfsimulator_state_t *bridge, int sock) {
+  if (bridge->buf[sock].conn_sock!=-1) {
+    LOG_W(HW,"Lost socket \n");
+    removeCirBuf(bridge, sock);
+
+    if (bridge->typeStamp==MAGICUE)
+      exit(1);
+  }
+}
+
+
+#define helpTxt "\
+\x1b[31m\
+rfsimulator: error: you have to run one UE and one eNB\n\
+For this, export RFSIMULATOR=enb (eNB case) or \n\
+                 RFSIMULATOR=<an ip address> (UE case)\n\
+\x1b[m"
+
+enum  blocking_t {
+  notBlocking,
+  blocking
+};
+
+void setblocking(int sock, enum blocking_t active) {
+  int opts;
+  AssertFatal( (opts = fcntl(sock, F_GETFL)) >= 0,"");
+
+  if (active==blocking)
+    opts = opts & ~O_NONBLOCK;
+  else
+    opts = opts | O_NONBLOCK;
+
+  AssertFatal(fcntl(sock, F_SETFL, opts) >= 0, "");
+}
+
+static bool flushInput(rfsimulator_state_t *t);
+
+void fullwrite(int fd, void *_buf, int count, rfsimulator_state_t *t) {
+  char *buf = _buf;
+  int l;
+  setblocking(fd, notBlocking);
+
+  while (count) {
+    l = write(fd, buf, count);
+
+    if (l <= 0) {
+      if (errno==EINTR)
+        continue;
+
+      if(errno==EAGAIN) {
+        flushInput(t);
+        continue;
+      } else
+        return;
+    }
+
+    count -= l;
+    buf += l;
+  }
+}
+
+int server_start(openair0_device *device) {
+  rfsimulator_state_t *t = (rfsimulator_state_t *) device->priv;
+  t->typeStamp=MAGICeNB;
+  AssertFatal((t->listen_sock = socket(AF_INET, SOCK_STREAM, 0)) >= 0, "");
+  int enable = 1;
+  AssertFatal(setsockopt(t->listen_sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) == 0, "");
+  struct sockaddr_in addr = {
+sin_family:
+    AF_INET,
+sin_port:
+    htons(PORT),
+sin_addr:
+    { s_addr: INADDR_ANY }
+  };
+  bind(t->listen_sock, (struct sockaddr *)&addr, sizeof(addr));
+  AssertFatal(listen(t->listen_sock, 5) == 0, "");
+  struct epoll_event ev;
+  ev.events = EPOLLIN;
+  ev.data.fd = t->listen_sock;
+  AssertFatal(epoll_ctl(t->epollfd, EPOLL_CTL_ADD,  t->listen_sock, &ev) != -1, "");
+  return 0;
+}
+
+int start_ue(openair0_device *device) {
+  rfsimulator_state_t *t = device->priv;
+  t->typeStamp=MAGICUE;
+  int sock;
+  AssertFatal((sock = socket(AF_INET, SOCK_STREAM, 0)) >= 0, "");
+  struct sockaddr_in addr = {
+sin_family:
+    AF_INET,
+sin_port:
+    htons(PORT),
+sin_addr:
+    { s_addr: INADDR_ANY }
+  };
+  addr.sin_addr.s_addr = inet_addr(t->ip);
+  bool connected=false;
+
+  while(!connected) {
+    LOG_I(HW,"rfsimulator: trying to connect to %s:%d\n", t->ip, PORT);
+
+    if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0) {
+      LOG_I(HW,"rfsimulator: connection established\n");
+      connected=true;
+    }
+
+    perror("rfsimulator");
+    sleep(1);
+  }
+
+  setblocking(sock, notBlocking);
+  allocCirBuf(t, sock);
+  t->buf[sock].alreadyRead=true; // UE will start blocking on read
+  return 0;
+}
+
+int rfsimulator_write(openair0_device *device, openair0_timestamp timestamp, void **samplesVoid, int nsamps, int nbAnt, int flags) {
+  rfsimulator_state_t *t = device->priv;
+
+  for (int i=0; i<FD_SETSIZE; i++) {
+    buffer_t *ptr=&t->buf[i];
+
+    if (ptr->conn_sock >= 0 ) {
+      transferHeader header= {t->typeStamp, nsamps, nbAnt, timestamp};
+      fullwrite(ptr->conn_sock,&header, sizeof(header), t);
+      sample_t tmpSamples[nsamps][nbAnt];
+
+      for(int a=0; a<nbAnt; a++) {
+        sample_t *in=(sample_t *)samplesVoid[a];
+
+        for(int s=0; s<nsamps; s++)
+          tmpSamples[s][a]=in[s];
+      }
+
+      if (ptr->conn_sock >= 0 )
+        fullwrite(ptr->conn_sock, (void *)tmpSamples, sampleToByte(nsamps,nbAnt), t);
+    }
+  }
+
+  LOG_D(HW,"sent %d samples at time: %ld->%ld, energy in first antenna: %d\n",
+        nsamps, timestamp, timestamp+nsamps, signal_energy(samplesVoid[0], nsamps) );
+  return nsamps;
+}
+
+static bool flushInput(rfsimulator_state_t *t) {
+  // Process all incoming events on sockets
+  // store the data in lists
+  struct epoll_event events[FD_SETSIZE]= {0};
+  int nfds = epoll_wait(t->epollfd, events, FD_SETSIZE, 200);
+
+  if ( nfds==-1 ) {
+    if ( errno==EINTR || errno==EAGAIN )
+      return false;
+    else
+      AssertFatal(false,"error in epoll_wait\n");
+  }
+
+  for (int nbEv = 0; nbEv < nfds; ++nbEv) {
+    int fd=events[nbEv].data.fd;
+
+    if (events[nbEv].events & EPOLLIN && fd == t->listen_sock) {
+      int conn_sock;
+      AssertFatal( (conn_sock = accept(t->listen_sock,NULL,NULL)) != -1, "");
+      setblocking(conn_sock, notBlocking);
+      allocCirBuf(t, conn_sock);
+      LOG_I(HW,"A ue connected\n");
+    } else {
+      if ( events[nbEv].events & (EPOLLHUP | EPOLLERR | EPOLLRDHUP) ) {
+        socketError(t,fd);
+        continue;
+      }
+
+      buffer_t *b=&t->buf[fd];
+
+      if ( b->circularBuf == NULL ) {
+        LOG_E(HW, "received data on not connected socket %d\n", events[nbEv].data.fd);
+        continue;
+      }
+
+      int blockSz;
+
+      if ( b->headerMode)
+        blockSz=b->remainToTransfer;
+      else
+        blockSz= b->transferPtr+b->remainToTransfer < b->circularBufEnd ?
+                 b->remainToTransfer :
+                 b->circularBufEnd - 1 - b->transferPtr ;
+
+      int sz=recv(fd, b->transferPtr, blockSz, MSG_DONTWAIT);
+
+      if ( sz < 0 ) {
+        if ( errno != EAGAIN ) {
+          LOG_E(HW,"socket failed %s\n", strerror(errno));
+          abort();
+        }
+      } else if ( sz == 0 )
+        continue;
+
+      AssertFatal((b->remainToTransfer-=sz) >= 0, "");
+      b->transferPtr+=sz;
+
+      if (b->transferPtr==b->circularBufEnd - 1)
+        b->transferPtr=(char *)b->circularBuf;
+
+      // check the header and start block transfer
+      if ( b->headerMode==true && b->remainToTransfer==0) {
+        AssertFatal( (t->typeStamp == MAGICUE  && b->th.magic==MAGICeNB) ||
+                     (t->typeStamp == MAGICeNB && b->th.magic==MAGICUE), "Socket Error in protocol");
+        b->headerMode=false;
+        b->alreadyRead=true;
+
+        if ( b->lastReceivedTS != b->th.timestamp) {
+          int nbAnt= b->th.nbAnt;
+
+          for (uint64_t index=b->lastReceivedTS; index < b->th.timestamp; index++ )
+            for (int a=0; a < nbAnt; a++)
+              b->circularBuf[(index*nbAnt+a)%CirSize]=0;
+
+          LOG_W(HW,"gap of: %ld in reception\n", b->th.timestamp-b->lastReceivedTS );
+        }
+
+        b->lastReceivedTS=b->th.timestamp;
+        b->transferPtr=(char *)&b->circularBuf[b->lastReceivedTS%CirSize];
+        b->remainToTransfer=sampleToByte(b->th.size, b->th.nbAnt);
+      }
+
+      if ( b->headerMode==false ) {
+        b->lastReceivedTS=b->th.timestamp+b->th.size-byteToSample(b->remainToTransfer,b->th.nbAnt);
+
+        if ( b->remainToTransfer==0) {
+          LOG_D(HW,"Completed block reception: %ld\n", b->lastReceivedTS);
+
+          // First block in UE, resync with the eNB current TS
+          if ( t->nextTimestamp == 0 )
+            t->nextTimestamp=b->lastReceivedTS-b->th.size;
+
+          b->headerMode=true;
+          b->transferPtr=(char *)&b->th;
+          b->remainToTransfer=sizeof(transferHeader);
+          b->th.magic=-1;
+        }
+      }
+    }
+  }
+
+  return nfds>0;
+}
+
+int rfsimulator_read(openair0_device *device, openair0_timestamp *ptimestamp, void **samplesVoid, int nsamps, int nbAnt) {
+  if (nbAnt != 1) {
+    LOG_E(HW, "rfsimulator: only 1 antenna tested\n");
+    exit(1);
+  }
+
+  rfsimulator_state_t *t = device->priv;
+  LOG_D(HW, "Enter rfsimulator_read, expect %d samples, will release at TS: %ld\n", nsamps, t->nextTimestamp+nsamps);
+  // deliver data from received data
+  // check if a UE is connected
+  int first_sock;
+
+  for (first_sock=0; first_sock<FD_SETSIZE; first_sock++)
+    if (t->buf[first_sock].circularBuf != NULL )
+      break;
+
+  if ( first_sock ==  FD_SETSIZE ) {
+    // no connected device (we are eNB, no UE is connected)
+    if (!flushInput(t)) {
+      for (int x=0; x < nbAnt; x++)
+        memset(samplesVoid[x],0,sampleToByte(nsamps,1));
+
+      t->nextTimestamp+=nsamps;
+      LOG_W(HW,"Generated void samples for Rx: %ld\n", t->nextTimestamp);
+      *ptimestamp = t->nextTimestamp-nsamps;
+      return nsamps;
+    }
+  } else {
+    bool have_to_wait;
+
+    do {
+      have_to_wait=false;
+
+      for ( int sock=0; sock<FD_SETSIZE; sock++)
+        if ( t->buf[sock].circularBuf &&
+             t->buf[sock].alreadyRead && //>= t->initialAhead &&
+             (t->nextTimestamp+nsamps) > t->buf[sock].lastReceivedTS ) {
+          have_to_wait=true;
+          break;
+        }
+
+      if (have_to_wait)
+        /*printf("Waiting on socket, current last ts: %ld, expected at least : %ld\n",
+          ptr->lastReceivedTS,
+          t->nextTimestamp+nsamps);
+        */
+        flushInput(t);
+    } while (have_to_wait);
+  }
+
+  // Clear the output buffer
+  for (int a=0; a<nbAnt; a++)
+    memset(samplesVoid[a],0,sampleToByte(nsamps,1));
+
+  // Add all input signal in the output buffer
+  for (int sock=0; sock<FD_SETSIZE; sock++) {
+    buffer_t *ptr=&t->buf[sock];
+
+    if ( ptr->circularBuf && ptr->alreadyRead ) {
+      for (int a=0; a<nbAnt; a++) {
+        sample_t *out=(sample_t *)samplesVoid[a];
+
+        for ( int i=0; i < nsamps; i++ )
+          out[i]+=ptr->circularBuf[((t->nextTimestamp+i)*nbAnt+a)%CirSize]<<1;
+      }
+    }
+  }
+
+  *ptimestamp = t->nextTimestamp; // return the time of the first sample
+  t->nextTimestamp+=nsamps;
+  LOG_D(HW,"Rx to upper layer: %d from %ld to %ld, energy in first antenna %d\n",
+        nsamps,
+        *ptimestamp, t->nextTimestamp,
+        signal_energy(samplesVoid[0], nsamps));
+  return nsamps;
+}
+
+
+int rfsimulator_request(openair0_device *device, void *msg, ssize_t msg_len) {
+  abort();
+  return 0;
+}
+int rfsimulator_reply(openair0_device *device, void *msg, ssize_t msg_len) {
+  abort();
+  return 0;
+}
+int rfsimulator_get_stats(openair0_device *device) {
+  return 0;
+}
+int rfsimulator_reset_stats(openair0_device *device) {
+  return 0;
+}
+void rfsimulator_end(openair0_device *device) {}
+int rfsimulator_stop(openair0_device *device) {
+  return 0;
+}
+int rfsimulator_set_freq(openair0_device *device, openair0_config_t *openair0_cfg,int exmimo_dump_config) {
+  return 0;
+}
+int rfsimulator_set_gains(openair0_device *device, openair0_config_t *openair0_cfg) {
+  return 0;
+}
+
+
+__attribute__((__visibility__("default")))
+int device_init(openair0_device *device, openair0_config_t *openair0_cfg) {
+  //set_log(HW,OAILOG_DEBUG);
+  rfsimulator_state_t *rfsimulator = (rfsimulator_state_t *)calloc(sizeof(rfsimulator_state_t),1);
+
+  if ((rfsimulator->ip=getenv("RFSIMULATOR")) == NULL ) {
+    LOG_E(HW,helpTxt);
+    exit(1);
+  }
+
+  rfsimulator->typeStamp = strncasecmp(rfsimulator->ip,"enb",3) == 0 ?
+                           MAGICeNB:
+                           MAGICUE;
+  LOG_I(HW,"rfsimulator: running as %s\n", rfsimulator-> typeStamp == MAGICeNB ? "eNB" : "UE");
+  device->trx_start_func       = rfsimulator->typeStamp == MAGICeNB ?
+                                 server_start :
+                                 start_ue;
+  device->trx_get_stats_func   = rfsimulator_get_stats;
+  device->trx_reset_stats_func = rfsimulator_reset_stats;
+  device->trx_end_func         = rfsimulator_end;
+  device->trx_stop_func        = rfsimulator_stop;
+  device->trx_set_freq_func    = rfsimulator_set_freq;
+  device->trx_set_gains_func   = rfsimulator_set_gains;
+  device->trx_write_func       = rfsimulator_write;
+  device->trx_read_func      = rfsimulator_read;
+  /* let's pretend to be a b2x0 */
+  device->type = USRP_B200_DEV;
+  device->openair0_cfg=&openair0_cfg[0];
+  device->priv = rfsimulator;
+
+  for (int i=0; i<FD_SETSIZE; i++)
+    rfsimulator->buf[i].conn_sock=-1;
+
+  AssertFatal((rfsimulator->epollfd = epoll_create1(0)) != -1,"");
+  rfsimulator->initialAhead=openair0_cfg[0].sample_rate/1000; // One sub frame
+  return 0;
+}
diff --git a/targets/RT/USER/lte-ru.c b/targets/RT/USER/lte-ru.c
index 89ca097bb5d67684225a77b197905f43d020b0a5..787e630d17658b0cb76cf8abc874e8f5dc1717e5 100644
--- a/targets/RT/USER/lte-ru.c
+++ b/targets/RT/USER/lte-ru.c
@@ -1381,12 +1381,11 @@ int setup_RU_buffers(RU_t *ru) {
     else if (frame_parms->N_RB_DL == 50)  ru->N_TA_offset = 624/2;
     else if (frame_parms->N_RB_DL == 25)  ru->N_TA_offset = 624/4;
 
-#if BASIC_SIMULATOR
-    /* this is required for the basic simulator in TDD mode
-     * TODO: find a proper cleaner solution
-     */
-    ru->N_TA_offset = 0;
-#endif
+    if(IS_SOFTMODEM_BASICSIM)
+      /* this is required for the basic simulator in TDD mode
+       * TODO: find a proper cleaner solution
+       */
+      ru->N_TA_offset = 0;
   }
 
   if (ru->openair0_cfg.mmapped_dma == 1) {
diff --git a/targets/RT/USER/lte-softmodem-common.c b/targets/RT/USER/lte-softmodem-common.c
index 0a637975368e4be03f98f53eb844e17cff13a411..242d0b76d70fabf9f1c0dda109f0d045b899781b 100644
--- a/targets/RT/USER/lte-softmodem-common.c
+++ b/targets/RT/USER/lte-softmodem-common.c
@@ -58,6 +58,8 @@ void get_common_options(void) {
   uint32_t noS1;
   uint32_t nokrnmod;
   uint32_t nonbiot;
+  uint32_t rfsim;
+  uint32_t basicsim;
   paramdef_t cmdline_params[] =CMDLINE_PARAMS_DESC ;
   paramdef_t cmdline_logparams[] =CMDLINE_LOGPARAMS_DESC ;
   checkedparam_t cmdline_log_CheckParams[] = CMDLINE_LOGPARAMS_CHECK_DESC;
@@ -90,6 +92,18 @@ void get_common_options(void) {
     set_softmodem_optmask(SOFTMODEM_NONBIOT_BIT);
   }
 
+  if (rfsim) {
+    set_softmodem_optmask(SOFTMODEM_RFSIM_BIT);
+  }
+
+  if (basicsim) {
+    set_softmodem_optmask(SOFTMODEM_BASICSIM_BIT);
+  }
+
+#if BASIC_SIMULATOR
+  set_softmodem_optmask(SOFTMODEM_BASICSIM_BIT);
+#endif
+
   if(parallel_config != NULL) set_parallel_conf(parallel_config);
 
   if(worker_config != NULL)   set_worker_conf(worker_config);
diff --git a/targets/RT/USER/lte-softmodem.c b/targets/RT/USER/lte-softmodem.c
index 9c736f8172285af4e0a0d46783d3c24cf160d2b3..15553c0af37f956c37d930389238d9bf1bc89acc 100644
--- a/targets/RT/USER/lte-softmodem.c
+++ b/targets/RT/USER/lte-softmodem.c
@@ -653,9 +653,14 @@ int main( int argc, char **argv ) {
   LOG_I(HW, "Version: %s\n", PACKAGE_VERSION);
   printf("Runtime table\n");
   fill_modeled_runtime_table(runtime_phy_rx,runtime_phy_tx);
-  pdcp_module_init( ( IS_SOFTMODEM_NOS1 && !(IS_SOFTMODEM_NOKRNMOD))? (PDCP_USE_NETLINK_BIT | LINK_ENB_PDCP_TO_IP_DRIVER_BIT) : LINK_ENB_PDCP_TO_GTPV1U_BIT);
+  uint32_t pdcp_initmask = ( IS_SOFTMODEM_NOS1 )? ( PDCP_USE_NETLINK_BIT | LINK_ENB_PDCP_TO_IP_DRIVER_BIT) : LINK_ENB_PDCP_TO_GTPV1U_BIT;
 #
 
+  if ( IS_SOFTMODEM_NOS1)
+    pdcp_initmask = pdcp_initmask | ENB_NAS_USE_TUN_BIT | SOFTMODEM_NOKRNMOD_BIT  ;
+
+  pdcp_module_init(pdcp_initmask);
+
   if (RC.nb_inst > 0)  {
     // don't create if node doesn't connect to RRC/S1/GTP
     if (create_tasks(1) < 0) {
diff --git a/targets/RT/USER/lte-softmodem.h b/targets/RT/USER/lte-softmodem.h
index 39f997a71f5a53ceab82a2ee1478a2a6d6d560ff..9b820e6e19e1f95f9f4ca199a2122af5ad149610 100644
--- a/targets/RT/USER/lte-softmodem.h
+++ b/targets/RT/USER/lte-softmodem.h
@@ -87,6 +87,7 @@
 #define CONFIG_HLP_PARALLEL_CMD  "three config for level of parallelism 'PARALLEL_SINGLE_THREAD', 'PARALLEL_RU_L1_SPLIT', or 'PARALLEL_RU_L1_TRX_SPLIT'\n"
 #define CONFIG_HLP_WORKER_CMD    "two option for worker 'WORKER_DISABLE' or 'WORKER_ENABLE'\n"
 #define CONFIG_HLP_NOS1          "Disable s1 interface\n"
+#define CONFIG_HLP_RFSIM         "Run in rf simulator mode (also known as basic simulator)\n"
 #define CONFIG_HLP_NOKRNMOD      "(noS1 only): Use tun instead of namesh module \n"
 #define CONFIG_HLP_DISABLNBIOT   "disable nb-iot, even if defined in config\n"
 
@@ -199,7 +200,9 @@
     {"numerology" ,             CONFIG_HLP_NUMEROLOGY,  PARAMFLAG_BOOL,         iptr:&NUMEROLOGY,                   defintval:0,                    TYPE_INT,       0},                     \
     {"parallel-config",         CONFIG_HLP_PARALLEL_CMD,0,                      strptr:(char **)&parallel_config,   defstrval:NULL,                 TYPE_STRING,    0},                     \
     {"worker-config",           CONFIG_HLP_WORKER_CMD,  0,                      strptr:(char **)&worker_config,     defstrval:NULL,                 TYPE_STRING,    0},                     \
-    {"noS1",                    CONFIG_HLP_NOS1,        PARAMFLAG_BOOL,         uptr:&noS1,             defintval:0,      TYPE_INT, 0},                     \
+    {"noS1",                    CONFIG_HLP_NOS1,        PARAMFLAG_BOOL,         uptr:&noS1,         defintval:0,      TYPE_INT, 0},                     \
+    {"rfsim",                   CONFIG_HLP_RFSIM,       PARAMFLAG_BOOL,         uptr:&rfsim,        defintval:0,      TYPE_INT, 0},                     \
+    {"basicsim",                CONFIG_HLP_RFSIM,       PARAMFLAG_BOOL,         uptr:&basicsim,     defintval:0,      TYPE_INT, 0},                     \
     {"nokrnmod",                CONFIG_HLP_NOKRNMOD,    PARAMFLAG_BOOL,         uptr:&nokrnmod,     defintval:0,      TYPE_INT, 0},                     \
     {"nbiot-disable",           CONFIG_HLP_DISABLNBIOT, PARAMFLAG_BOOL,         uptr:&nonbiot,      defuintval:0,                   TYPE_INT,       0},                     \
   }
@@ -238,8 +241,8 @@
 #define SOFTMODEM_NOS1_BIT            (1<<0)
 #define SOFTMODEM_NOKRNMOD_BIT        (1<<1)
 #define SOFTMODEM_NONBIOT_BIT         (1<<2)
-#define SOFTMODEM_BASICSIM_BIT        (1<<10)
-
+#define SOFTMODEM_RFSIM_BIT           (1<<10)
+#define SOFTMODEM_BASICSIM_BIT        (1<<11)
 typedef struct {
   uint64_t       optmask;
   THREAD_STRUCT  thread_struct;
@@ -260,6 +263,7 @@ typedef struct {
 #define IS_SOFTMODEM_NOS1            ( get_softmodem_optmask() & SOFTMODEM_NOS1_BIT)
 #define IS_SOFTMODEM_NOKRNMOD        ( get_softmodem_optmask() & SOFTMODEM_NOKRNMOD_BIT)
 #define IS_SOFTMODEM_NONBIOT         ( get_softmodem_optmask() & SOFTMODEM_NONBIOT_BIT)
+#define IS_SOFTMODEM_RFSIM           ( get_softmodem_optmask() & SOFTMODEM_RFSIM_BIT)
 #define IS_SOFTMODEM_BASICSIM        ( get_softmodem_optmask() & SOFTMODEM_BASICSIM_BIT)
 extern uint64_t get_softmodem_optmask(void);
 extern uint64_t set_softmodem_optmask(uint64_t bitmask);
diff --git a/targets/RT/USER/lte-ue.c b/targets/RT/USER/lte-ue.c
index f67dbeca7efd0c17557f3e0d35d53028b312d46c..bb2319774c5b8d64400538f409882f6977a231b1 100644
--- a/targets/RT/USER/lte-ue.c
+++ b/targets/RT/USER/lte-ue.c
@@ -80,12 +80,12 @@ void init_UE_threads_stub(int);
 void init_UE_single_thread_stub(int);
 void *UE_thread(void *arg);
 void init_UE(int nb_inst,int eMBMS_active, int uecap_xer_in, int timing_correction, int phy_test, int UE_scan, int UE_scan_carrier, runmode_t mode,int rxgain,int txpowermax,LTE_DL_FRAME_PARMS *fp);
-void init_UE_stub(int nb_inst,int,int,char*);
-void init_UE_stub_single_thread(int nb_inst,int,int,char*);
+void init_UE_stub(int nb_inst,int,int,char *);
+void init_UE_stub_single_thread(int nb_inst,int,int,char *);
 int init_timer_thread(void);
 extern void oai_subframe_ind(uint16_t sfn, uint16_t sf);
 extern void multicast_link_start(void (*rx_handlerP) (unsigned int, char *),
-                          unsigned char _multicast_group, char *multicast_ifname);
+                                 unsigned char _multicast_group, char *multicast_ifname);
 extern int oai_nfapi_crc_indication(nfapi_crc_indication_t *crc_ind);
 extern int oai_nfapi_crc_indication(nfapi_crc_indication_t *crc_ind);
 extern int oai_nfapi_harq_indication(nfapi_harq_indication_t *harq_ind);
@@ -169,21 +169,18 @@ struct sched_param              sched_param_UE_thread;
 
 void get_uethreads_params(void) {
   paramdef_t cmdline_threadsparams[] =CMDLINE_UETHREADSPARAMS_DESC;
-
-
   config_process_cmdline( cmdline_threadsparams,sizeof(cmdline_threadsparams)/sizeof(paramdef_t),NULL);
 }
 
 
 void phy_init_lte_ue_transport(PHY_VARS_UE *ue,int absraction_flag);
 
-PHY_VARS_UE* init_ue_vars(LTE_DL_FRAME_PARMS *frame_parms,
-			  uint8_t UE_id,
-			  uint8_t abstraction_flag)
+PHY_VARS_UE *init_ue_vars(LTE_DL_FRAME_PARMS *frame_parms,
+                          uint8_t UE_id,
+                          uint8_t abstraction_flag)
 
 {
-
-  PHY_VARS_UE* ue = (PHY_VARS_UE *)malloc(sizeof(PHY_VARS_UE));
+  PHY_VARS_UE *ue = (PHY_VARS_UE *)malloc(sizeof(PHY_VARS_UE));
   memset(ue,0,sizeof(PHY_VARS_UE));
 
   if (frame_parms!=(LTE_DL_FRAME_PARMS *)NULL) { // if we want to give initial frame parms, allocate the PHY_VARS_UE structure and put them in
@@ -195,13 +192,12 @@ PHY_VARS_UE* init_ue_vars(LTE_DL_FRAME_PARMS *frame_parms,
   ue->mac_enabled = 1;
 
   // In phy_stub_UE (MAC-to-MAC) mode these init functions don't need to get called. Is this correct?
-  if (nfapi_mode!=3)
-    {
-      // initialize all signal buffers
-      init_lte_ue_signal(ue,1,abstraction_flag);
-      // intialize transport
-      init_lte_ue_transport(ue,abstraction_flag);
-    }
+  if (nfapi_mode!=3) {
+    // initialize all signal buffers
+    init_lte_ue_signal(ue,1,abstraction_flag);
+    // intialize transport
+    init_lte_ue_transport(ue,abstraction_flag);
+  }
 
   return(ue);
 }
@@ -211,9 +207,9 @@ char uecap_xer[1024];
 
 
 
-void init_thread(int sched_runtime, int sched_deadline, int sched_fifo, cpu_set_t *cpuset, char * name) {
-
+void init_thread(int sched_runtime, int sched_deadline, int sched_fifo, cpu_set_t *cpuset, char *name) {
 #ifdef DEADLINE_SCHEDULER
+
   if (sched_runtime!=0) {
     struct sched_attr attr= {0};
     attr.size = sizeof(attr);
@@ -222,60 +218,64 @@ void init_thread(int sched_runtime, int sched_deadline, int sched_fifo, cpu_set_
     attr.sched_deadline = sched_deadline;
     attr.sched_period   = 0;
     AssertFatal(sched_setattr(0, &attr, 0) == 0,
-		"[SCHED] %s thread: sched_setattr failed %s \n", name, strerror(errno));
+                "[SCHED] %s thread: sched_setattr failed %s \n", name, strerror(errno));
     LOG_I(HW,"[SCHED][eNB] %s deadline thread %lu started on CPU %d\n",
-	  name, (unsigned long)gettid(), sched_getcpu());
+          name, (unsigned long)gettid(), sched_getcpu());
   }
+
 #else
+
   if (CPU_COUNT(cpuset) > 0)
     AssertFatal( 0 == pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), cpuset), "");
+
   struct sched_param sp;
   sp.sched_priority = sched_fifo;
   AssertFatal(pthread_setschedparam(pthread_self(),SCHED_FIFO,&sp)==0,
-	      "Can't set thread priority, Are you root?\n");
+              "Can't set thread priority, Are you root?\n");
   /* Check the actual affinity mask assigned to the thread */
   cpu_set_t *cset=CPU_ALLOC(CPU_SETSIZE);
+
   if (0 == pthread_getaffinity_np(pthread_self(), CPU_ALLOC_SIZE(CPU_SETSIZE), cset)) {
-    char txt[512]={0};
+    char txt[512]= {0};
+
     for (int j = 0; j < CPU_SETSIZE; j++)
       if (CPU_ISSET(j, cset))
-	sprintf(txt+strlen(txt), " %d ", j);
+        sprintf(txt+strlen(txt), " %d ", j);
+
     printf("CPU Affinity of thread %s is %s\n", name, txt);
   }
+
   CPU_FREE(cset);
 #endif
-
 }
 
 void init_UE(int nb_inst,int eMBMS_active, int uecap_xer_in, int timing_correction, int phy_test, int UE_scan, int UE_scan_carrier, runmode_t mode,int rxgain,int txpowermax,LTE_DL_FRAME_PARMS *fp0) {
-
   PHY_VARS_UE *UE;
   int         inst;
   int         ret;
   LTE_DL_FRAME_PARMS *fp;
-
   LOG_I(PHY,"UE : Calling Layer 2 for initialization\n");
-
   l2_init_ue(eMBMS_active,(uecap_xer_in==1)?uecap_xer:NULL,
-	     0,// cba_group_active
-	     0); // HO flag
+             0,// cba_group_active
+             0); // HO flag
+
+  if (PHY_vars_UE_g==NULL) PHY_vars_UE_g = (PHY_VARS_UE ***)calloc(1+nb_inst,sizeof(PHY_VARS_UE **));
+
+  for (inst=0; inst<nb_inst; inst++) {
+    if (PHY_vars_UE_g[inst]==NULL) PHY_vars_UE_g[inst] = (PHY_VARS_UE **)calloc(1+MAX_NUM_CCs,sizeof(PHY_VARS_UE *));
 
-  if (PHY_vars_UE_g==NULL) PHY_vars_UE_g = (PHY_VARS_UE***)calloc(1+nb_inst,sizeof(PHY_VARS_UE**));
-   
-  for (inst=0;inst<nb_inst;inst++) {
-    if (PHY_vars_UE_g[inst]==NULL) PHY_vars_UE_g[inst] = (PHY_VARS_UE**)calloc(1+MAX_NUM_CCs,sizeof(PHY_VARS_UE*));
     LOG_I(PHY,"Allocating UE context %d\n",inst);
 
     if (simL1flag == 0) PHY_vars_UE_g[inst][0] = init_ue_vars(fp0,inst,0);
     else {
       // needed for memcopy below. these are not used in the RU, but needed for UE
-       RC.ru[0]->frame_parms.nb_antennas_rx = fp0->nb_antennas_rx;
-       RC.ru[0]->frame_parms.nb_antennas_tx = fp0->nb_antennas_tx;
-       PHY_vars_UE_g[inst][0]  = init_ue_vars(&RC.ru[0]->frame_parms,inst,0);
+      RC.ru[0]->frame_parms.nb_antennas_rx = fp0->nb_antennas_rx;
+      RC.ru[0]->frame_parms.nb_antennas_tx = fp0->nb_antennas_tx;
+      PHY_vars_UE_g[inst][0]  = init_ue_vars(&RC.ru[0]->frame_parms,inst,0);
     }
+
     // turn off timing control loop in UE
     PHY_vars_UE_g[inst][0]->no_timing_correction = timing_correction;
-
     UE = PHY_vars_UE_g[inst][0];
     fp = &UE->frame_parms;
     printf("PHY_vars_UE_g[0][0] = %p\n",UE);
@@ -290,7 +290,6 @@ void init_UE(int nb_inst,int eMBMS_active, int uecap_xer_in, int timing_correcti
         UE->pusch_config_dedicated[i].betaOffset_ACK_Index = 0;
         UE->pusch_config_dedicated[i].betaOffset_RI_Index  = 0;
         UE->pusch_config_dedicated[i].betaOffset_CQI_Index = 2;
-        
         UE->scheduling_request_config[i].sr_PUCCH_ResourceIndex = 0;
         UE->scheduling_request_config[i].sr_ConfigIndex = 7+(0%3);
         UE->scheduling_request_config[i].dsr_TransMax = sr_n4;
@@ -305,69 +304,75 @@ void init_UE(int nb_inst,int eMBMS_active, int uecap_xer_in, int timing_correcti
     if (UE->mac_enabled == 1) {
       UE->pdcch_vars[0][0]->crnti = 0x1234;
       UE->pdcch_vars[1][0]->crnti = 0x1234;
-    }else {
+    } else {
       UE->pdcch_vars[0][0]->crnti = 0x1235;
       UE->pdcch_vars[1][0]->crnti = 0x1235;
     }
+
     UE->rx_total_gain_dB =  rxgain;
     UE->tx_power_max_dBm = txpowermax;
-
     UE->frame_parms.nb_antennas_tx = fp0->nb_antennas_tx;
-    UE->frame_parms.nb_antennas_rx = fp0->nb_antennas_rx; 
+    UE->frame_parms.nb_antennas_rx = fp0->nb_antennas_rx;
 
     if (fp->frame_type == TDD) {
       switch (fp->N_RB_DL) {
+        case 100:
+          if (fp->threequarter_fs) UE->N_TA_offset = (624*3)/4;
+          else                              UE->N_TA_offset = 624;
 
-      case 100:
-	if (fp->threequarter_fs) UE->N_TA_offset = (624*3)/4;
-	else                              UE->N_TA_offset = 624;
-	break;
-      case 75:
-	UE->N_TA_offset = (624*3)/4;
-	break;
-      case 50:
-	UE->N_TA_offset = 624/2;
-	break;
-      case 25:
-	UE->N_TA_offset = 624/4;
-	break;
-      case 15:
-	UE->N_TA_offset = 624/8;
-	break;
-      case 6:
-	UE->N_TA_offset = 624/16;
-	break;
-      default:
-	AssertFatal(1==0,"illegal N_RB_DL %d\n",fp->N_RB_DL);
-	break;
+          break;
+
+        case 75:
+          UE->N_TA_offset = (624*3)/4;
+          break;
+
+        case 50:
+          UE->N_TA_offset = 624/2;
+          break;
+
+        case 25:
+          UE->N_TA_offset = 624/4;
+          break;
+
+        case 15:
+          UE->N_TA_offset = 624/8;
+          break;
+
+        case 6:
+          UE->N_TA_offset = 624/16;
+          break;
+
+        default:
+          AssertFatal(1==0,"illegal N_RB_DL %d\n",fp->N_RB_DL);
+          break;
       }
-    }
-    else UE->N_TA_offset = 0;
+    } else UE->N_TA_offset = 0;
 
-#if BASIC_SIMULATOR
-    /* this is required for the basic simulator in TDD mode
-     * TODO: find a proper cleaner solution
-     */
-    UE->N_TA_offset = 0;
-#endif
+    if( IS_SOFTMODEM_BASICSIM)
+      /* this is required for the basic simulator in TDD mode
+       * TODO: find a proper cleaner solution
+       */
+      UE->N_TA_offset = 0;
 
     if (simL1flag == 1) init_ue_devices(UE);
+
     LOG_I(PHY,"Intializing UE Threads for instance %d (%p,%p)...\n",inst,PHY_vars_UE_g[inst],PHY_vars_UE_g[inst][0]);
     init_UE_threads(inst);
 
     if (simL1flag == 0) {
       ret = openair0_device_load(&(UE->rfdevice), &openair0_cfg[0]);
-      if (ret !=0){
-	exit_fun("Error loading device library");
+
+      if (ret !=0) {
+        exit_fun("Error loading device library");
       }
     }
+
     UE->rfdevice.host_type = RAU_HOST;
     //    UE->rfdevice.type      = NONE_DEV;
-
     AssertFatal(0 == pthread_create(&UE->proc.pthread_ue,
                                     &UE->proc.attr_ue,
                                     UE_thread,
-                                    (void*)UE), "");
+                                    (void *)UE), "");
   }
 
   printf("UE threads created by %ld\n", gettid());
@@ -376,31 +381,24 @@ void init_UE(int nb_inst,int eMBMS_active, int uecap_xer_in, int timing_correcti
 // Initiating all UEs within a single set of threads for PHY_STUB. Future extensions -> multiple
 // set of threads for multiple UEs.
 void init_UE_stub_single_thread(int nb_inst,int eMBMS_active, int uecap_xer_in, char *emul_iface) {
-
   int         inst;
-
   LOG_I(PHY,"UE : Calling Layer 2 for initialization, nb_inst: %d \n", nb_inst);
-
   l2_init_ue(eMBMS_active,(uecap_xer_in==1)?uecap_xer:NULL,
-	     0,// cba_group_active
-	     0); // HO flag
-
-  for (inst=0;inst<nb_inst;inst++) {
+             0,// cba_group_active
+             0); // HO flag
 
+  for (inst=0; inst<nb_inst; inst++) {
     LOG_I(PHY,"Initializing memory for UE instance %d (%p)\n",inst,PHY_vars_UE_g[inst]);
     // PHY_vars_UE_g[inst][0] = init_ue_vars(NULL,inst,0);
   }
+
   init_timer_thread();
   init_UE_single_thread_stub(nb_inst);
-
-
   printf("UE threads created \n");
-
   LOG_I(PHY,"Starting multicast link on %s\n",emul_iface);
-  if(nfapi_mode!=3)
-  multicast_link_start(ue_stub_rx_handler,0,emul_iface);
-
 
+  if(nfapi_mode!=3)
+    multicast_link_start(ue_stub_rx_handler,0,emul_iface);
 }
 
 
@@ -408,36 +406,29 @@ void init_UE_stub_single_thread(int nb_inst,int eMBMS_active, int uecap_xer_in,
 
 
 void init_UE_stub(int nb_inst,int eMBMS_active, int uecap_xer_in, char *emul_iface) {
-
   int         inst;
-
   LOG_I(PHY,"UE : Calling Layer 2 for initialization\n");
-
   l2_init_ue(eMBMS_active,(uecap_xer_in==1)?uecap_xer:NULL,
-	     0,// cba_group_active
-	     0); // HO flag
-
-  for (inst=0;inst<nb_inst;inst++) {
+             0,// cba_group_active
+             0); // HO flag
 
+  for (inst=0; inst<nb_inst; inst++) {
     LOG_I(PHY,"Initializing memory for UE instance %d (%p)\n",inst,PHY_vars_UE_g[inst]);
     PHY_vars_UE_g[inst][0] = init_ue_vars(NULL,inst,0);
   }
-  init_timer_thread();
 
-  for (inst=0;inst<nb_inst;inst++) {
+  init_timer_thread();
 
+  for (inst=0; inst<nb_inst; inst++) {
     LOG_I(PHY,"Intializing UE Threads for instance %d (%p,%p)...\n",inst,PHY_vars_UE_g[inst],PHY_vars_UE_g[inst][0]);
     init_UE_threads_stub(inst);
   }
 
   printf("UE threads created \n");
-
   LOG_I(PHY,"Starting multicast link on %s\n",emul_iface);
-  if(nfapi_mode !=3)
-     multicast_link_start(ue_stub_rx_handler,0,emul_iface);
-
-
 
+  if(nfapi_mode !=3)
+    multicast_link_start(ue_stub_rx_handler,0,emul_iface);
 }
 
 
@@ -450,11 +441,10 @@ void init_UE_stub(int nb_inst,int eMBMS_active, int uecap_xer_in, char *emul_ifa
  * \returns a pointer to an int. The storage is not on the heap and must not be freed.
  */
 
-static void *UE_thread_synch(void *arg)
-{
+static void *UE_thread_synch(void *arg) {
   static int UE_thread_synch_retval;
   int i ;
-  PHY_VARS_UE *UE = (PHY_VARS_UE*) arg;
+  PHY_VARS_UE *UE = (PHY_VARS_UE *) arg;
   int current_band = 0;
   int current_offset = 0;
   sync_mode_t sync_mode = pbch;
@@ -463,30 +453,28 @@ static void *UE_thread_synch(void *arg)
   int found;
   int freq_offset=0;
   char threadname[128];
-
   printf("UE_thread_sync in with PHY_vars_UE %p\n",arg);
-
   cpu_set_t cpuset;
   CPU_ZERO(&cpuset);
+
   if ( threads.iq != -1 )
     CPU_SET(threads.iq, &cpuset);
+
   // this thread priority must be lower that the main acquisition thread
   sprintf(threadname, "sync UE %d\n", UE->Mod_id);
   init_thread(100000, 500000, FIFO_PRIORITY-1, &cpuset, threadname);
-
   printf("starting UE synch thread (IC %d)\n",UE->proc.instance_cnt_synch);
   ind = 0;
   found = 0;
 
-
   if (UE->UE_scan == 0) {
     do  {
       current_band = eutra_bands[ind].band;
       printf( "Scanning band %d, dl_min %"PRIu32", ul_min %"PRIu32"\n", current_band, eutra_bands[ind].dl_min,eutra_bands[ind].ul_min);
 
       if ((eutra_bands[ind].dl_min <= UE->frame_parms.dl_CarrierFreq) && (eutra_bands[ind].dl_max >= UE->frame_parms.dl_CarrierFreq)) {
-	for (i=0; i<4; i++)
-	  uplink_frequency_offset[CC_id][i] = eutra_bands[ind].ul_min - eutra_bands[ind].dl_min;
+        for (i=0; i<4; i++)
+          uplink_frequency_offset[CC_id][i] = eutra_bands[ind].ul_min - eutra_bands[ind].dl_min;
 
         found = 1;
         break;
@@ -501,241 +489,240 @@ static void *UE_thread_synch(void *arg)
       return &UE_thread_synch_retval;
     }
 
+    LOG_I( PHY, "[SCHED][UE] Check absolute frequency DL %"PRIu32", UL %"PRIu32" (oai_exit %d, rx_num_channels %d)\n", UE->frame_parms.dl_CarrierFreq, UE->frame_parms.ul_CarrierFreq,oai_exit,
+           openair0_cfg[0].rx_num_channels);
 
-    LOG_I( PHY, "[SCHED][UE] Check absolute frequency DL %"PRIu32", UL %"PRIu32" (oai_exit %d, rx_num_channels %d)\n", UE->frame_parms.dl_CarrierFreq, UE->frame_parms.ul_CarrierFreq,oai_exit, openair0_cfg[0].rx_num_channels);
-
-    for (i=0;i<openair0_cfg[UE->rf_map.card].rx_num_channels;i++) {
+    for (i=0; i<openair0_cfg[UE->rf_map.card].rx_num_channels; i++) {
       openair0_cfg[UE->rf_map.card].rx_freq[UE->rf_map.chain+i] = UE->frame_parms.dl_CarrierFreq;
       openair0_cfg[UE->rf_map.card].tx_freq[UE->rf_map.chain+i] = UE->frame_parms.ul_CarrierFreq;
       openair0_cfg[UE->rf_map.card].autocal[UE->rf_map.chain+i] = 1;
+
       if (uplink_frequency_offset[CC_id][i] != 0) //
-	openair0_cfg[UE->rf_map.card].duplex_mode = duplex_mode_FDD;
+        openair0_cfg[UE->rf_map.card].duplex_mode = duplex_mode_FDD;
       else //FDD
-	openair0_cfg[UE->rf_map.card].duplex_mode = duplex_mode_TDD;
+        openair0_cfg[UE->rf_map.card].duplex_mode = duplex_mode_TDD;
     }
 
     sync_mode = pbch;
-
   } else if  (UE->UE_scan == 1) {
     current_band=0;
 
     for (i=0; i<openair0_cfg[UE->rf_map.card].rx_num_channels; i++) {
       downlink_frequency[UE->rf_map.card][UE->rf_map.chain+i] = bands_to_scan.band_info[CC_id].dl_min;
       uplink_frequency_offset[UE->rf_map.card][UE->rf_map.chain+i] =
-	bands_to_scan.band_info[CC_id].ul_min-bands_to_scan.band_info[CC_id].dl_min;
+        bands_to_scan.band_info[CC_id].ul_min-bands_to_scan.band_info[CC_id].dl_min;
       openair0_cfg[UE->rf_map.card].rx_freq[UE->rf_map.chain+i] = downlink_frequency[CC_id][i];
       openair0_cfg[UE->rf_map.card].tx_freq[UE->rf_map.chain+i] =
-	downlink_frequency[CC_id][i]+uplink_frequency_offset[CC_id][i];
+        downlink_frequency[CC_id][i]+uplink_frequency_offset[CC_id][i];
       openair0_cfg[UE->rf_map.card].rx_gain[UE->rf_map.chain+i] = UE->rx_total_gain_dB;
     }
   }
 
-/*
-  while (sync_var<0)
-    pthread_cond_wait(&sync_cond, &sync_mutex);
-  pthread_mutex_unlock(&sync_mutex);
-*/
+  /*
+    while (sync_var<0)
+      pthread_cond_wait(&sync_cond, &sync_mutex);
+    pthread_mutex_unlock(&sync_mutex);
+  */
   wait_sync("UE_thread_sync");
-
   printf("Started device, unlocked sync_mutex (UE_sync_thread)\n");
 
   while (oai_exit==0) {
     AssertFatal ( 0== pthread_mutex_lock(&UE->proc.mutex_synch), "");
+
     while (UE->proc.instance_cnt_synch < 0)
       // the thread waits here most of the time
       pthread_cond_wait( &UE->proc.cond_synch, &UE->proc.mutex_synch );
+
     AssertFatal ( 0== pthread_mutex_unlock(&UE->proc.mutex_synch), "");
 
     switch (sync_mode) {
-    case pss:
-      LOG_I(PHY,"[SCHED][UE] Scanning band %d (%d), freq %u\n",bands_to_scan.band_info[current_band].band, current_band,bands_to_scan.band_info[current_band].dl_min+current_offset);
-      lte_sync_timefreq(UE,current_band,bands_to_scan.band_info[current_band].dl_min+current_offset);
-      current_offset += 20000000; // increase by 20 MHz
-
-      if (current_offset > bands_to_scan.band_info[current_band].dl_max-bands_to_scan.band_info[current_band].dl_min) {
-	current_band++;
-	current_offset=0;
-      }
+      case pss:
+        LOG_I(PHY,"[SCHED][UE] Scanning band %d (%d), freq %u\n",bands_to_scan.band_info[current_band].band, current_band,bands_to_scan.band_info[current_band].dl_min+current_offset);
+        lte_sync_timefreq(UE,current_band,bands_to_scan.band_info[current_band].dl_min+current_offset);
+        current_offset += 20000000; // increase by 20 MHz
+
+        if (current_offset > bands_to_scan.band_info[current_band].dl_max-bands_to_scan.band_info[current_band].dl_min) {
+          current_band++;
+          current_offset=0;
+        }
 
-      if (current_band==bands_to_scan.nbands) {
-	current_band=0;
-	oai_exit=1;
-      }
+        if (current_band==bands_to_scan.nbands) {
+          current_band=0;
+          oai_exit=1;
+        }
 
-      for (i=0; i<openair0_cfg[UE->rf_map.card].rx_num_channels; i++) {
-	downlink_frequency[UE->rf_map.card][UE->rf_map.chain+i] = bands_to_scan.band_info[current_band].dl_min+current_offset;
-	uplink_frequency_offset[UE->rf_map.card][UE->rf_map.chain+i] = bands_to_scan.band_info[current_band].ul_min-bands_to_scan.band_info[0].dl_min + current_offset;
+        for (i=0; i<openair0_cfg[UE->rf_map.card].rx_num_channels; i++) {
+          downlink_frequency[UE->rf_map.card][UE->rf_map.chain+i] = bands_to_scan.band_info[current_band].dl_min+current_offset;
+          uplink_frequency_offset[UE->rf_map.card][UE->rf_map.chain+i] = bands_to_scan.band_info[current_band].ul_min-bands_to_scan.band_info[0].dl_min + current_offset;
+          openair0_cfg[UE->rf_map.card].rx_freq[UE->rf_map.chain+i] = downlink_frequency[CC_id][i];
+          openair0_cfg[UE->rf_map.card].tx_freq[UE->rf_map.chain+i] = downlink_frequency[CC_id][i]+uplink_frequency_offset[CC_id][i];
+          openair0_cfg[UE->rf_map.card].rx_gain[UE->rf_map.chain+i] = UE->rx_total_gain_dB;
 
-	openair0_cfg[UE->rf_map.card].rx_freq[UE->rf_map.chain+i] = downlink_frequency[CC_id][i];
-	openair0_cfg[UE->rf_map.card].tx_freq[UE->rf_map.chain+i] = downlink_frequency[CC_id][i]+uplink_frequency_offset[CC_id][i];
-	openair0_cfg[UE->rf_map.card].rx_gain[UE->rf_map.chain+i] = UE->rx_total_gain_dB;
-	if (UE->UE_scan_carrier) {
-	  openair0_cfg[UE->rf_map.card].autocal[UE->rf_map.chain+i] = 1;
-	}
-      }
+          if (UE->UE_scan_carrier) {
+            openair0_cfg[UE->rf_map.card].autocal[UE->rf_map.chain+i] = 1;
+          }
+        }
 
-      break;
+        break;
 
-    case pbch:
+      case pbch:
+        LOG_I(PHY, "[UE thread Synch] Running Initial Synch (mode %d)\n",UE->mode);
+
+        if (initial_sync( UE, UE->mode ) == 0) {
+          LOG_I( HW, "Got synch: hw_slot_offset %d, carrier off %d Hz, rxgain %d (DL %u, UL %u), UE_scan_carrier %d\n",
+                 (UE->rx_offset<<1) / UE->frame_parms.samples_per_tti,
+                 freq_offset,
+                 UE->rx_total_gain_dB,
+                 downlink_frequency[0][0]+freq_offset,
+                 downlink_frequency[0][0]+uplink_frequency_offset[0][0]+freq_offset,
+                 UE->UE_scan_carrier );
+
+          // rerun with new cell parameters and frequency-offset
+          for (i=0; i<openair0_cfg[UE->rf_map.card].rx_num_channels; i++) {
+            openair0_cfg[UE->rf_map.card].rx_gain[UE->rf_map.chain+i] = UE->rx_total_gain_dB;//-USRP_GAIN_OFFSET;
+
+            if (UE->UE_scan_carrier == 1) {
+              if (freq_offset >= 0)
+                openair0_cfg[UE->rf_map.card].rx_freq[UE->rf_map.chain+i] += abs(UE->common_vars.freq_offset);
+              else
+                openair0_cfg[UE->rf_map.card].rx_freq[UE->rf_map.chain+i] -= abs(UE->common_vars.freq_offset);
+
+              openair0_cfg[UE->rf_map.card].tx_freq[UE->rf_map.chain+i] =
+                openair0_cfg[UE->rf_map.card].rx_freq[UE->rf_map.chain+i]+uplink_frequency_offset[CC_id][i];
+              downlink_frequency[CC_id][i] = openair0_cfg[CC_id].rx_freq[i];
+              freq_offset=0;
+            }
+          }
 
-#if DISABLE_LOG_X
-      printf("[UE thread Synch] Running Initial Synch (mode %d)\n",UE->mode);
-#else
-      LOG_I(PHY, "[UE thread Synch] Running Initial Synch (mode %d)\n",UE->mode);
-#endif
-      if (initial_sync( UE, UE->mode ) == 0) {
-
-	LOG_I( HW, "Got synch: hw_slot_offset %d, carrier off %d Hz, rxgain %d (DL %u, UL %u), UE_scan_carrier %d\n",
-	       (UE->rx_offset<<1) / UE->frame_parms.samples_per_tti,
-	       freq_offset,
-	       UE->rx_total_gain_dB,
-	       downlink_frequency[0][0]+freq_offset,
-	       downlink_frequency[0][0]+uplink_frequency_offset[0][0]+freq_offset,
-	       UE->UE_scan_carrier );
-
-
-	// rerun with new cell parameters and frequency-offset
-	for (i=0; i<openair0_cfg[UE->rf_map.card].rx_num_channels; i++) {
-	  openair0_cfg[UE->rf_map.card].rx_gain[UE->rf_map.chain+i] = UE->rx_total_gain_dB;//-USRP_GAIN_OFFSET;
-	  if (UE->UE_scan_carrier == 1) {
-	    if (freq_offset >= 0)
-	      openair0_cfg[UE->rf_map.card].rx_freq[UE->rf_map.chain+i] += abs(UE->common_vars.freq_offset);
-	    else
-	      openair0_cfg[UE->rf_map.card].rx_freq[UE->rf_map.chain+i] -= abs(UE->common_vars.freq_offset);
-	    openair0_cfg[UE->rf_map.card].tx_freq[UE->rf_map.chain+i] =
-	      openair0_cfg[UE->rf_map.card].rx_freq[UE->rf_map.chain+i]+uplink_frequency_offset[CC_id][i];
-	    downlink_frequency[CC_id][i] = openair0_cfg[CC_id].rx_freq[i];
-	    freq_offset=0;
-	  }
-	}
-
-	// reconfigure for potentially different bandwidth
-	switch(UE->frame_parms.N_RB_DL) {
-	case 6:
-	  openair0_cfg[UE->rf_map.card].sample_rate =1.92e6;
-	  openair0_cfg[UE->rf_map.card].rx_bw          =.96e6;
-	  openair0_cfg[UE->rf_map.card].tx_bw          =.96e6;
-	  //            openair0_cfg[0].rx_gain[0] -= 12;
-	  break;
-	case 25:
-	  openair0_cfg[UE->rf_map.card].sample_rate =7.68e6;
-	  openair0_cfg[UE->rf_map.card].rx_bw          =2.5e6;
-	  openair0_cfg[UE->rf_map.card].tx_bw          =2.5e6;
-	  //            openair0_cfg[0].rx_gain[0] -= 6;
-	  break;
-	case 50:
-	  openair0_cfg[UE->rf_map.card].sample_rate =15.36e6;
-	  openair0_cfg[UE->rf_map.card].rx_bw          =5.0e6;
-	  openair0_cfg[UE->rf_map.card].tx_bw          =5.0e6;
-	  //            openair0_cfg[0].rx_gain[0] -= 3;
-	  break;
-	case 100:
-	  openair0_cfg[UE->rf_map.card].sample_rate=30.72e6;
-	  openair0_cfg[UE->rf_map.card].rx_bw=10.0e6;
-	  openair0_cfg[UE->rf_map.card].tx_bw=10.0e6;
-	  //            openair0_cfg[0].rx_gain[0] -= 0;
-	  break;
-	}
-
-	UE->rfdevice.trx_set_freq_func(&UE->rfdevice,&openair0_cfg[0],0);
-	//UE->rfdevice.trx_set_gains_func(&openair0,&openair0_cfg[0]);
-	//UE->rfdevice.trx_stop_func(&UE->rfdevice);
-	sleep(1);
-	init_frame_parms(&UE->frame_parms,1);
-	/*if (UE->rfdevice.trx_start_func(&UE->rfdevice) != 0 ) {
-	  LOG_E(HW,"Could not start the device\n");
-	  oai_exit=1;
-	  }*/
-
-	if (UE->UE_scan_carrier == 1) {
-
-	  UE->UE_scan_carrier = 0;
-	} else {
-	  AssertFatal ( 0== pthread_mutex_lock(&UE->proc.mutex_synch), "");
-	  UE->is_synchronized = 1;
-	  AssertFatal ( 0== pthread_mutex_unlock(&UE->proc.mutex_synch), "");
-
-	  if( UE->mode == rx_dump_frame ) {
-	    FILE *fd;
-	    if ((UE->proc.proc_rxtx[0].frame_rx&1) == 0) {  // this guarantees SIB1 is present
-	      if ((fd = fopen("rxsig_frame0.dat","w")) != NULL) {
-		fwrite((void*)&UE->common_vars.rxdata[0][0],
-		       sizeof(int32_t),
-		       10*UE->frame_parms.samples_per_tti,
-		       fd);
-		LOG_I(PHY,"Dummping Frame ... bye bye \n");
-		fclose(fd);
-		exit(0);
-	      } else {
-		LOG_E(PHY,"Cannot open file for writing\n");
-		exit(0);
-	      }
-	    } else {
-	      AssertFatal ( 0== pthread_mutex_lock(&UE->proc.mutex_synch), "");
-	      UE->is_synchronized = 0;
-	      AssertFatal ( 0== pthread_mutex_unlock(&UE->proc.mutex_synch), "");
-
-	    }
-	  }
-	}
-      } else {
-	// initial sync failed
-	// calculate new offset and try again
-	if (UE->UE_scan_carrier == 1) {
-	  if (freq_offset >= 0)
-	    freq_offset += 100;
-	  freq_offset *= -1;
-
-	  if (abs(freq_offset) > 7500) {
-	    LOG_I( PHY, "[initial_sync] No cell synchronization found, abandoning\n" );
-	    FILE *fd;
-	    if ((fd = fopen("rxsig_frame0.dat","w"))!=NULL) {
-	      fwrite((void*)&UE->common_vars.rxdata[0][0],
-		     sizeof(int32_t),
-		     10*UE->frame_parms.samples_per_tti,
-		     fd);
-	      LOG_I(PHY,"Dummping Frame ... bye bye \n");
-	      fclose(fd);
-	      exit(0);
-	    }
-	    AssertFatal(1==0,"No cell synchronization found, abandoning");
-	    return &UE_thread_synch_retval; // not reached
-	  }
-	}
-#if DISABLE_LOG_X
-	printf("[initial_sync] trying carrier off %d Hz, rxgain %d (DL %u, UL %u)\n",
-	       freq_offset,
-	       UE->rx_total_gain_dB,
-	       downlink_frequency[0][0]+freq_offset,
-	       downlink_frequency[0][0]+uplink_frequency_offset[0][0]+freq_offset );
-#else
-	LOG_I(PHY, "[initial_sync] trying carrier off %d Hz, rxgain %d (DL %u, UL %u)\n",
-	      freq_offset,
-	      UE->rx_total_gain_dB,
-	      downlink_frequency[0][0]+freq_offset,
-	      downlink_frequency[0][0]+uplink_frequency_offset[0][0]+freq_offset );
-#endif
+          // reconfigure for potentially different bandwidth
+          switch(UE->frame_parms.N_RB_DL) {
+            case 6:
+              openair0_cfg[UE->rf_map.card].sample_rate =1.92e6;
+              openair0_cfg[UE->rf_map.card].rx_bw          =.96e6;
+              openair0_cfg[UE->rf_map.card].tx_bw          =.96e6;
+              //            openair0_cfg[0].rx_gain[0] -= 12;
+              break;
+
+            case 25:
+              openair0_cfg[UE->rf_map.card].sample_rate =7.68e6;
+              openair0_cfg[UE->rf_map.card].rx_bw          =2.5e6;
+              openair0_cfg[UE->rf_map.card].tx_bw          =2.5e6;
+              //            openair0_cfg[0].rx_gain[0] -= 6;
+              break;
+
+            case 50:
+              openair0_cfg[UE->rf_map.card].sample_rate =15.36e6;
+              openair0_cfg[UE->rf_map.card].rx_bw          =5.0e6;
+              openair0_cfg[UE->rf_map.card].tx_bw          =5.0e6;
+              //            openair0_cfg[0].rx_gain[0] -= 3;
+              break;
+
+            case 100:
+              openair0_cfg[UE->rf_map.card].sample_rate=30.72e6;
+              openair0_cfg[UE->rf_map.card].rx_bw=10.0e6;
+              openair0_cfg[UE->rf_map.card].tx_bw=10.0e6;
+              //            openair0_cfg[0].rx_gain[0] -= 0;
+              break;
+          }
 
-	for (i=0; i<openair0_cfg[UE->rf_map.card].rx_num_channels; i++) {
-	  openair0_cfg[UE->rf_map.card].rx_freq[UE->rf_map.chain+i] = downlink_frequency[CC_id][i]+freq_offset;
-	  openair0_cfg[UE->rf_map.card].tx_freq[UE->rf_map.chain+i] = downlink_frequency[CC_id][i]+uplink_frequency_offset[CC_id][i]+freq_offset;
-	  openair0_cfg[UE->rf_map.card].rx_gain[UE->rf_map.chain+i] = UE->rx_total_gain_dB;//-USRP_GAIN_OFFSET;
-	  if (UE->UE_scan_carrier==1)
-	    openair0_cfg[UE->rf_map.card].autocal[UE->rf_map.chain+i] = 1;
-	}
-	UE->rfdevice.trx_set_freq_func(&UE->rfdevice,&openair0_cfg[0],0);
-      }// initial_sync=0
-      break;
-    case si:
-    default:
-      break;
+          UE->rfdevice.trx_set_freq_func(&UE->rfdevice,&openair0_cfg[0],0);
+          //UE->rfdevice.trx_set_gains_func(&openair0,&openair0_cfg[0]);
+          //UE->rfdevice.trx_stop_func(&UE->rfdevice);
+          sleep(1);
+          init_frame_parms(&UE->frame_parms,1);
+
+          /*if (UE->rfdevice.trx_start_func(&UE->rfdevice) != 0 ) {
+            LOG_E(HW,"Could not start the device\n");
+            oai_exit=1;
+            }*/
+
+          if (UE->UE_scan_carrier == 1) {
+            UE->UE_scan_carrier = 0;
+          } else {
+            AssertFatal ( 0== pthread_mutex_lock(&UE->proc.mutex_synch), "");
+            UE->is_synchronized = 1;
+            AssertFatal ( 0== pthread_mutex_unlock(&UE->proc.mutex_synch), "");
+
+            if( UE->mode == rx_dump_frame ) {
+              FILE *fd;
+
+              if ((UE->proc.proc_rxtx[0].frame_rx&1) == 0) {  // this guarantees SIB1 is present
+                if ((fd = fopen("rxsig_frame0.dat","w")) != NULL) {
+                  fwrite((void *)&UE->common_vars.rxdata[0][0],
+                         sizeof(int32_t),
+                         10*UE->frame_parms.samples_per_tti,
+                         fd);
+                  LOG_I(PHY,"Dummping Frame ... bye bye \n");
+                  fclose(fd);
+                  exit(0);
+                } else {
+                  LOG_E(PHY,"Cannot open file for writing\n");
+                  exit(0);
+                }
+              } else {
+                AssertFatal ( 0== pthread_mutex_lock(&UE->proc.mutex_synch), "");
+                UE->is_synchronized = 0;
+                AssertFatal ( 0== pthread_mutex_unlock(&UE->proc.mutex_synch), "");
+              }
+            }
+          }
+        } else {
+          // initial sync failed
+          // calculate new offset and try again
+          if (UE->UE_scan_carrier == 1) {
+            if (freq_offset >= 0)
+              freq_offset += 100;
+
+            freq_offset *= -1;
+
+            if (abs(freq_offset) > 7500) {
+              LOG_I( PHY, "[initial_sync] No cell synchronization found, abandoning\n" );
+              FILE *fd;
+
+              if ((fd = fopen("rxsig_frame0.dat","w"))!=NULL) {
+                fwrite((void *)&UE->common_vars.rxdata[0][0],
+                       sizeof(int32_t),
+                       10*UE->frame_parms.samples_per_tti,
+                       fd);
+                LOG_I(PHY,"Dummping Frame ... bye bye \n");
+                fclose(fd);
+                exit(0);
+              }
+
+              AssertFatal(1==0,"No cell synchronization found, abandoning");
+              return &UE_thread_synch_retval; // not reached
+            }
+          }
+
+          LOG_I(PHY, "[initial_sync] trying carrier off %d Hz, rxgain %d (DL %u, UL %u)\n",
+                freq_offset,
+                UE->rx_total_gain_dB,
+                downlink_frequency[0][0]+freq_offset,
+                downlink_frequency[0][0]+uplink_frequency_offset[0][0]+freq_offset );
+
+          for (i=0; i<openair0_cfg[UE->rf_map.card].rx_num_channels; i++) {
+            openair0_cfg[UE->rf_map.card].rx_freq[UE->rf_map.chain+i] = downlink_frequency[CC_id][i]+freq_offset;
+            openair0_cfg[UE->rf_map.card].tx_freq[UE->rf_map.chain+i] = downlink_frequency[CC_id][i]+uplink_frequency_offset[CC_id][i]+freq_offset;
+            openair0_cfg[UE->rf_map.card].rx_gain[UE->rf_map.chain+i] = UE->rx_total_gain_dB;//-USRP_GAIN_OFFSET;
+
+            if (UE->UE_scan_carrier==1)
+              openair0_cfg[UE->rf_map.card].autocal[UE->rf_map.chain+i] = 1;
+          }
+
+          UE->rfdevice.trx_set_freq_func(&UE->rfdevice,&openair0_cfg[0],0);
+        }// initial_sync=0
+
+        break;
+
+      case si:
+      default:
+        break;
     }
 
     AssertFatal ( 0== pthread_mutex_lock(&UE->proc.mutex_synch), "");
     // indicate readiness
     UE->proc.instance_cnt_synch--;
     AssertFatal ( 0== pthread_mutex_unlock(&UE->proc.mutex_synch), "");
-
     VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME( VCD_SIGNAL_DUMPER_FUNCTIONS_UE_THREAD_SYNCH, 0 );
   }  // while !oai_exit
 
@@ -749,15 +736,18 @@ static void *UE_thread_synch(void *arg)
  * \param arg is a pointer to a \ref PHY_VARS_UE structure.
  * \returns a pointer to an int. The storage is not on the heap and must not be freed.
  */
-const char * get_connectionloss_errstr(int errcode) {
-        switch (errcode) {
-        case CONNECTION_LOST:
-          return "RRC Connection lost, returning to PRACH";
-        case PHY_RESYNCH:
-           return "RRC Connection lost, trying to resynch";
-        case RESYNCH:
-           return "return to PRACH and perform a contention-free access";
-        };
+const char *get_connectionloss_errstr(int errcode) {
+  switch (errcode) {
+    case CONNECTION_LOST:
+      return "RRC Connection lost, returning to PRACH";
+
+    case PHY_RESYNCH:
+      return "RRC Connection lost, trying to resynch";
+
+    case RESYNCH:
+      return "return to PRACH and perform a contention-free access";
+  };
+
   return "UNKNOWN RETURN CODE";
 }
 
@@ -766,9 +756,7 @@ static void *UE_thread_rxn_txnp4(void *arg) {
   struct rx_tx_thread_data *rtd = arg;
   UE_rxtx_proc_t *proc = rtd->proc;
   PHY_VARS_UE    *UE   = rtd->UE;
-
   proc->subframe_rx=proc->sub_frame_start;
-
   char threadname[256];
   sprintf(threadname,"UE_%d_proc_%d", UE->Mod_id, proc->sub_frame_start);
   cpu_set_t cpuset;
@@ -776,55 +764,56 @@ static void *UE_thread_rxn_txnp4(void *arg) {
 
   if ( (proc->sub_frame_start+1)%RX_NB_TH == 0 && threads.one != -1 )
     CPU_SET(threads.one, &cpuset);
+
   if ( (proc->sub_frame_start+1)%RX_NB_TH == 1 && threads.two != -1 )
     CPU_SET(threads.two, &cpuset);
+
   if ( (proc->sub_frame_start+1)%RX_NB_TH == 2 && threads.three != -1 )
     CPU_SET(threads.three, &cpuset);
+
   //CPU_SET(threads.three, &cpuset);
-  init_thread(900000,1000000 , FIFO_PRIORITY-1, &cpuset,
-	      threadname);
+  init_thread(900000,1000000, FIFO_PRIORITY-1, &cpuset,
+              threadname);
 
   while (!oai_exit) {
     if (pthread_mutex_lock(&proc->mutex_rxtx) != 0) {
       LOG_E( PHY, "[SCHED][UE] error locking mutex for UE RXTX\n" );
       exit_fun("nothing to add");
     }
+
     while (proc->instance_cnt_rxtx < 0) {
       // most of the time, the thread is waiting here
       pthread_cond_wait( &proc->cond_rxtx, &proc->mutex_rxtx );
     }
-    if (pthread_mutex_unlock(&proc->mutex_rxtx) != 0) {
-      LOG_E( PHY, "[SCHED][UE] error unlocking mutex for UE RXn_TXnp4\n" );
-      exit_fun("nothing to add");
-    }
 
+    //printf("Processing sub frqme %d in %s\n", proc->subframe_rx, threadname);
     initRefTimes(t2);
     initRefTimes(t3);
     pickTime(current);
     updateTimes(proc->gotIQs, &t2, 10000, "Delay to wake up UE_Thread_Rx (case 2)");
-
     // Process Rx data for one sub-frame
     lte_subframe_t sf_type = subframe_select( &UE->frame_parms, proc->subframe_rx);
-    if ((sf_type == SF_DL) ||
-	(UE->frame_parms.frame_type == FDD) ||
-	(sf_type == SF_S)) {
 
+    if ((sf_type == SF_DL) ||
+        (UE->frame_parms.frame_type == FDD) ||
+        (sf_type == SF_S)) {
       if (UE->frame_parms.frame_type == TDD) {
-	LOG_D(PHY, "%s,TDD%d,%s: calling UE_RX\n",
-	      threadname,
-	      UE->frame_parms.tdd_config,
-	      (sf_type==SF_DL? "SF_DL" :
-	       (sf_type==SF_UL? "SF_UL" :
-		(sf_type==SF_S ? "SF_S"  : "UNKNOWN_SF_TYPE"))));
+        LOG_D(PHY, "%s,TDD%d,%s: calling UE_RX\n",
+              threadname,
+              UE->frame_parms.tdd_config,
+              (sf_type==SF_DL? "SF_DL" :
+               (sf_type==SF_UL? "SF_UL" :
+                (sf_type==SF_S ? "SF_S"  : "UNKNOWN_SF_TYPE"))));
       } else {
-	LOG_D(PHY, "%s,%s,%s: calling UE_RX\n",
-	      threadname,
-	      (UE->frame_parms.frame_type==FDD? "FDD":
-	       (UE->frame_parms.frame_type==TDD? "TDD":"UNKNOWN_DUPLEX_MODE")),
-	      (sf_type==SF_DL? "SF_DL" :
-	       (sf_type==SF_UL? "SF_UL" :
-		(sf_type==SF_S ? "SF_S"  : "UNKNOWN_SF_TYPE"))));
+        LOG_D(PHY, "%s,%s,%s: calling UE_RX\n",
+              threadname,
+              (UE->frame_parms.frame_type==FDD? "FDD":
+               (UE->frame_parms.frame_type==TDD? "TDD":"UNKNOWN_DUPLEX_MODE")),
+              (sf_type==SF_DL? "SF_DL" :
+               (sf_type==SF_UL? "SF_UL" :
+                (sf_type==SF_S ? "SF_S"  : "UNKNOWN_SF_TYPE"))));
       }
+
 #ifdef UE_SLOT_PARALLELISATION
       phy_procedures_slot_parallelization_UE_RX( UE, proc, 0, 0, 1, UE->mode, no_relay, NULL );
 #else
@@ -835,49 +824,46 @@ static void *UE_thread_rxn_txnp4(void *arg) {
 #if UE_TIMING_TRACE
     start_meas(&UE->generic_stat);
 #endif
-    if (UE->mac_enabled==1) {
 
+    if (UE->mac_enabled==1) {
       int ret = ue_scheduler(UE->Mod_id,
-			 proc->frame_rx,
-			 proc->subframe_rx,
-			 proc->frame_tx,
-			 proc->subframe_tx,
-			 subframe_select(&UE->frame_parms,proc->subframe_tx),
-			 0,
-			 0/*FIXME CC_id*/);
+                             proc->frame_rx,
+                             proc->subframe_rx,
+                             proc->frame_tx,
+                             proc->subframe_tx,
+                             subframe_select(&UE->frame_parms,proc->subframe_tx),
+                             0,
+                             0/*FIXME CC_id*/);
+
       if ( ret != CONNECTION_OK) {
-	LOG_E( PHY, "[UE %"PRIu8"] Frame %"PRIu32", subframe %u %s\n",
-	       UE->Mod_id, proc->frame_rx, proc->subframe_tx,get_connectionloss_errstr(ret) );
+        LOG_E( PHY, "[UE %"PRIu8"] Frame %"PRIu32", subframe %u %s\n",
+               UE->Mod_id, proc->frame_rx, proc->subframe_tx,get_connectionloss_errstr(ret) );
       }
     }
+
 #if UE_TIMING_TRACE
     stop_meas(&UE->generic_stat);
 #endif
 
-
     // Prepare the future Tx data
 
     if ((subframe_select( &UE->frame_parms, proc->subframe_tx) == SF_UL) ||
-	(UE->frame_parms.frame_type == FDD) )
+        (UE->frame_parms.frame_type == FDD) )
       if (UE->mode != loop_through_memory)
-	phy_procedures_UE_TX(UE,proc,0,0,UE->mode);
-
-
+        phy_procedures_UE_TX(UE,proc,0,0,UE->mode);
 
     if ((subframe_select( &UE->frame_parms, proc->subframe_tx) == SF_S) &&
-	(UE->frame_parms.frame_type == TDD))
+        (UE->frame_parms.frame_type == TDD))
       if (UE->mode != loop_through_memory)
-	phy_procedures_UE_S_TX(UE,0,0);
+        phy_procedures_UE_S_TX(UE,0,0);
+
     updateTimes(current, &t3, 10000, "Delay to process sub-frame (case 3)");
+    proc->instance_cnt_rxtx--;
 
-    if (pthread_mutex_lock(&proc->mutex_rxtx) != 0) {
-      LOG_E( PHY, "[SCHED][UE] error locking mutex for UE RXTX\n" );
-      exit_fun("noting to add");
+    if ( IS_SOFTMODEM_BASICSIM || IS_SOFTMODEM_RFSIM ) {
+      if (pthread_cond_signal(&proc->cond_rxtx) != 0) abort();
     }
-    proc->instance_cnt_rxtx--;
-#if BASIC_SIMULATOR
-    if (pthread_cond_signal(&proc->cond_rxtx) != 0) abort();
-#endif
+
     if (pthread_mutex_unlock(&proc->mutex_rxtx) != 0) {
       LOG_E( PHY, "[SCHED][UE] error unlocking mutex for UE RXTX\n" );
       exit_fun("noting to add");
@@ -894,61 +880,57 @@ static void *UE_thread_rxn_txnp4(void *arg) {
 unsigned int emulator_absSF;
 
 void ue_stub_rx_handler(unsigned int num_bytes, char *rx_buffer) {
-
   PHY_VARS_UE *UE;
   UE = PHY_vars_UE_g[0][0];
+  UE_tport_t *pdu = (UE_tport_t *)rx_buffer;
+  SLSCH_t *slsch = (SLSCH_t *)&pdu->slsch;
+  SLDCH_t *sldch = (SLDCH_t *)&pdu->sldch;
+
+  switch (((UE_tport_header_t *)rx_buffer)->packet_type) {
+    case TTI_SYNC:
+      emulator_absSF = ((UE_tport_header_t *)rx_buffer)->absSF;
+      wakeup_thread(&UE->timer_mutex,&UE->timer_cond,&UE->instance_cnt_timer,"timer_thread");
+      break;
 
-  UE_tport_t *pdu = (UE_tport_t*)rx_buffer;
-  SLSCH_t *slsch = (SLSCH_t*)&pdu->slsch;
-  SLDCH_t *sldch = (SLDCH_t*)&pdu->sldch;
-
-  switch (((UE_tport_header_t*)rx_buffer)->packet_type) {
-  case TTI_SYNC:
-    emulator_absSF = ((UE_tport_header_t*)rx_buffer)->absSF;
-    wakeup_thread(&UE->timer_mutex,&UE->timer_cond,&UE->instance_cnt_timer,"timer_thread");
-    break;
-  case SLSCH:
-
-
-    LOG_I(PHY,"Emulator SFN.SF %d.%d, Got SLSCH packet\n",emulator_absSF/10,emulator_absSF%10);
-    LOG_I(PHY,"Received %d bytes on UE-UE link for SFN.SF %d.%d, sending SLSCH payload (%d bytes) to MAC\n",num_bytes,
-	  pdu->header.absSF/10,pdu->header.absSF%10,
-	  slsch->payload_length);
-    printf("SLSCH:");
-    for (int i=0;i<sizeof(SLSCH_t);i++) printf("%x ",((uint8_t*)slsch)[i]);
-    printf("\n");
-
-    ue_send_sl_sdu(0,
-		   0,
-		   pdu->header.absSF/10,
-		   pdu->header.absSF%10,
-		   pdu->payload,
-		   slsch->payload_length,
-		   0,
-		   SL_DISCOVERY_FLAG_NO);
-    break;
-
-  case SLDCH:
-
-
-    LOG_I(PHY,"Emulator SFN.SF %d.%d, Got SLDCH packet\n",emulator_absSF/10,emulator_absSF%10);
-    LOG_I(PHY,"Received %d bytes on UE-UE link for SFN.SF %d.%d, sending SLDCH payload (%d bytes) to MAC\n",num_bytes,
-          pdu->header.absSF/10,pdu->header.absSF%10,
-          sldch->payload_length);
-    printf("SLDCH:");
-    for (int i=0;i<sizeof(SLDCH_t);i++) printf("%x ",((uint8_t*)sldch)[i]);
-    printf("\n");
-
-    ue_send_sl_sdu(0,
-                   0,
-                   pdu->header.absSF/10,
-                   pdu->header.absSF%10,
-                   sldch->payload,
-                   sldch->payload_length,
-                   0,
-                   SL_DISCOVERY_FLAG_YES);
-    break;
+    case SLSCH:
+      LOG_I(PHY,"Emulator SFN.SF %d.%d, Got SLSCH packet\n",emulator_absSF/10,emulator_absSF%10);
+      LOG_I(PHY,"Received %d bytes on UE-UE link for SFN.SF %d.%d, sending SLSCH payload (%d bytes) to MAC\n",num_bytes,
+            pdu->header.absSF/10,pdu->header.absSF%10,
+            slsch->payload_length);
+      printf("SLSCH:");
+
+      for (int i=0; i<sizeof(SLSCH_t); i++) printf("%x ",((uint8_t *)slsch)[i]);
+
+      printf("\n");
+      ue_send_sl_sdu(0,
+                     0,
+                     pdu->header.absSF/10,
+                     pdu->header.absSF%10,
+                     pdu->payload,
+                     slsch->payload_length,
+                     0,
+                     SL_DISCOVERY_FLAG_NO);
+      break;
 
+    case SLDCH:
+      LOG_I(PHY,"Emulator SFN.SF %d.%d, Got SLDCH packet\n",emulator_absSF/10,emulator_absSF%10);
+      LOG_I(PHY,"Received %d bytes on UE-UE link for SFN.SF %d.%d, sending SLDCH payload (%d bytes) to MAC\n",num_bytes,
+            pdu->header.absSF/10,pdu->header.absSF%10,
+            sldch->payload_length);
+      printf("SLDCH:");
+
+      for (int i=0; i<sizeof(SLDCH_t); i++) printf("%x ",((uint8_t *)sldch)[i]);
+
+      printf("\n");
+      ue_send_sl_sdu(0,
+                     0,
+                     pdu->header.absSF/10,
+                     pdu->header.absSF%10,
+                     sldch->payload,
+                     sldch->payload_length,
+                     0,
+                     SL_DISCOVERY_FLAG_YES);
+      break;
   }
 }
 
@@ -962,21 +944,19 @@ void ue_stub_rx_handler(unsigned int num_bytes, char *rx_buffer) {
  */
 
 static void *UE_phy_stub_single_thread_rxn_txnp4(void *arg) {
-
-	thread_top_init("UE_phy_stub_thread_rxn_txnp4",1,870000L,1000000L,1000000L);
-
-	// for multipule UE's L2-emulator
-	//module_id_t Mod_id = 0;
-
-	//int init_ra_UE = -1; // This counter is used to initiate the RA of each UE in different SFrames
+  thread_top_init("UE_phy_stub_thread_rxn_txnp4",1,870000L,1000000L,1000000L);
+  // for multipule UE's L2-emulator
+  //module_id_t Mod_id = 0;
+  //int init_ra_UE = -1; // This counter is used to initiate the RA of each UE in different SFrames
   static __thread int UE_thread_rxtx_retval;
   struct rx_tx_thread_data *rtd = arg;
+
   if (rtd == NULL) {
-      LOG_E( MAC, "[SCHED][UE] rx_tx_thread_data *rtd: NULL pointer\n" );
-      exit_fun("nothing to add");    
+    LOG_E( MAC, "[SCHED][UE] rx_tx_thread_data *rtd: NULL pointer\n" );
+    exit_fun("nothing to add");
   }
-  UE_rxtx_proc_t *proc = rtd->proc;
 
+  UE_rxtx_proc_t *proc = rtd->proc;
   // settings for nfapi-L2-emulator mode
   module_id_t ue_thread_id = rtd->ue_thread_id;
   uint16_t     ue_index = 0;
@@ -987,11 +967,9 @@ static void *UE_phy_stub_single_thread_rxn_txnp4(void *arg) {
   uint8_t   end_flag;
   proc = &PHY_vars_UE_g[0][0]->proc.proc_rxtx[0];
   phy_stub_ticking->num_single_thread[ue_thread_id] = -1;
-
   UE = rtd->UE;
- 
 
-  if(ue_thread_id == 0){
+  if(ue_thread_id == 0) {
     phy_stub_ticking->ticking_var = -1;
     proc->subframe_rx=proc->sub_frame_start;
     // Initializations for nfapi-L2-emulator mode
@@ -1001,296 +979,287 @@ static void *UE_phy_stub_single_thread_rxn_txnp4(void *arg) {
     tx_request_pdu_list = NULL;
 
     // waiting for all UE's threads set phy_stub_ticking->num_single_thread[ue_thread_id] = -1.
-    do{
+    do {
       end_flag = 1;
-      for(uint16_t i = 0;i< NB_THREAD_INST;i++){
-        if(phy_stub_ticking->num_single_thread[i] == 0){
+
+      for(uint16_t i = 0; i< NB_THREAD_INST; i++) {
+        if(phy_stub_ticking->num_single_thread[i] == 0) {
           end_flag = 0;
         }
       }
-   }while(end_flag == 0);
+    } while(end_flag == 0);
 
     sync_var=0;
   }
 
-
   //PANOS: CAREFUL HERE!
   wait_sync("UE_phy_stub_single_thread_rxn_txnp4");
 
   while (!oai_exit) {
-    if(ue_thread_id == 0){
-    if (pthread_mutex_lock(&phy_stub_ticking->mutex_ticking) != 0) {
-      LOG_E( MAC, "[SCHED][UE] error locking mutex for UE RXTX\n" );
-      exit_fun("nothing to add");
-    }
-    while (phy_stub_ticking->ticking_var < 0) {
-      // most of the time, the thread is waiting here
-      //pthread_cond_wait( &proc->cond_rxtx, &proc->mutex_rxtx )
-      LOG_D(MAC,"Waiting for ticking_var\n");
-      pthread_cond_wait( &phy_stub_ticking->cond_ticking, &phy_stub_ticking->mutex_ticking);
-    }
-    phy_stub_ticking->ticking_var--;
-    if (pthread_mutex_unlock(&phy_stub_ticking->mutex_ticking) != 0) {
-      LOG_E( MAC, "[SCHED][UE] error unlocking mutex for UE RXn_TXnp4\n" );
-      exit_fun("nothing to add");
-    }
-
-    proc->subframe_rx=timer_subframe;
-    proc->frame_rx = timer_frame;
-    
-    // FDD and TDD tx timing settings.
-    // XXX:It is the result of timing adjustment in debug.
-    // It is necessary to investigate why this will work in the future.
-    proc->subframe_tx=(timer_subframe+sf_ahead)%10;
-    proc->frame_tx = proc->frame_rx + (proc->subframe_rx>(9-sf_ahead)?1:0);
-    //oai_subframe_ind(proc->frame_rx, proc->subframe_rx);
-
-    if (UE != NULL) {
-      if (UE->frame_parms.frame_type == FDD) {
-        oai_subframe_ind(proc->frame_rx, proc->subframe_rx);
-      } else {
-        oai_subframe_ind(proc->frame_tx, proc->subframe_tx);
+    if(ue_thread_id == 0) {
+      if (pthread_mutex_lock(&phy_stub_ticking->mutex_ticking) != 0) {
+        LOG_E( MAC, "[SCHED][UE] error locking mutex for UE RXTX\n" );
+        exit_fun("nothing to add");
       }
-    } else {
-      // Default will be FDD
-      oai_subframe_ind(proc->frame_rx, proc->subframe_rx);
-    }
-
-    //Guessing that the next 4 lines are not needed for the phy_stub mode.
-    /*initRefTimes(t2);
-      initRefTimes(t3);
-      pickTime(current);
-      updateTimes(proc->gotIQs, &t2, 10000, "Delay to wake up UE_Thread_Rx (case 2)");*/
-
 
-    	// Not sure whether we should put the memory allocation here and not sure how much memory
-        //we should allocate for each subframe cycle.
-    	UL_INFO = (UL_IND_t*)malloc(sizeof(UL_IND_t));
+      while (phy_stub_ticking->ticking_var < 0) {
+        // most of the time, the thread is waiting here
+        //pthread_cond_wait( &proc->cond_rxtx, &proc->mutex_rxtx )
+        LOG_D(MAC,"Waiting for ticking_var\n");
+        pthread_cond_wait( &phy_stub_ticking->cond_ticking, &phy_stub_ticking->mutex_ticking);
+      }
 
-    	UL_INFO->rx_ind.rx_indication_body.rx_pdu_list = (nfapi_rx_indication_pdu_t*)malloc(NB_UE_INST*sizeof(nfapi_rx_indication_pdu_t));
-    	UL_INFO->rx_ind.rx_indication_body.number_of_pdus = 0;
+      phy_stub_ticking->ticking_var--;
 
+      if (pthread_mutex_unlock(&phy_stub_ticking->mutex_ticking) != 0) {
+        LOG_E( MAC, "[SCHED][UE] error unlocking mutex for UE RXn_TXnp4\n" );
+        exit_fun("nothing to add");
+      }
 
-    	UL_INFO->crc_ind.crc_indication_body.crc_pdu_list = (nfapi_crc_indication_pdu_t*)malloc(NB_UE_INST*sizeof(nfapi_crc_indication_pdu_t));
-    	UL_INFO->crc_ind.crc_indication_body.number_of_crcs = 0;
+      proc->subframe_rx=timer_subframe;
+      proc->frame_rx = timer_frame;
+      // FDD and TDD tx timing settings.
+      // XXX:It is the result of timing adjustment in debug.
+      // It is necessary to investigate why this will work in the future.
+      proc->subframe_tx=(timer_subframe+sf_ahead)%10;
+      proc->frame_tx = proc->frame_rx + (proc->subframe_rx>(9-sf_ahead)?1:0);
+      //oai_subframe_ind(proc->frame_rx, proc->subframe_rx);
+
+      if (UE != NULL) {
+        if (UE->frame_parms.frame_type == FDD) {
+          oai_subframe_ind(proc->frame_rx, proc->subframe_rx);
+        } else {
+          oai_subframe_ind(proc->frame_tx, proc->subframe_tx);
+        }
+      } else {
+        // Default will be FDD
+        oai_subframe_ind(proc->frame_rx, proc->subframe_rx);
+      }
 
-    	UL_INFO->harq_ind.harq_indication_body.harq_pdu_list = (nfapi_harq_indication_pdu_t*)malloc(NB_UE_INST*sizeof(nfapi_harq_indication_pdu_t));
-    	UL_INFO->harq_ind.harq_indication_body.number_of_harqs = 0;
+      //Guessing that the next 4 lines are not needed for the phy_stub mode.
+      /*initRefTimes(t2);
+        initRefTimes(t3);
+        pickTime(current);
+        updateTimes(proc->gotIQs, &t2, 10000, "Delay to wake up UE_Thread_Rx (case 2)");*/
+      // Not sure whether we should put the memory allocation here and not sure how much memory
+      //we should allocate for each subframe cycle.
+      UL_INFO = (UL_IND_t *)malloc(sizeof(UL_IND_t));
+      UL_INFO->rx_ind.rx_indication_body.rx_pdu_list = (nfapi_rx_indication_pdu_t *)malloc(NB_UE_INST*sizeof(nfapi_rx_indication_pdu_t));
+      UL_INFO->rx_ind.rx_indication_body.number_of_pdus = 0;
+      UL_INFO->crc_ind.crc_indication_body.crc_pdu_list = (nfapi_crc_indication_pdu_t *)malloc(NB_UE_INST*sizeof(nfapi_crc_indication_pdu_t));
+      UL_INFO->crc_ind.crc_indication_body.number_of_crcs = 0;
+      UL_INFO->harq_ind.harq_indication_body.harq_pdu_list = (nfapi_harq_indication_pdu_t *)malloc(NB_UE_INST*sizeof(nfapi_harq_indication_pdu_t));
+      UL_INFO->harq_ind.harq_indication_body.number_of_harqs = 0;
+      UL_INFO->sr_ind.sr_indication_body.sr_pdu_list = (nfapi_sr_indication_pdu_t *)malloc(NB_UE_INST*sizeof(nfapi_sr_indication_pdu_t));
+      UL_INFO->sr_ind.sr_indication_body.number_of_srs = 0;
+      UL_INFO->cqi_ind.cqi_pdu_list =  (nfapi_cqi_indication_pdu_t *)malloc(NB_UE_INST*sizeof(nfapi_cqi_indication_pdu_t));
+      UL_INFO->cqi_ind.cqi_raw_pdu_list = (nfapi_cqi_indication_raw_pdu_t *)malloc(NB_UE_INST*sizeof(nfapi_cqi_indication_raw_pdu_t));
+      UL_INFO->cqi_ind.number_of_cqis = 0;
+
+      if (pthread_mutex_lock(&phy_stub_ticking->mutex_single_thread) != 0) {
+        LOG_E( MAC, "[SCHED][UE] error locking mutex for ue_thread_id %d (mutex_single_thread)\n",ue_thread_id);
+        exit_fun("nothing to add");
+      }
 
-    	UL_INFO->sr_ind.sr_indication_body.sr_pdu_list = (nfapi_sr_indication_pdu_t*)malloc(NB_UE_INST*sizeof(nfapi_sr_indication_pdu_t));
-     	UL_INFO->sr_ind.sr_indication_body.number_of_srs = 0;
+      memset(&phy_stub_ticking->num_single_thread[0],0,sizeof(int)*NB_THREAD_INST);
+      pthread_cond_broadcast(&phy_stub_ticking->cond_single_thread);
 
-        UL_INFO->cqi_ind.cqi_pdu_list =  (nfapi_cqi_indication_pdu_t*)malloc(NB_UE_INST*sizeof(nfapi_cqi_indication_pdu_t));
-        UL_INFO->cqi_ind.cqi_raw_pdu_list = (nfapi_cqi_indication_raw_pdu_t*)malloc(NB_UE_INST*sizeof(nfapi_cqi_indication_raw_pdu_t));
-        UL_INFO->cqi_ind.number_of_cqis = 0;
+      if (pthread_mutex_unlock(&phy_stub_ticking->mutex_single_thread) != 0) {
+        LOG_E( MAC, "[SCHED][UE] error unlocking mutex for ue_thread_id %d (mutex_single_thread)\n",ue_thread_id);
+        exit_fun("nothing to add");
+      }
+    } else {
+      if (pthread_mutex_lock(&phy_stub_ticking->mutex_single_thread) != 0) {
+        LOG_E( MAC, "[SCHED][UE] error locking mutex for ue_thread_id %d (mutex_single_thread)\n",ue_thread_id);
+        exit_fun("nothing to add");
+      }
 
-        if (pthread_mutex_lock(&phy_stub_ticking->mutex_single_thread) != 0) {
-          LOG_E( MAC, "[SCHED][UE] error locking mutex for ue_thread_id %d (mutex_single_thread)\n",ue_thread_id);
-          exit_fun("nothing to add");
-        }
-        memset(&phy_stub_ticking->num_single_thread[0],0,sizeof(int)*NB_THREAD_INST);
-        pthread_cond_broadcast(&phy_stub_ticking->cond_single_thread);
+      while (phy_stub_ticking->num_single_thread[ue_thread_id] < 0) {
+        // most of the time, the thread is waiting here
+        LOG_D(MAC,"Waiting for single_thread (ue_thread_id %d)\n",ue_thread_id);
+        pthread_cond_wait( &phy_stub_ticking->cond_single_thread, &phy_stub_ticking->mutex_single_thread);
+      }
 
-        if (pthread_mutex_unlock(&phy_stub_ticking->mutex_single_thread) != 0) {
-          LOG_E( MAC, "[SCHED][UE] error unlocking mutex for ue_thread_id %d (mutex_single_thread)\n",ue_thread_id);
-          exit_fun("nothing to add");
-        }
-    }else{
-        if (pthread_mutex_lock(&phy_stub_ticking->mutex_single_thread) != 0) {
-          LOG_E( MAC, "[SCHED][UE] error locking mutex for ue_thread_id %d (mutex_single_thread)\n",ue_thread_id);
-           exit_fun("nothing to add");
-        }
-        while (phy_stub_ticking->num_single_thread[ue_thread_id] < 0) {
-          // most of the time, the thread is waiting here
-          LOG_D(MAC,"Waiting for single_thread (ue_thread_id %d)\n",ue_thread_id);
-          pthread_cond_wait( &phy_stub_ticking->cond_single_thread, &phy_stub_ticking->mutex_single_thread);
-        }
-        if (pthread_mutex_unlock(&phy_stub_ticking->mutex_single_thread) != 0) {
-          LOG_E( MAC, "[SCHED][UE] error unlocking mutex for ue_thread_id %d (mutex_single_thread)\n",ue_thread_id);
-          exit_fun("nothing to add");
-        }
+      if (pthread_mutex_unlock(&phy_stub_ticking->mutex_single_thread) != 0) {
+        LOG_E( MAC, "[SCHED][UE] error unlocking mutex for ue_thread_id %d (mutex_single_thread)\n",ue_thread_id);
+        exit_fun("nothing to add");
+      }
     }
 
     //for (Mod_id=0; Mod_id<NB_UE_INST; Mod_id++) {
     for (ue_index=0; ue_index < ue_num; ue_index++) {
-    ue_Mod_id = ue_thread_id + NB_THREAD_INST*ue_index;
-    UE = PHY_vars_UE_g[ue_Mod_id][0];
-    //LOG_D(MAC, "UE_phy_stub_single_thread_rxn_txnp4, NB_UE_INST:%d, Mod_id:%d \n", NB_UE_INST, Mod_id);
-    //UE = PHY_vars_UE_g[Mod_id][0];
-    lte_subframe_t sf_type = subframe_select( &UE->frame_parms, proc->subframe_rx);
-    if ((sf_type == SF_DL) ||
-	(UE->frame_parms.frame_type == FDD) ||
-	(sf_type == SF_S)) {
-
-      if (UE->frame_parms.frame_type == TDD) {
-	LOG_D(PHY, "TDD%d,%s: calling UE_RX\n",
-	      UE->frame_parms.tdd_config,
-	      (sf_type==SF_DL? "SF_DL" :
-	       (sf_type==SF_UL? "SF_UL" :
-		(sf_type==SF_S ? "SF_S"  : "UNKNOWN_SF_TYPE"))));
-      } else {
-	LOG_D(PHY, "%s,%s: calling UE_RX\n",
-	      (UE->frame_parms.frame_type==FDD? "FDD":
-	       (UE->frame_parms.frame_type==TDD? "TDD":"UNKNOWN_DUPLEX_MODE")),
-	      (sf_type==SF_DL? "SF_DL" :
-	       (sf_type==SF_UL? "SF_UL" :
-		(sf_type==SF_S ? "SF_S"  : "UNKNOWN_SF_TYPE"))));
-      }
+      ue_Mod_id = ue_thread_id + NB_THREAD_INST*ue_index;
+      UE = PHY_vars_UE_g[ue_Mod_id][0];
+      //LOG_D(MAC, "UE_phy_stub_single_thread_rxn_txnp4, NB_UE_INST:%d, Mod_id:%d \n", NB_UE_INST, Mod_id);
+      //UE = PHY_vars_UE_g[Mod_id][0];
+      lte_subframe_t sf_type = subframe_select( &UE->frame_parms, proc->subframe_rx);
+
+      if ((sf_type == SF_DL) ||
+          (UE->frame_parms.frame_type == FDD) ||
+          (sf_type == SF_S)) {
+        if (UE->frame_parms.frame_type == TDD) {
+          LOG_D(PHY, "TDD%d,%s: calling UE_RX\n",
+                UE->frame_parms.tdd_config,
+                (sf_type==SF_DL? "SF_DL" :
+                 (sf_type==SF_UL? "SF_UL" :
+                  (sf_type==SF_S ? "SF_S"  : "UNKNOWN_SF_TYPE"))));
+        } else {
+          LOG_D(PHY, "%s,%s: calling UE_RX\n",
+                (UE->frame_parms.frame_type==FDD? "FDD":
+                 (UE->frame_parms.frame_type==TDD? "TDD":"UNKNOWN_DUPLEX_MODE")),
+                (sf_type==SF_DL? "SF_DL" :
+                 (sf_type==SF_UL? "SF_UL" :
+                  (sf_type==SF_S ? "SF_S"  : "UNKNOWN_SF_TYPE"))));
+        }
 
+        phy_procedures_UE_SL_RX(UE,proc);
 
-      phy_procedures_UE_SL_RX(UE,proc);
-
-      if (dl_config_req!=NULL && tx_request_pdu_list!=NULL){
-    	  //if(dl_config_req!= NULL) {
-    	  dl_config_req_UE_MAC(dl_config_req, ue_Mod_id);
+        if (dl_config_req!=NULL && tx_request_pdu_list!=NULL) {
+          //if(dl_config_req!= NULL) {
+          dl_config_req_UE_MAC(dl_config_req, ue_Mod_id);
+        }
 
-      }
+        if (hi_dci0_req!=NULL && hi_dci0_req->hi_dci0_request_body.hi_dci0_pdu_list!=NULL) {
+          hi_dci0_req_UE_MAC(hi_dci0_req, ue_Mod_id);
+        }
 
-      if (hi_dci0_req!=NULL && hi_dci0_req->hi_dci0_request_body.hi_dci0_pdu_list!=NULL){
-    	  hi_dci0_req_UE_MAC(hi_dci0_req, ue_Mod_id);
+        if(nfapi_mode!=3)
+          phy_procedures_UE_SL_TX(UE,proc);
       }
 
-      if(nfapi_mode!=3)
-      phy_procedures_UE_SL_TX(UE,proc);
-
-    }
-
 #if UE_TIMING_TRACE
-    start_meas(&UE->generic_stat);
+      start_meas(&UE->generic_stat);
 #endif
 
-    if (UE->mac_enabled==1) {
-
-      ret = ue_scheduler(ue_Mod_id,
-			 proc->frame_rx,
-			 proc->subframe_rx,
-			 proc->frame_tx,
-			 proc->subframe_tx,
-			 subframe_select(&UE->frame_parms,proc->subframe_tx),
-			 0,
-			 0/*FIXME CC_id*/);
-      if ( ret != CONNECTION_OK) {
-	LOG_E( PHY, "[UE %"PRIu8"] Frame %"PRIu32", subframe %u %s\n",
-	       UE->Mod_id, proc->frame_rx, proc->subframe_tx,get_connectionloss_errstr(ret) );
+      if (UE->mac_enabled==1) {
+        ret = ue_scheduler(ue_Mod_id,
+                           proc->frame_rx,
+                           proc->subframe_rx,
+                           proc->frame_tx,
+                           proc->subframe_tx,
+                           subframe_select(&UE->frame_parms,proc->subframe_tx),
+                           0,
+                           0/*FIXME CC_id*/);
+
+        if ( ret != CONNECTION_OK) {
+          LOG_E( PHY, "[UE %"PRIu8"] Frame %"PRIu32", subframe %u %s\n",
+                 UE->Mod_id, proc->frame_rx, proc->subframe_tx,get_connectionloss_errstr(ret) );
+        }
       }
-    }
+
 #if UE_TIMING_TRACE
-    stop_meas(&UE->generic_stat);
+      stop_meas(&UE->generic_stat);
 #endif
 
+      // Prepare the future Tx data
+
+      if ((subframe_select( &UE->frame_parms, proc->subframe_tx) == SF_UL) ||
+          (UE->frame_parms.frame_type == FDD) )
+        if (UE->mode != loop_through_memory) {
+          // We make the start of RA between consecutive UEs differ by 20 frames
+          //if ((UE_mac_inst[Mod_id].UE_mode[0] == PRACH  && Mod_id == 0) || (UE_mac_inst[Mod_id].UE_mode[0] == PRACH && Mod_id>0 && proc->frame_rx >= UE_mac_inst[Mod_id-1].ra_frame + 20) ) {
+          if (UE_mac_inst[ue_Mod_id].UE_mode[0] == PRACH  && ue_Mod_id == next_Mod_id) {
+            next_ra_frame++;
+
+            if(next_ra_frame > 200) {
+              // check if we have PRACH opportunity
+              if (is_prach_subframe(&UE->frame_parms,proc->frame_tx, proc->subframe_tx) &&  UE_mac_inst[ue_Mod_id].SI_Decoded == 1) {
+                // The one working strangely...
+                //if (is_prach_subframe(&UE->frame_parms,proc->frame_tx, proc->subframe_tx && Mod_id == (module_id_t) init_ra_UE) ) {
+                PRACH_RESOURCES_t *prach_resources = ue_get_rach(ue_Mod_id, 0, proc->frame_tx, 0, proc->subframe_tx);
+
+                if(prach_resources!=NULL ) {
+                  UE_mac_inst[ue_Mod_id].ra_frame = proc->frame_rx;
+                  LOG_D(MAC, "UE_phy_stub_thread_rxn_txnp4 before RACH, Mod_id: %d frame %d subframe %d\n", ue_Mod_id,proc->frame_tx, proc->subframe_tx);
+                  fill_rach_indication_UE_MAC(ue_Mod_id, proc->frame_tx,proc->subframe_tx, UL_INFO, prach_resources->ra_PreambleIndex, prach_resources->ra_RNTI);
+                  Msg1_transmitted(ue_Mod_id, 0, proc->frame_tx, 0);
+                  UE_mac_inst[ue_Mod_id].UE_mode[0] = RA_RESPONSE;
+                  next_Mod_id = ue_Mod_id + 1;
+                  //next_ra_frame = (proc->frame_rx + 20)%1000;
+                  next_ra_frame = 0;
+                }
 
-    // Prepare the future Tx data
+                //ue_prach_procedures(ue,proc,eNB_id,abstraction_flag,mode);
+              }
+            }
+          } // mode is PRACH
 
-    if ((subframe_select( &UE->frame_parms, proc->subframe_tx) == SF_UL) ||
-	(UE->frame_parms.frame_type == FDD) )
-      if (UE->mode != loop_through_memory){
-
-    // We make the start of RA between consecutive UEs differ by 20 frames
-	//if ((UE_mac_inst[Mod_id].UE_mode[0] == PRACH  && Mod_id == 0) || (UE_mac_inst[Mod_id].UE_mode[0] == PRACH && Mod_id>0 && proc->frame_rx >= UE_mac_inst[Mod_id-1].ra_frame + 20) ) {
-	if (UE_mac_inst[ue_Mod_id].UE_mode[0] == PRACH  && ue_Mod_id == next_Mod_id) {
-          next_ra_frame++;
-          if(next_ra_frame > 200){
-	  // check if we have PRACH opportunity
-
-	  if (is_prach_subframe(&UE->frame_parms,proc->frame_tx, proc->subframe_tx) &&  UE_mac_inst[ue_Mod_id].SI_Decoded == 1) {
-
-	  // The one working strangely...
-      //if (is_prach_subframe(&UE->frame_parms,proc->frame_tx, proc->subframe_tx && Mod_id == (module_id_t) init_ra_UE) ) {
-
-	    PRACH_RESOURCES_t *prach_resources = ue_get_rach(ue_Mod_id, 0, proc->frame_tx, 0, proc->subframe_tx);
-	    if(prach_resources!=NULL ) {
-	    	UE_mac_inst[ue_Mod_id].ra_frame = proc->frame_rx;
-	      LOG_D(MAC, "UE_phy_stub_thread_rxn_txnp4 before RACH, Mod_id: %d frame %d subframe %d\n", ue_Mod_id ,proc->frame_tx, proc->subframe_tx);
-	      fill_rach_indication_UE_MAC(ue_Mod_id, proc->frame_tx ,proc->subframe_tx, UL_INFO, prach_resources->ra_PreambleIndex, prach_resources->ra_RNTI);
-	      Msg1_transmitted(ue_Mod_id, 0, proc->frame_tx, 0);
-	      UE_mac_inst[ue_Mod_id].UE_mode[0] = RA_RESPONSE;
-	      next_Mod_id = ue_Mod_id + 1;
-	      //next_ra_frame = (proc->frame_rx + 20)%1000;
-              next_ra_frame = 0;
-	    }
-
-	    //ue_prach_procedures(ue,proc,eNB_id,abstraction_flag,mode);
-	  }
+          // Substitute call to phy_procedures Tx with call to phy_stub functions in order to trigger
+          // UE Tx procedures directly at the MAC layer, based on the received ul_config requests from the vnf (eNB).
+          // Generate UL_indications which correspond to UL traffic.
+          if(ul_config_req!=NULL) { //&& UE_mac_inst[Mod_id].ul_config_req->ul_config_request_body.ul_config_pdu_list != NULL){
+            ul_config_req_UE_MAC(ul_config_req, timer_frame, timer_subframe, ue_Mod_id);
           }
-	} // mode is PRACH
-	// Substitute call to phy_procedures Tx with call to phy_stub functions in order to trigger
-	// UE Tx procedures directly at the MAC layer, based on the received ul_config requests from the vnf (eNB).
-	// Generate UL_indications which correspond to UL traffic.
-	if(ul_config_req!=NULL){ //&& UE_mac_inst[Mod_id].ul_config_req->ul_config_request_body.ul_config_pdu_list != NULL){
-		ul_config_req_UE_MAC(ul_config_req, timer_frame, timer_subframe, ue_Mod_id);
-	}
-      }
-
-    phy_procedures_UE_SL_RX(UE,proc);
-
+        }
 
+      phy_procedures_UE_SL_RX(UE,proc);
     } //for (Mod_id=0; Mod_id<NB_UE_INST; Mod_id++)
 
     phy_stub_ticking->num_single_thread[ue_thread_id] = -1;
 
     // waiting for all UE's threads set phy_stub_ticking->num_single_thread[ue_thread_id] = -1.
-    if(ue_thread_id == 0){
-      do{
+    if(ue_thread_id == 0) {
+      do {
         end_flag = 1;
-        for(uint16_t i = 0;i< NB_THREAD_INST;i++){
-          if(phy_stub_ticking->num_single_thread[i] == 0){
-             end_flag = 0;
+
+        for(uint16_t i = 0; i< NB_THREAD_INST; i++) {
+          if(phy_stub_ticking->num_single_thread[i] == 0) {
+            end_flag = 0;
           }
         }
-      }while(end_flag == 0);
+      } while(end_flag == 0);
+
+      if (UL_INFO->crc_ind.crc_indication_body.number_of_crcs>0) {
+        //LOG_D(PHY,"UL_info->crc_ind.crc_indication_body.number_of_crcs:%d CRC_IND:SFN/SF:%d\n", UL_info->crc_ind.crc_indication_body.number_of_crcs, NFAPI_SFNSF2DEC(UL_info->crc_ind.sfn_sf));
+        //LOG_I(MAC, "ul_config_req_UE_MAC 2.2, SFN/SF of PNF counter:%d.%d, number_of_crcs: %d \n", timer_frame, timer_subframe, UL_INFO->crc_ind.crc_indication_body.number_of_crcs);
+        oai_nfapi_crc_indication(&UL_INFO->crc_ind);
+        //LOG_I(MAC, "ul_config_req_UE_MAC 2.21 \n");
+        UL_INFO->crc_ind.crc_indication_body.number_of_crcs = 0;
+      }
 
+      if (UL_INFO->rx_ind.rx_indication_body.number_of_pdus>0) {
+        //LOG_D(PHY,"UL_info->rx_ind.number_of_pdus:%d RX_IND:SFN/SF:%d\n", UL_info->rx_ind.rx_indication_body.number_of_pdus, NFAPI_SFNSF2DEC(UL_info->rx_ind.sfn_sf));
+        //LOG_I(MAC, "ul_config_req_UE_MAC 2.3, SFN/SF of PNF counter:%d.%d, number_of_pdus: %d \n", timer_frame, timer_subframe, UL_INFO->rx_ind.rx_indication_body.number_of_pdus);
+        oai_nfapi_rx_ind(&UL_INFO->rx_ind);
 
-    if (UL_INFO->crc_ind.crc_indication_body.number_of_crcs>0)
-      {
-    	  //LOG_D(PHY,"UL_info->crc_ind.crc_indication_body.number_of_crcs:%d CRC_IND:SFN/SF:%d\n", UL_info->crc_ind.crc_indication_body.number_of_crcs, NFAPI_SFNSF2DEC(UL_info->crc_ind.sfn_sf));
-    	  //LOG_I(MAC, "ul_config_req_UE_MAC 2.2, SFN/SF of PNF counter:%d.%d, number_of_crcs: %d \n", timer_frame, timer_subframe, UL_INFO->crc_ind.crc_indication_body.number_of_crcs);
-    	  oai_nfapi_crc_indication(&UL_INFO->crc_ind);
-    	  //LOG_I(MAC, "ul_config_req_UE_MAC 2.21 \n");
-    	  UL_INFO->crc_ind.crc_indication_body.number_of_crcs = 0;
-      }
-      if (UL_INFO->rx_ind.rx_indication_body.number_of_pdus>0)
-      {
-    	  //LOG_D(PHY,"UL_info->rx_ind.number_of_pdus:%d RX_IND:SFN/SF:%d\n", UL_info->rx_ind.rx_indication_body.number_of_pdus, NFAPI_SFNSF2DEC(UL_info->rx_ind.sfn_sf));
-    	  //LOG_I(MAC, "ul_config_req_UE_MAC 2.3, SFN/SF of PNF counter:%d.%d, number_of_pdus: %d \n", timer_frame, timer_subframe, UL_INFO->rx_ind.rx_indication_body.number_of_pdus);
-    	  oai_nfapi_rx_ind(&UL_INFO->rx_ind);
-          for(uint8_t num_pdu = 0;num_pdu < UL_INFO->rx_ind.rx_indication_body.number_of_pdus;num_pdu++){
-            free(UL_INFO->rx_ind.rx_indication_body.rx_pdu_list[num_pdu].data);
-          }
-    	  //LOG_I(MAC, "ul_config_req_UE_MAC 2.31 \n");
-    	  UL_INFO->rx_ind.rx_indication_body.number_of_pdus = 0;
+        for(uint8_t num_pdu = 0; num_pdu < UL_INFO->rx_ind.rx_indication_body.number_of_pdus; num_pdu++) {
+          free(UL_INFO->rx_ind.rx_indication_body.rx_pdu_list[num_pdu].data);
+        }
+
+        //LOG_I(MAC, "ul_config_req_UE_MAC 2.31 \n");
+        UL_INFO->rx_ind.rx_indication_body.number_of_pdus = 0;
       }
-      if(UL_INFO->harq_ind.harq_indication_body.number_of_harqs>0)
-      {
-    	  //LOG_D(MAC, "ul_config_req_UE_MAC 2.4, SFN/SF of PNF counter:%d.%d, number_of_harqs: %d \n", timer_frame, timer_subframe, UL_INFO->harq_ind.harq_indication_body.number_of_harqs);
-    	  oai_nfapi_harq_indication(&UL_INFO->harq_ind);
-    	  //LOG_I(MAC, "ul_config_req_UE_MAC 2.41 \n");
-    	  UL_INFO->harq_ind.harq_indication_body.number_of_harqs =0;
 
+      if(UL_INFO->harq_ind.harq_indication_body.number_of_harqs>0) {
+        //LOG_D(MAC, "ul_config_req_UE_MAC 2.4, SFN/SF of PNF counter:%d.%d, number_of_harqs: %d \n", timer_frame, timer_subframe, UL_INFO->harq_ind.harq_indication_body.number_of_harqs);
+        oai_nfapi_harq_indication(&UL_INFO->harq_ind);
+        //LOG_I(MAC, "ul_config_req_UE_MAC 2.41 \n");
+        UL_INFO->harq_ind.harq_indication_body.number_of_harqs =0;
       }
-      if(UL_INFO->sr_ind.sr_indication_body.number_of_srs>0)
-      {
-    	  //LOG_I(MAC, "ul_config_req_UE_MAC 2.5, SFN/SF of PNF counter:%d.%d, number_of_srs: %d \n", timer_frame, timer_subframe, UL_INFO->sr_ind.sr_indication_body.number_of_srs);
-    	  oai_nfapi_sr_indication(&UL_INFO->sr_ind);
-    	  //LOG_I(MAC, "ul_config_req_UE_MAC 2.51 \n");
-    	  UL_INFO->sr_ind.sr_indication_body.number_of_srs = 0;
+
+      if(UL_INFO->sr_ind.sr_indication_body.number_of_srs>0) {
+        //LOG_I(MAC, "ul_config_req_UE_MAC 2.5, SFN/SF of PNF counter:%d.%d, number_of_srs: %d \n", timer_frame, timer_subframe, UL_INFO->sr_ind.sr_indication_body.number_of_srs);
+        oai_nfapi_sr_indication(&UL_INFO->sr_ind);
+        //LOG_I(MAC, "ul_config_req_UE_MAC 2.51 \n");
+        UL_INFO->sr_ind.sr_indication_body.number_of_srs = 0;
       }
 
       // Free UL_INFO messages
       //if(UL_INFO->crc_ind.crc_indication_body.crc_pdu_list != NULL){
-    	  free(UL_INFO->crc_ind.crc_indication_body.crc_pdu_list);
-    	  UL_INFO->crc_ind.crc_indication_body.crc_pdu_list = NULL;
+      free(UL_INFO->crc_ind.crc_indication_body.crc_pdu_list);
+      UL_INFO->crc_ind.crc_indication_body.crc_pdu_list = NULL;
       //}
       //if(UL_INFO->rx_ind.rx_indication_body.rx_pdu_list != NULL){
-    	  free(UL_INFO->rx_ind.rx_indication_body.rx_pdu_list);
-    	  UL_INFO->rx_ind.rx_indication_body.rx_pdu_list = NULL;
+      free(UL_INFO->rx_ind.rx_indication_body.rx_pdu_list);
+      UL_INFO->rx_ind.rx_indication_body.rx_pdu_list = NULL;
       //}
       //if(UL_INFO->harq_ind.harq_indication_body.harq_pdu_list !=NULL){
-    	  free(UL_INFO->harq_ind.harq_indication_body.harq_pdu_list);
-    	  UL_INFO->harq_ind.harq_indication_body.harq_pdu_list = NULL;
+      free(UL_INFO->harq_ind.harq_indication_body.harq_pdu_list);
+      UL_INFO->harq_ind.harq_indication_body.harq_pdu_list = NULL;
       //}
       //if(UL_INFO->sr_ind.sr_indication_body.sr_pdu_list!=NULL){
-    	  free(UL_INFO->sr_ind.sr_indication_body.sr_pdu_list);
-    	  UL_INFO->sr_ind.sr_indication_body.sr_pdu_list = NULL;
+      free(UL_INFO->sr_ind.sr_indication_body.sr_pdu_list);
+      UL_INFO->sr_ind.sr_indication_body.sr_pdu_list = NULL;
       //}
       free(UL_INFO->cqi_ind.cqi_pdu_list);
       UL_INFO->cqi_ind.cqi_pdu_list = NULL;
@@ -1300,43 +1269,48 @@ static void *UE_phy_stub_single_thread_rxn_txnp4(void *arg) {
       UL_INFO = NULL;
 
       // De-allocate memory of nfapi requests copies before next subframe round
-      if(dl_config_req!=NULL){
-    	  if(dl_config_req->vendor_extension!=NULL){
-            free(dl_config_req->vendor_extension);
-            dl_config_req->vendor_extension = NULL;
-          }
-    	  if(dl_config_req->dl_config_request_body.dl_config_pdu_list!=NULL){
-    		  free(dl_config_req->dl_config_request_body.dl_config_pdu_list);
-    		  dl_config_req->dl_config_request_body.dl_config_pdu_list = NULL;
-    	  }
-    	  free(dl_config_req);
-    	  dl_config_req = NULL;
-      }
-      if(tx_request_pdu_list!=NULL){
-    	  free(tx_request_pdu_list);
-    	  tx_request_pdu_list = NULL;
+      if(dl_config_req!=NULL) {
+        if(dl_config_req->vendor_extension!=NULL) {
+          free(dl_config_req->vendor_extension);
+          dl_config_req->vendor_extension = NULL;
+        }
+
+        if(dl_config_req->dl_config_request_body.dl_config_pdu_list!=NULL) {
+          free(dl_config_req->dl_config_request_body.dl_config_pdu_list);
+          dl_config_req->dl_config_request_body.dl_config_pdu_list = NULL;
+        }
+
+        free(dl_config_req);
+        dl_config_req = NULL;
       }
-      if(ul_config_req!=NULL){
-    	  if(ul_config_req->ul_config_request_body.ul_config_pdu_list != NULL){
-    		  free(ul_config_req->ul_config_request_body.ul_config_pdu_list);
-    		  ul_config_req->ul_config_request_body.ul_config_pdu_list = NULL;
-    	  }
-    	  free(ul_config_req);
-    	  ul_config_req = NULL;
+
+      if(tx_request_pdu_list!=NULL) {
+        free(tx_request_pdu_list);
+        tx_request_pdu_list = NULL;
       }
 
-      if(hi_dci0_req!=NULL){
-    	  if(hi_dci0_req->hi_dci0_request_body.hi_dci0_pdu_list!=NULL){
-    		  free(hi_dci0_req->hi_dci0_request_body.hi_dci0_pdu_list);
-    		  hi_dci0_req->hi_dci0_request_body.hi_dci0_pdu_list = NULL;
-    	  }
-    	  free(hi_dci0_req);
-    	  hi_dci0_req = NULL;
+      if(ul_config_req!=NULL) {
+        if(ul_config_req->ul_config_request_body.ul_config_pdu_list != NULL) {
+          free(ul_config_req->ul_config_request_body.ul_config_pdu_list);
+          ul_config_req->ul_config_request_body.ul_config_pdu_list = NULL;
+        }
+
+        free(ul_config_req);
+        ul_config_req = NULL;
       }
 
-    }
+      if(hi_dci0_req!=NULL) {
+        if(hi_dci0_req->hi_dci0_request_body.hi_dci0_pdu_list!=NULL) {
+          free(hi_dci0_req->hi_dci0_request_body.hi_dci0_pdu_list);
+          hi_dci0_req->hi_dci0_request_body.hi_dci0_pdu_list = NULL;
+        }
 
+        free(hi_dci0_req);
+        hi_dci0_req = NULL;
+      }
+    }
   }
+
   // thread finished
   free(arg);
   return &UE_thread_rxtx_retval;
@@ -1354,34 +1328,32 @@ static void *UE_phy_stub_single_thread_rxn_txnp4(void *arg) {
  */
 
 static void *UE_phy_stub_thread_rxn_txnp4(void *arg) {
-
-	thread_top_init("UE_phy_stub_thread_rxn_txnp4",1,870000L,1000000L,1000000L);
-
-	module_id_t Mod_id = 0;
+  thread_top_init("UE_phy_stub_thread_rxn_txnp4",1,870000L,1000000L,1000000L);
+  module_id_t Mod_id = 0;
   static __thread int UE_thread_rxtx_retval;
   struct rx_tx_thread_data *rtd = arg;
   UE_rxtx_proc_t *proc = rtd->proc;
   PHY_VARS_UE    *UE   = rtd->UE;
-
   phy_stub_ticking->ticking_var = -1;
   proc->subframe_rx=proc->sub_frame_start;
-
   // CAREFUL HERE!
   wait_sync("UE_phy_stub_thread_rxn_txnp4");
 
   while (!oai_exit) {
-
     if (pthread_mutex_lock(&phy_stub_ticking->mutex_ticking) != 0) {
       LOG_E( MAC, "[SCHED][UE] error locking mutex for UE RXTX\n" );
       exit_fun("nothing to add");
     }
+
     while (phy_stub_ticking->ticking_var < 0) {
       // most of the time, the thread is waiting here
       //pthread_cond_wait( &proc->cond_rxtx, &proc->mutex_rxtx )
       LOG_D(MAC,"Waiting for ticking_var\n");
       pthread_cond_wait( &phy_stub_ticking->cond_ticking, &phy_stub_ticking->mutex_ticking);
     }
+
     phy_stub_ticking->ticking_var--;
+
     if (pthread_mutex_unlock(&phy_stub_ticking->mutex_ticking) != 0) {
       LOG_E( MAC, "[SCHED][UE] error unlocking mutex for UE RXn_TXnp4\n" );
       exit_fun("nothing to add");
@@ -1391,125 +1363,118 @@ static void *UE_phy_stub_thread_rxn_txnp4(void *arg) {
     proc->frame_rx = timer_frame;
     proc->subframe_tx=(timer_subframe+4)%10;
     proc->frame_tx = proc->frame_rx + (proc->subframe_rx>5?1:0);
-
-
     // Process Rx data for one sub-frame
     lte_subframe_t sf_type = subframe_select( &UE->frame_parms, proc->subframe_rx);
-    if ((sf_type == SF_DL) ||
-	(UE->frame_parms.frame_type == FDD) ||
-	(sf_type == SF_S)) {
 
+    if ((sf_type == SF_DL) ||
+        (UE->frame_parms.frame_type == FDD) ||
+        (sf_type == SF_S)) {
       if (UE->frame_parms.frame_type == TDD) {
-	LOG_D(PHY, "TDD%d,%s: calling UE_RX\n",
-	      UE->frame_parms.tdd_config,
-	      (sf_type==SF_DL? "SF_DL" :
-	       (sf_type==SF_UL? "SF_UL" :
-		(sf_type==SF_S ? "SF_S"  : "UNKNOWN_SF_TYPE"))));
+        LOG_D(PHY, "TDD%d,%s: calling UE_RX\n",
+              UE->frame_parms.tdd_config,
+              (sf_type==SF_DL? "SF_DL" :
+               (sf_type==SF_UL? "SF_UL" :
+                (sf_type==SF_S ? "SF_S"  : "UNKNOWN_SF_TYPE"))));
       } else {
-	LOG_D(PHY, "%s,%s: calling UE_RX\n",
-	      (UE->frame_parms.frame_type==FDD? "FDD":
-	       (UE->frame_parms.frame_type==TDD? "TDD":"UNKNOWN_DUPLEX_MODE")),
-	      (sf_type==SF_DL? "SF_DL" :
-	       (sf_type==SF_UL? "SF_UL" :
-		(sf_type==SF_S ? "SF_S"  : "UNKNOWN_SF_TYPE"))));
+        LOG_D(PHY, "%s,%s: calling UE_RX\n",
+              (UE->frame_parms.frame_type==FDD? "FDD":
+               (UE->frame_parms.frame_type==TDD? "TDD":"UNKNOWN_DUPLEX_MODE")),
+              (sf_type==SF_DL? "SF_DL" :
+               (sf_type==SF_UL? "SF_UL" :
+                (sf_type==SF_S ? "SF_S"  : "UNKNOWN_SF_TYPE"))));
       }
 
-
       phy_procedures_UE_SL_RX(UE,proc);
-
-       oai_subframe_ind(timer_frame, timer_subframe);
+      oai_subframe_ind(timer_frame, timer_subframe);
 
       if(dl_config_req!= NULL) {
-
-	dl_config_req_UE_MAC(dl_config_req, Mod_id);
-
+        dl_config_req_UE_MAC(dl_config_req, Mod_id);
       }
+
       //if(UE_mac_inst[Mod_id].hi_dci0_req!= NULL){
-      if (hi_dci0_req!=NULL && hi_dci0_req->hi_dci0_request_body.hi_dci0_pdu_list!=NULL){
-    	  hi_dci0_req_UE_MAC(hi_dci0_req, Mod_id);
-    	  //if(UE_mac_inst[Mod_id].hi_dci0_req->hi_dci0_request_body.hi_dci0_pdu_list!=NULL){
-    		  free(hi_dci0_req->hi_dci0_request_body.hi_dci0_pdu_list);
-    		  hi_dci0_req->hi_dci0_request_body.hi_dci0_pdu_list = NULL;
-    	  //}
-    	  free(hi_dci0_req);
-    	  hi_dci0_req = NULL;
+      if (hi_dci0_req!=NULL && hi_dci0_req->hi_dci0_request_body.hi_dci0_pdu_list!=NULL) {
+        hi_dci0_req_UE_MAC(hi_dci0_req, Mod_id);
+        //if(UE_mac_inst[Mod_id].hi_dci0_req->hi_dci0_request_body.hi_dci0_pdu_list!=NULL){
+        free(hi_dci0_req->hi_dci0_request_body.hi_dci0_pdu_list);
+        hi_dci0_req->hi_dci0_request_body.hi_dci0_pdu_list = NULL;
+        //}
+        free(hi_dci0_req);
+        hi_dci0_req = NULL;
+      } else if(hi_dci0_req!=NULL) {
+        free(hi_dci0_req);
+        hi_dci0_req = NULL;
       }
 
-      else if(hi_dci0_req!=NULL){
-      		free(hi_dci0_req);
-      		hi_dci0_req = NULL;
-      	}
-
       if (nfapi_mode != 3)
         phy_procedures_UE_SL_TX(UE,proc);
-
     }
 
 #if UE_TIMING_TRACE
     start_meas(&UE->generic_stat);
 #endif
-    if (UE->mac_enabled==1) {
 
+    if (UE->mac_enabled==1) {
       int ret = ue_scheduler(UE->Mod_id,
-			 proc->frame_rx,
-			 proc->subframe_rx,
-			 proc->frame_tx,
-			 proc->subframe_tx,
-			 subframe_select(&UE->frame_parms,proc->subframe_tx),
-			 0,
-			 0);
+                             proc->frame_rx,
+                             proc->subframe_rx,
+                             proc->frame_tx,
+                             proc->subframe_tx,
+                             subframe_select(&UE->frame_parms,proc->subframe_tx),
+                             0,
+                             0);
+
       if (ret != CONNECTION_OK)
-	LOG_E( PHY, "[UE %"PRIu8"] Frame %"PRIu32", subframe %u %s\n",
-	       UE->Mod_id, proc->frame_rx, proc->subframe_tx,get_connectionloss_errstr(ret) );
+        LOG_E( PHY, "[UE %"PRIu8"] Frame %"PRIu32", subframe %u %s\n",
+               UE->Mod_id, proc->frame_rx, proc->subframe_tx,get_connectionloss_errstr(ret) );
     }
+
 #if UE_TIMING_TRACE
     stop_meas(&UE->generic_stat);
 #endif
 
-
     // Prepare the future Tx data
 
     if ((subframe_select( &UE->frame_parms, proc->subframe_tx) == SF_UL) ||
-	(UE->frame_parms.frame_type == FDD) )
-      if (UE->mode != loop_through_memory){
-
-	if ((UE_mac_inst[Mod_id].UE_mode[0] == PRACH) ) {
-
-	  // check if we have PRACH opportunity
-
-	  if (is_prach_subframe(&UE->frame_parms,proc->frame_tx, proc->subframe_tx)) {
-	    PRACH_RESOURCES_t *prach_resources = ue_get_rach(Mod_id, 0, proc->frame_tx, 0, proc->subframe_tx);
-	    if(prach_resources!=NULL) {
-	      fill_rach_indication_UE_MAC(Mod_id, proc->frame_tx ,proc->subframe_tx, UL_INFO, prach_resources->ra_PreambleIndex, prach_resources->ra_RNTI);
-	      Msg1_transmitted(Mod_id, 0, proc->frame_tx, 0);
-	      UE_mac_inst[Mod_id].UE_mode[0] = RA_RESPONSE;
-	    }
-
-	    //ue_prach_procedures(ue,proc,eNB_id,abstraction_flag,mode);
-	  }
-	} // mode is PRACH
-	// Substitute call to phy_procedures Tx with call to phy_stub functions in order to trigger
-	// UE Tx procedures directly at the MAC layer, based on the received ul_config requests from the vnf (eNB).
-	// Generate UL_indications which correspond to UL traffic.
-	if(ul_config_req!= NULL && ul_config_req->ul_config_request_body.ul_config_pdu_list != NULL){
-		//LOG_I(MAC, "UE_phy_stub_thread_rxn_txnp4 ul_config_req is not NULL \n");
-		ul_config_req_UE_MAC(ul_config_req, timer_frame, timer_subframe, Mod_id);
-		if(ul_config_req->ul_config_request_body.ul_config_pdu_list != NULL){
-			free(ul_config_req->ul_config_request_body.ul_config_pdu_list);
-			ul_config_req->ul_config_request_body.ul_config_pdu_list = NULL;
-		}
-		free(ul_config_req);
-		ul_config_req = NULL;
-	}
-	else if(ul_config_req!=NULL){
-		free(ul_config_req);
-		ul_config_req = NULL;
-	}
+        (UE->frame_parms.frame_type == FDD) )
+      if (UE->mode != loop_through_memory) {
+        if ((UE_mac_inst[Mod_id].UE_mode[0] == PRACH) ) {
+          // check if we have PRACH opportunity
+          if (is_prach_subframe(&UE->frame_parms,proc->frame_tx, proc->subframe_tx)) {
+            PRACH_RESOURCES_t *prach_resources = ue_get_rach(Mod_id, 0, proc->frame_tx, 0, proc->subframe_tx);
+
+            if(prach_resources!=NULL) {
+              fill_rach_indication_UE_MAC(Mod_id, proc->frame_tx,proc->subframe_tx, UL_INFO, prach_resources->ra_PreambleIndex, prach_resources->ra_RNTI);
+              Msg1_transmitted(Mod_id, 0, proc->frame_tx, 0);
+              UE_mac_inst[Mod_id].UE_mode[0] = RA_RESPONSE;
+            }
+
+            //ue_prach_procedures(ue,proc,eNB_id,abstraction_flag,mode);
+          }
+        } // mode is PRACH
+
+        // Substitute call to phy_procedures Tx with call to phy_stub functions in order to trigger
+        // UE Tx procedures directly at the MAC layer, based on the received ul_config requests from the vnf (eNB).
+        // Generate UL_indications which correspond to UL traffic.
+        if(ul_config_req!= NULL && ul_config_req->ul_config_request_body.ul_config_pdu_list != NULL) {
+          //LOG_I(MAC, "UE_phy_stub_thread_rxn_txnp4 ul_config_req is not NULL \n");
+          ul_config_req_UE_MAC(ul_config_req, timer_frame, timer_subframe, Mod_id);
+
+          if(ul_config_req->ul_config_request_body.ul_config_pdu_list != NULL) {
+            free(ul_config_req->ul_config_request_body.ul_config_pdu_list);
+            ul_config_req->ul_config_request_body.ul_config_pdu_list = NULL;
+          }
+
+          free(ul_config_req);
+          ul_config_req = NULL;
+        } else if(ul_config_req!=NULL) {
+          free(ul_config_req);
+          ul_config_req = NULL;
+        }
       }
 
     phy_procedures_UE_SL_RX(UE,proc);
-
   }
+
   // thread finished
   free(arg);
   return &UE_thread_rxtx_retval;
@@ -1528,39 +1493,34 @@ static void *UE_phy_stub_thread_rxn_txnp4(void *arg) {
  */
 
 void *UE_thread(void *arg) {
-
-
   PHY_VARS_UE *UE = (PHY_VARS_UE *) arg;
   //  int tx_enabled = 0;
   int dummy_rx[UE->frame_parms.nb_antennas_rx][UE->frame_parms.samples_per_tti] __attribute__((aligned(32)));
   openair0_timestamp timestamp,timestamp1;
-  void* rxp[NB_ANTENNAS_RX], *txp[NB_ANTENNAS_TX];
+  void *rxp[NB_ANTENNAS_RX], *txp[NB_ANTENNAS_TX];
   int start_rx_stream = 0;
   int i;
   int th_id;
-
   static uint8_t thread_idx = 0;
-
   cpu_set_t cpuset;
   CPU_ZERO(&cpuset);
+
   if ( threads.iq != -1 )
     CPU_SET(threads.iq, &cpuset);
-  init_thread(100000, 500000, FIFO_PRIORITY, &cpuset,
-	      "UHD Threads");
 
+  init_thread(100000, 500000, FIFO_PRIORITY, &cpuset,
+              "UHD Threads");
   /*
   while (sync_var<0)
     pthread_cond_wait(&sync_cond, &sync_mutex);
   pthread_mutex_unlock(&sync_mutex);
   */
-
   wait_sync("UE thread");
 #ifdef NAS_UE
   MessageDef *message_p;
   message_p = itti_alloc_new_message(TASK_NAS_UE, INITIALIZE_MESSAGE);
   itti_send_msg_to_task (TASK_NAS_UE, UE->Mod_id + NB_eNB_INST, message_p);
 #endif
-
   int sub_frame=-1;
   //int cumulated_shift=0;
 
@@ -1570,12 +1530,11 @@ void *UE_thread(void *arg) {
   }
 
   while (!oai_exit) {
-#if BASIC_SIMULATOR
-    while (!(UE->proc.instance_cnt_synch < 0)) {
-      printf("ue sync not ready\n");
-      usleep(500*1000);
-    }
-#endif
+    if (IS_SOFTMODEM_BASICSIM)
+      while (!(UE->proc.instance_cnt_synch < 0)) {
+        printf("ue sync not ready\n");
+        usleep(500*1000);
+      }
 
     AssertFatal ( 0== pthread_mutex_lock(&UE->proc.mutex_synch), "");
     int instance_cnt_synch = UE->proc.instance_cnt_synch;
@@ -1584,217 +1543,241 @@ void *UE_thread(void *arg) {
 
     if (is_synchronized == 0) {
       if (instance_cnt_synch < 0) {  // we can invoke the synch
-	// grab 10 ms of signal and wakeup synch thread
-	for (int i=0; i<UE->frame_parms.nb_antennas_rx; i++)
-	  rxp[i] = (void*)&UE->common_vars.rxdata[i][0];
-
-	if (UE->mode != loop_through_memory)
-	  AssertFatal( UE->frame_parms.samples_per_tti*10 ==
-		       UE->rfdevice.trx_read_func(&UE->rfdevice,
-						  &timestamp,
-						  rxp,
-						  UE->frame_parms.samples_per_tti*10,
-						  UE->frame_parms.nb_antennas_rx), "");
-	AssertFatal ( 0== pthread_mutex_lock(&UE->proc.mutex_synch), "");
-	instance_cnt_synch = ++UE->proc.instance_cnt_synch;
-	if (instance_cnt_synch == 0) {
-	  AssertFatal( 0 == pthread_cond_signal(&UE->proc.cond_synch), "");
-	} else {
-	  LOG_E( PHY, "[SCHED][UE] UE sync thread busy!!\n" );
-	  exit_fun("nothing to add");
-	}
-	AssertFatal ( 0== pthread_mutex_unlock(&UE->proc.mutex_synch), "");
+        // grab 10 ms of signal and wakeup synch thread
+        for (int i=0; i<UE->frame_parms.nb_antennas_rx; i++)
+          rxp[i] = (void *)&UE->common_vars.rxdata[i][0];
+
+        if (UE->mode != loop_through_memory)
+          AssertFatal( UE->frame_parms.samples_per_tti*10 ==
+                       UE->rfdevice.trx_read_func(&UE->rfdevice,
+                                                  &timestamp,
+                                                  rxp,
+                                                  UE->frame_parms.samples_per_tti*10,
+                                                  UE->frame_parms.nb_antennas_rx), "");
+
+        AssertFatal ( 0== pthread_mutex_lock(&UE->proc.mutex_synch), "");
+        instance_cnt_synch = ++UE->proc.instance_cnt_synch;
+
+        if (instance_cnt_synch == 0) {
+          AssertFatal( 0 == pthread_cond_signal(&UE->proc.cond_synch), "");
+        } else {
+          LOG_E( PHY, "[SCHED][UE] UE sync thread busy!!\n" );
+          exit_fun("nothing to add");
+        }
+
+        AssertFatal ( 0== pthread_mutex_unlock(&UE->proc.mutex_synch), "");
       } else {
 #if OAISIM
-	(void)dummy_rx; /* avoid gcc warnings */
-	usleep(500);
+        (void)dummy_rx; /* avoid gcc warnings */
+        usleep(500);
 #else
-	// grab 10 ms of signal into dummy buffer
-	if (UE->mode != loop_through_memory) {
-	  for (int i=0; i<UE->frame_parms.nb_antennas_rx; i++)
-	    rxp[i] = (void*)&dummy_rx[i][0];
-	  for (int sf=0; sf<10; sf++)
-	    //	    printf("Reading dummy sf %d\n",sf);
-	    UE->rfdevice.trx_read_func(&UE->rfdevice,
-				       &timestamp,
-				       rxp,
-				       UE->frame_parms.samples_per_tti,
-				       UE->frame_parms.nb_antennas_rx);
-	}
+
+        // grab 10 ms of signal into dummy buffer
+        if (UE->mode != loop_through_memory) {
+          for (int i=0; i<UE->frame_parms.nb_antennas_rx; i++)
+            rxp[i] = (void *)&dummy_rx[i][0];
+
+          for (int sf=0; sf<10; sf++)
+            //      printf("Reading dummy sf %d\n",sf);
+            UE->rfdevice.trx_read_func(&UE->rfdevice,
+                                       &timestamp,
+                                       rxp,
+                                       UE->frame_parms.samples_per_tti,
+                                       UE->frame_parms.nb_antennas_rx);
+        }
+
 #endif
-	}
-
-        } // UE->is_synchronized==0
-        else {
-            if (start_rx_stream==0) {
-                start_rx_stream=1;
-                if (UE->mode != loop_through_memory) {
-                    if (UE->no_timing_correction==0) {
-                        LOG_I(PHY,"Resynchronizing RX by %d samples (mode = %d)\n",UE->rx_offset,UE->mode);
-                        AssertFatal(UE->rx_offset ==
-                                    UE->rfdevice.trx_read_func(&UE->rfdevice,
-                                                               &timestamp,
-                                                               (void**)UE->common_vars.rxdata,
-                                                               UE->rx_offset,
-                                                               UE->frame_parms.nb_antennas_rx),"");
-                    }
-                    UE->rx_offset=0;
-                    UE->time_sync_cell=0;
-                    //UE->proc.proc_rxtx[0].frame_rx++;
-                    //UE->proc.proc_rxtx[1].frame_rx++;
-                    for (th_id=0; th_id < RX_NB_TH; th_id++) {
-                        UE->proc.proc_rxtx[th_id].frame_rx++;
-                    }
-
-                    // read in first symbol
-                    AssertFatal (UE->frame_parms.ofdm_symbol_size+UE->frame_parms.nb_prefix_samples0 ==
-                                 UE->rfdevice.trx_read_func(&UE->rfdevice,
-                                                            &timestamp,
-                                                            (void**)UE->common_vars.rxdata,
-                                                            UE->frame_parms.ofdm_symbol_size+UE->frame_parms.nb_prefix_samples0,
-                                                            UE->frame_parms.nb_antennas_rx),"");
-                    slot_fep(UE,0, 0, 0, 0, 0);
-                } //UE->mode != loop_through_memory
-                else
-                    rt_sleep_ns(1000*1000);
+      }
+    } // UE->is_synchronized==0
+    else {
+      if (start_rx_stream==0) {
+        start_rx_stream=1;
+
+        if (UE->mode != loop_through_memory) {
+          if (UE->no_timing_correction==0) {
+            LOG_I(PHY,"Resynchronizing RX by %d samples (mode = %d)\n",UE->rx_offset,UE->mode);
+            AssertFatal(UE->rx_offset ==
+                        UE->rfdevice.trx_read_func(&UE->rfdevice,
+                                                   &timestamp,
+                                                   (void **)UE->common_vars.rxdata,
+                                                   UE->rx_offset,
+                                                   UE->frame_parms.nb_antennas_rx),"");
+          }
+
+          UE->rx_offset=0;
+          UE->time_sync_cell=0;
+
+          //UE->proc.proc_rxtx[0].frame_rx++;
+          //UE->proc.proc_rxtx[1].frame_rx++;
+          for (th_id=0; th_id < RX_NB_TH; th_id++) {
+            UE->proc.proc_rxtx[th_id].frame_rx++;
+          }
+
+          // read in first symbol
+          AssertFatal (UE->frame_parms.ofdm_symbol_size+UE->frame_parms.nb_prefix_samples0 ==
+                       UE->rfdevice.trx_read_func(&UE->rfdevice,
+                                                  &timestamp,
+                                                  (void **)UE->common_vars.rxdata,
+                                                  UE->frame_parms.ofdm_symbol_size+UE->frame_parms.nb_prefix_samples0,
+                                                  UE->frame_parms.nb_antennas_rx),"");
+          slot_fep(UE,0, 0, 0, 0, 0);
+        } //UE->mode != loop_through_memory
+        else
+          rt_sleep_ns(1000*1000);
+      } else {
+        sub_frame++;
+        sub_frame%=10;
+        UE_rxtx_proc_t *proc = &UE->proc.proc_rxtx[thread_idx];
+        // update thread index for received subframe
+        UE->current_thread_id[sub_frame] = thread_idx;
+
+        if (IS_SOFTMODEM_BASICSIM || IS_SOFTMODEM_RFSIM ) {
+          int t;
+
+          for (t = 0; t < 2; t++) {
+            UE_rxtx_proc_t *proc = &UE->proc.proc_rxtx[t];
+            pthread_mutex_lock(&proc->mutex_rxtx);
+
+            while (proc->instance_cnt_rxtx >= 0) pthread_cond_wait( &proc->cond_rxtx, &proc->mutex_rxtx );
+
+            pthread_mutex_unlock(&proc->mutex_rxtx);
+          }
+        }
+
+        LOG_D(PHY,"Process Subframe %d thread Idx %d \n", sub_frame, UE->current_thread_id[sub_frame]);
+        thread_idx++;
+
+        if(thread_idx>=RX_NB_TH)
+          thread_idx = 0;
+
+        if (UE->mode != loop_through_memory) {
+          for (i=0; i<UE->frame_parms.nb_antennas_rx; i++)
+            rxp[i] = (void *)&UE->common_vars.rxdata[i][UE->frame_parms.ofdm_symbol_size+
+                     UE->frame_parms.nb_prefix_samples0+
+                     sub_frame*UE->frame_parms.samples_per_tti];
+
+          for (i=0; i<UE->frame_parms.nb_antennas_tx; i++)
+            txp[i] = (void *)&UE->common_vars.txdata[i][((sub_frame+2)%10)*UE->frame_parms.samples_per_tti];
+
+          int readBlockSize, writeBlockSize;
+
+          if (sub_frame<9) {
+            readBlockSize=UE->frame_parms.samples_per_tti;
+            writeBlockSize=UE->frame_parms.samples_per_tti;
+          } else {
+            // set TO compensation to zero
+            UE->rx_offset_diff = 0;
+
+            // compute TO compensation that should be applied for this frame
+
+            if (UE->no_timing_correction == 0) {
+              if ( UE->rx_offset < 5*UE->frame_parms.samples_per_tti  &&
+                   UE->rx_offset > 0 )
+                UE->rx_offset_diff = -1 ;
+
+              if ( UE->rx_offset > 5*UE->frame_parms.samples_per_tti &&
+                   UE->rx_offset < 10*UE->frame_parms.samples_per_tti )
+                UE->rx_offset_diff = 1;
+            }
+
+            LOG_D(PHY,"AbsSubframe %d.%d SET rx_off_diff to %d rx_offset %d \n",proc->frame_rx,sub_frame,UE->rx_offset_diff,UE->rx_offset);
+            readBlockSize=UE->frame_parms.samples_per_tti -
+                          UE->frame_parms.ofdm_symbol_size -
+                          UE->frame_parms.nb_prefix_samples0 -
+                          UE->rx_offset_diff;
+            writeBlockSize=UE->frame_parms.samples_per_tti -
+                           UE->rx_offset_diff;
+          }
+
+          AssertFatal(readBlockSize ==
+                      UE->rfdevice.trx_read_func(&UE->rfdevice,
+                                                 &timestamp,
+                                                 rxp,
+                                                 readBlockSize,
+                                                 UE->frame_parms.nb_antennas_rx),"");
+          AssertFatal( writeBlockSize ==
+                       UE->rfdevice.trx_write_func(&UE->rfdevice,
+                           timestamp+
+                           (2*UE->frame_parms.samples_per_tti) -
+                           UE->frame_parms.ofdm_symbol_size-UE->frame_parms.nb_prefix_samples0 -
+                           openair0_cfg[0].tx_sample_advance,
+                           txp,
+                           writeBlockSize,
+                           UE->frame_parms.nb_antennas_tx,
+                           1),"");
+
+          if( sub_frame==9) {
+            // read in first symbol of next frame and adjust for timing drift
+            int first_symbols=writeBlockSize-readBlockSize;
+
+            if ( first_symbols > 0 )
+              AssertFatal(first_symbols ==
+                          UE->rfdevice.trx_read_func(&UE->rfdevice,
+                                                     &timestamp1,
+                                                     (void **)UE->common_vars.rxdata,
+                                                     first_symbols,
+                                                     UE->frame_parms.nb_antennas_rx),"");
+
+            if ( first_symbols <0 )
+              LOG_E(PHY,"can't compensate: diff =%d\n", first_symbols);
+          }
+
+          pickTime(gotIQs);
+          struct timespec tv= {0};
+          tv.tv_nsec=10*1000;
 
+          if( IS_SOFTMODEM_BASICSIM || IS_SOFTMODEM_RFSIM)
+            tv.tv_sec=INT_MAX;
+
+          // operate on thread sf mod 2
+          if (pthread_mutex_timedlock(&proc->mutex_rxtx, &tv) !=0) {
+            if ( errno == ETIMEDOUT) {
+              LOG_E(PHY,"Missed real time\n");
+              continue;
             } else {
-                sub_frame++;
-                sub_frame%=10;
-                UE_rxtx_proc_t *proc = &UE->proc.proc_rxtx[thread_idx];
-                // update thread index for received subframe
-                UE->current_thread_id[sub_frame] = thread_idx;
-
-#if BASIC_SIMULATOR
-                {
-                  int t;
-                  for (t = 0; t < 2; t++) {
-                        UE_rxtx_proc_t *proc = &UE->proc.proc_rxtx[t];
-                        pthread_mutex_lock(&proc->mutex_rxtx);
-                        while (proc->instance_cnt_rxtx >= 0) pthread_cond_wait( &proc->cond_rxtx, &proc->mutex_rxtx );
-                        pthread_mutex_unlock(&proc->mutex_rxtx);
-                  }
-                }
-#endif
-                LOG_D(PHY,"Process Subframe %d thread Idx %d \n", sub_frame, UE->current_thread_id[sub_frame]);
-
-                thread_idx++;
-                if(thread_idx>=RX_NB_TH)
-                    thread_idx = 0;
-
-
-                if (UE->mode != loop_through_memory) {
-                    for (i=0; i<UE->frame_parms.nb_antennas_rx; i++)
-                        rxp[i] = (void*)&UE->common_vars.rxdata[i][UE->frame_parms.ofdm_symbol_size+
-                                 UE->frame_parms.nb_prefix_samples0+
-                                 sub_frame*UE->frame_parms.samples_per_tti];
-                    for (i=0; i<UE->frame_parms.nb_antennas_tx; i++)
-                        txp[i] = (void*)&UE->common_vars.txdata[i][((sub_frame+2)%10)*UE->frame_parms.samples_per_tti];
-
-                    int readBlockSize, writeBlockSize;
-                    if (sub_frame<9) {
-                        readBlockSize=UE->frame_parms.samples_per_tti;
-                        writeBlockSize=UE->frame_parms.samples_per_tti;
-                    } else {
-                        // set TO compensation to zero
-
-                        UE->rx_offset_diff = 0;
-
-                        // compute TO compensation that should be applied for this frame
-
-			if (UE->no_timing_correction == 0) {
-			  if ( UE->rx_offset < 5*UE->frame_parms.samples_per_tti  &&
-			       UE->rx_offset > 0 )
-                            UE->rx_offset_diff = -1 ;
-			  if ( UE->rx_offset > 5*UE->frame_parms.samples_per_tti &&
-			       UE->rx_offset < 10*UE->frame_parms.samples_per_tti )
-                            UE->rx_offset_diff = 1;
-			}
-
-                        LOG_D(PHY,"AbsSubframe %d.%d SET rx_off_diff to %d rx_offset %d \n",proc->frame_rx,sub_frame,UE->rx_offset_diff,UE->rx_offset);
-                        readBlockSize=UE->frame_parms.samples_per_tti -
-                                      UE->frame_parms.ofdm_symbol_size -
-                                      UE->frame_parms.nb_prefix_samples0 -
-                                      UE->rx_offset_diff;
-                        writeBlockSize=UE->frame_parms.samples_per_tti -
-                                       UE->rx_offset_diff;
-                    }
-
-                    AssertFatal(readBlockSize ==
-                                UE->rfdevice.trx_read_func(&UE->rfdevice,
-                                                           &timestamp,
-                                                           rxp,
-                                                           readBlockSize,
-                                                           UE->frame_parms.nb_antennas_rx),"");
-                    AssertFatal( writeBlockSize ==
-                                 UE->rfdevice.trx_write_func(&UE->rfdevice,
-                                         timestamp+
-                                         (2*UE->frame_parms.samples_per_tti) -
-                                         UE->frame_parms.ofdm_symbol_size-UE->frame_parms.nb_prefix_samples0 -
-                                         openair0_cfg[0].tx_sample_advance,
-                                         txp,
-                                         writeBlockSize,
-                                         UE->frame_parms.nb_antennas_tx,
-                                         1),"");
-                    if( sub_frame==9) {
-                        // read in first symbol of next frame and adjust for timing drift
-                        int first_symbols=writeBlockSize-readBlockSize;
-                        if ( first_symbols > 0 )
-                            AssertFatal(first_symbols ==
-                                        UE->rfdevice.trx_read_func(&UE->rfdevice,
-                                                                   &timestamp1,
-                                                                   (void**)UE->common_vars.rxdata,
-                                                                   first_symbols,
-                                                                   UE->frame_parms.nb_antennas_rx),"");
-                        if ( first_symbols <0 )
-                            LOG_E(PHY,"can't compensate: diff =%d\n", first_symbols);
-                    }
-                    pickTime(gotIQs);
-                    // operate on thread sf mod 2
-                    AssertFatal(pthread_mutex_lock(&proc->mutex_rxtx) ==0,"");
-                    if(sub_frame == 0) {
-                        //UE->proc.proc_rxtx[0].frame_rx++;
-                        //UE->proc.proc_rxtx[1].frame_rx++;
-                        for (th_id=0; th_id < RX_NB_TH; th_id++) {
-                            UE->proc.proc_rxtx[th_id].frame_rx++;
-                        }
-                    }
-                    //UE->proc.proc_rxtx[0].gotIQs=readTime(gotIQs);
-                    //UE->proc.proc_rxtx[1].gotIQs=readTime(gotIQs);
-                    for (th_id=0; th_id < RX_NB_TH; th_id++) {
-                        UE->proc.proc_rxtx[th_id].gotIQs=readTime(gotIQs);
-                    }
-                    proc->subframe_rx=sub_frame;
-                    proc->subframe_tx=(sub_frame+4)%10;
-                    proc->frame_tx = proc->frame_rx + (proc->subframe_rx>5?1:0);
-                    proc->timestamp_tx = timestamp+
-                                         (4*UE->frame_parms.samples_per_tti)-
-                                         UE->frame_parms.ofdm_symbol_size-UE->frame_parms.nb_prefix_samples0;
-
-                    proc->instance_cnt_rxtx++;
-                    LOG_D( PHY, "[SCHED][UE %d] UE RX instance_cnt_rxtx %d subframe %d !!\n", UE->Mod_id, proc->instance_cnt_rxtx,proc->subframe_rx);
-                    if (proc->instance_cnt_rxtx != 0) {
-                      LOG_E( PHY, "[SCHED][UE %d] UE RX thread busy (IC %d)!!\n", UE->Mod_id, proc->instance_cnt_rxtx);
-                      if (proc->instance_cnt_rxtx > 2)
-                        exit_fun("instance_cnt_rxtx > 2");
-                    }
-
-                    AssertFatal (pthread_cond_signal(&proc->cond_rxtx) ==0 ,"");
-                    AssertFatal(pthread_mutex_unlock(&proc->mutex_rxtx) ==0,"");
-                    initRefTimes(t1);
-                    initStaticTime(lastTime);
-                    updateTimes(lastTime, &t1, 20000, "Delay between two IQ acquisitions (case 1)");
-                    pickStaticTime(lastTime);
+              LOG_E(PHY,"System error\n");
+              abort();
+            }
+          }
 
-                } else {
-                    printf("Processing subframe %d",proc->subframe_rx);
-                    getchar();
-                }
-            } // start_rx_stream==1
-        } // UE->is_synchronized==1
+          //usleep(3000);
+          if(sub_frame == 0) {
+            //UE->proc.proc_rxtx[0].frame_rx++;
+            //UE->proc.proc_rxtx[1].frame_rx++;
+            for (th_id=0; th_id < RX_NB_TH; th_id++) {
+              UE->proc.proc_rxtx[th_id].frame_rx++;
+            }
+          }
+
+          //UE->proc.proc_rxtx[0].gotIQs=readTime(gotIQs);
+          //UE->proc.proc_rxtx[1].gotIQs=readTime(gotIQs);
+          for (th_id=0; th_id < RX_NB_TH; th_id++) {
+            UE->proc.proc_rxtx[th_id].gotIQs=readTime(gotIQs);
+          }
 
-    } // while !oai_exit
-    return NULL;
+          proc->subframe_rx=sub_frame;
+          proc->subframe_tx=(sub_frame+4)%10;
+          proc->frame_tx = proc->frame_rx + (proc->subframe_rx>5?1:0);
+          proc->timestamp_tx = timestamp+
+                               (4*UE->frame_parms.samples_per_tti)-
+                               UE->frame_parms.ofdm_symbol_size-UE->frame_parms.nb_prefix_samples0;
+          proc->instance_cnt_rxtx++;
+          LOG_D( PHY, "[SCHED][UE %d] UE RX instance_cnt_rxtx %d subframe %d !!\n", UE->Mod_id, proc->instance_cnt_rxtx,proc->subframe_rx);
+          AssertFatal (pthread_cond_signal(&proc->cond_rxtx) ==0,"");
+          AssertFatal(pthread_mutex_unlock(&proc->mutex_rxtx) ==0,"");
+          initRefTimes(t1);
+          initStaticTime(lastTime);
+          updateTimes(lastTime, &t1, 20000, "Delay between two IQ acquisitions (case 1)");
+          pickStaticTime(lastTime);
+        } else {
+          printf("Processing subframe %d",proc->subframe_rx);
+          getchar();
+        }
+      } // start_rx_stream==1
+    } // UE->is_synchronized==1
+  } // while !oai_exit
+
+  return NULL;
 }
 
 
@@ -1813,28 +1796,26 @@ void *UE_thread(void *arg) {
 void init_UE_threads(int inst) {
   struct rx_tx_thread_data *rtd;
   PHY_VARS_UE *UE;
-
   AssertFatal(PHY_vars_UE_g!=NULL,"PHY_vars_UE_g is NULL\n");
   AssertFatal(PHY_vars_UE_g[inst]!=NULL,"PHY_vars_UE_g[inst] is NULL\n");
   AssertFatal(PHY_vars_UE_g[inst][0]!=NULL,"PHY_vars_UE_g[inst][0] is NULL\n");
   UE = PHY_vars_UE_g[inst][0];
-
   pthread_attr_init (&UE->proc.attr_ue);
   pthread_attr_setstacksize(&UE->proc.attr_ue,8192);//5*PTHREAD_STACK_MIN);
-
   pthread_mutex_init(&UE->proc.mutex_synch,NULL);
   pthread_cond_init(&UE->proc.cond_synch,NULL);
   UE->proc.instance_cnt_synch = -1;
   UE->is_synchronized = 0;
-
   // the threads are not yet active, therefore access is allowed without locking
   int nb_threads=RX_NB_TH;
+
   for (int i=0; i<nb_threads; i++) {
     rtd = calloc(1, sizeof(struct rx_tx_thread_data));
+
     if (rtd == NULL) abort();
+
     rtd->UE = UE;
     rtd->proc = &UE->proc.proc_rxtx[i];
-
     pthread_mutex_init(&UE->proc.proc_rxtx[i].mutex_rxtx,NULL);
     pthread_cond_init(&UE->proc.proc_rxtx[i].cond_rxtx,NULL);
     UE->proc.proc_rxtx[i].instance_cnt_rxtx = -1;
@@ -1842,19 +1823,17 @@ void init_UE_threads(int inst) {
     UE->proc.proc_rxtx[i].sub_frame_step=nb_threads;
     printf("Init_UE_threads rtd %d proc %d nb_threads %d i %d\n",rtd->proc->sub_frame_start, UE->proc.proc_rxtx[i].sub_frame_start,nb_threads, i);
     pthread_create(&UE->proc.proc_rxtx[i].pthread_rxtx, NULL, UE_thread_rxn_txnp4, rtd);
-
 #ifdef UE_SLOT_PARALLELISATION
     //pthread_mutex_init(&UE->proc.proc_rxtx[i].mutex_slot0_dl_processing,NULL);
     //pthread_cond_init(&UE->proc.proc_rxtx[i].cond_slot0_dl_processing,NULL);
     //pthread_create(&UE->proc.proc_rxtx[i].pthread_slot0_dl_processing,NULL,UE_thread_slot0_dl_processing, rtd);
-
     pthread_mutex_init(&UE->proc.proc_rxtx[i].mutex_slot1_dl_processing,NULL);
     pthread_cond_init(&UE->proc.proc_rxtx[i].cond_slot1_dl_processing,NULL);
     pthread_create(&UE->proc.proc_rxtx[i].pthread_slot1_dl_processing,NULL,UE_thread_slot1_dl_processing, rtd);
 #endif
-
   }
-  pthread_create(&UE->proc.pthread_synch,NULL,UE_thread_synch,(void*)UE);
+
+  pthread_create(&UE->proc.pthread_synch,NULL,UE_thread_synch,(void *)UE);
 }
 
 
@@ -1874,40 +1853,42 @@ void init_UE_single_thread_stub(int nb_inst) {
   struct rx_tx_thread_data *rtd;
   PHY_VARS_UE *UE;
 
-  for (int i=0; i<nb_inst; i++){
-	  AssertFatal(PHY_vars_UE_g!=NULL,"PHY_vars_UE_g is NULL\n");
-	  AssertFatal(PHY_vars_UE_g[i]!=NULL,"PHY_vars_UE_g[inst] is NULL\n");
-	  AssertFatal(PHY_vars_UE_g[i][0]!=NULL,"PHY_vars_UE_g[inst][0] is NULL\n");
-	  if(nfapi_mode == 3){
+  for (int i=0; i<nb_inst; i++) {
+    AssertFatal(PHY_vars_UE_g!=NULL,"PHY_vars_UE_g is NULL\n");
+    AssertFatal(PHY_vars_UE_g[i]!=NULL,"PHY_vars_UE_g[inst] is NULL\n");
+    AssertFatal(PHY_vars_UE_g[i][0]!=NULL,"PHY_vars_UE_g[inst][0] is NULL\n");
+
+    if(nfapi_mode == 3) {
 #ifdef NAS_UE
-          MessageDef *message_p;
-          message_p = itti_alloc_new_message(TASK_NAS_UE, INITIALIZE_MESSAGE);
-         itti_send_msg_to_task (TASK_NAS_UE, i + NB_eNB_INST, message_p);
+      MessageDef *message_p;
+      message_p = itti_alloc_new_message(TASK_NAS_UE, INITIALIZE_MESSAGE);
+      itti_send_msg_to_task (TASK_NAS_UE, i + NB_eNB_INST, message_p);
 #endif
-	  }
+    }
   }
-  UE = PHY_vars_UE_g[0][0];
 
+  UE = PHY_vars_UE_g[0][0];
   pthread_attr_init (&UE->proc.attr_ue);
   pthread_attr_setstacksize(&UE->proc.attr_ue,8192);//5*PTHREAD_STACK_MIN);
-
   // Don't need synch for phy_stub mode
   //pthread_mutex_init(&UE->proc.mutex_synch,NULL);
   //pthread_cond_init(&UE->proc.cond_synch,NULL);
-
   // the threads are not yet active, therefore access is allowed without locking
   // In phy_stub_UE mode due to less heavy processing operations we don't need two threads
   //int nb_threads=RX_NB_TH;
   int nb_threads=1;
-  for(uint16_t ue_thread_id = 0;ue_thread_id < NB_THREAD_INST;ue_thread_id++){
+
+  for(uint16_t ue_thread_id = 0; ue_thread_id < NB_THREAD_INST; ue_thread_id++) {
     UE = PHY_vars_UE_g[ue_thread_id][0];
+
     for (int i=0; i<nb_threads; i++) {
       rtd = calloc(1, sizeof(struct rx_tx_thread_data));
+
       if (rtd == NULL) abort();
+
       rtd->UE = UE;
       rtd->proc = &UE->proc.proc_rxtx[i];
       rtd->ue_thread_id = ue_thread_id;
-
       pthread_mutex_init(&UE->proc.proc_rxtx[i].mutex_rxtx,NULL);
       pthread_cond_init(&UE->proc.proc_rxtx[i].cond_rxtx,NULL);
       UE->proc.proc_rxtx[i].sub_frame_start=i;
@@ -1916,6 +1897,7 @@ void init_UE_single_thread_stub(int nb_inst) {
       pthread_create(&UE->proc.proc_rxtx[i].pthread_rxtx, NULL, UE_phy_stub_single_thread_rxn_txnp4, rtd);
     }
   }
+
   // Remove thread for UE_sync in phy_stub_UE mode.
   //pthread_create(&UE->proc.pthread_synch,NULL,UE_thread_synch,(void*)UE);
 }
@@ -1937,38 +1919,35 @@ void init_UE_single_thread_stub(int nb_inst) {
 void init_UE_threads_stub(int inst) {
   struct rx_tx_thread_data *rtd;
   PHY_VARS_UE *UE;
-
   AssertFatal(PHY_vars_UE_g!=NULL,"PHY_vars_UE_g is NULL\n");
   AssertFatal(PHY_vars_UE_g[inst]!=NULL,"PHY_vars_UE_g[inst] is NULL\n");
   AssertFatal(PHY_vars_UE_g[inst][0]!=NULL,"PHY_vars_UE_g[inst][0] is NULL\n");
   UE = PHY_vars_UE_g[inst][0];
-
   pthread_attr_init (&UE->proc.attr_ue);
   pthread_attr_setstacksize(&UE->proc.attr_ue,8192);//5*PTHREAD_STACK_MIN);
-
   // Don't need synch for phy_stub mode
   //pthread_mutex_init(&UE->proc.mutex_synch,NULL);
   //pthread_cond_init(&UE->proc.cond_synch,NULL);
-
   // the threads are not yet active, therefore access is allowed without locking
   // In phy_stub_UE mode due to less heavy processing operations we don't need two threads
   //int nb_threads=RX_NB_TH;
   int nb_threads=1;
+
   for (int i=0; i<nb_threads; i++) {
     rtd = calloc(1, sizeof(struct rx_tx_thread_data));
+
     if (rtd == NULL) abort();
+
     rtd->UE = UE;
     rtd->proc = &UE->proc.proc_rxtx[i];
-
     pthread_mutex_init(&UE->proc.proc_rxtx[i].mutex_rxtx,NULL);
     pthread_cond_init(&UE->proc.proc_rxtx[i].cond_rxtx,NULL);
     UE->proc.proc_rxtx[i].sub_frame_start=i;
     UE->proc.proc_rxtx[i].sub_frame_step=nb_threads;
     printf("Init_UE_threads rtd %d proc %d nb_threads %d i %d\n",rtd->proc->sub_frame_start, UE->proc.proc_rxtx[i].sub_frame_start,nb_threads, i);
     pthread_create(&UE->proc.proc_rxtx[i].pthread_rxtx, NULL, UE_phy_stub_thread_rxn_txnp4, rtd);
-
-
   }
+
   // Remove thread for UE_sync in phy_stub_UE mode.
   //pthread_create(&UE->proc.pthread_synch,NULL,UE_thread_synch,(void*)UE);
 }
@@ -1978,61 +1957,54 @@ void init_UE_threads_stub(int inst) {
 
 #ifdef OPENAIR2
 void fill_ue_band_info(void) {
-
   LTE_UE_EUTRA_Capability_t *UE_EUTRA_Capability = UE_rrc_inst[0].UECap->UE_EUTRA_Capability;
   int i,j;
-
   bands_to_scan.nbands = UE_EUTRA_Capability->rf_Parameters.supportedBandListEUTRA.list.count;
 
   for (i=0; i<bands_to_scan.nbands; i++) {
-
     for (j=0; j<sizeof (eutra_bands) / sizeof (eutra_bands[0]); j++)
       if (eutra_bands[j].band == UE_EUTRA_Capability->rf_Parameters.supportedBandListEUTRA.list.array[i]->bandEUTRA) {
-	memcpy(&bands_to_scan.band_info[i],
-	       &eutra_bands[j],
-	       sizeof(eutra_band_t));
-
-	printf("Band %d (%lu) : DL %u..%u Hz, UL %u..%u Hz, Duplex %s \n",
-	       bands_to_scan.band_info[i].band,
-	       UE_EUTRA_Capability->rf_Parameters.supportedBandListEUTRA.list.array[i]->bandEUTRA,
-	       bands_to_scan.band_info[i].dl_min,
-	       bands_to_scan.band_info[i].dl_max,
-	       bands_to_scan.band_info[i].ul_min,
-	       bands_to_scan.band_info[i].ul_max,
-	       (bands_to_scan.band_info[i].frame_type==FDD) ? "FDD" : "TDD");
-	break;
+        memcpy(&bands_to_scan.band_info[i],
+               &eutra_bands[j],
+               sizeof(eutra_band_t));
+        printf("Band %d (%lu) : DL %u..%u Hz, UL %u..%u Hz, Duplex %s \n",
+               bands_to_scan.band_info[i].band,
+               UE_EUTRA_Capability->rf_Parameters.supportedBandListEUTRA.list.array[i]->bandEUTRA,
+               bands_to_scan.band_info[i].dl_min,
+               bands_to_scan.band_info[i].dl_max,
+               bands_to_scan.band_info[i].ul_min,
+               bands_to_scan.band_info[i].ul_max,
+               (bands_to_scan.band_info[i].frame_type==FDD) ? "FDD" : "TDD");
+        break;
       }
   }
 }
 #endif
 
 int setup_ue_buffers(PHY_VARS_UE **phy_vars_ue, openair0_config_t *openair0_cfg) {
-
   int i, CC_id;
   LTE_DL_FRAME_PARMS *frame_parms;
 
   for (CC_id=0; CC_id<MAX_NUM_CCs; CC_id++) {
-
     AssertFatal( phy_vars_ue[CC_id] !=0, "");
     frame_parms = &(phy_vars_ue[CC_id]->frame_parms);
-
     // replace RX signal buffers with mmaped HW versions
-    rxdata = (int32_t**)malloc16( frame_parms->nb_antennas_rx*sizeof(int32_t*) );
-    txdata = (int32_t**)malloc16( frame_parms->nb_antennas_tx*sizeof(int32_t*) );
+    rxdata = (int32_t **)malloc16( frame_parms->nb_antennas_rx*sizeof(int32_t *) );
+    txdata = (int32_t **)malloc16( frame_parms->nb_antennas_tx*sizeof(int32_t *) );
 
     for (i=0; i<frame_parms->nb_antennas_rx; i++) {
       LOG_I(PHY, "Mapping UE CC_id %d, rx_ant %d, freq %u on card %d, chain %d\n",
-	    CC_id, i, downlink_frequency[CC_id][i], phy_vars_ue[CC_id]->rf_map.card, (phy_vars_ue[CC_id]->rf_map.chain)+i );
+            CC_id, i, downlink_frequency[CC_id][i], phy_vars_ue[CC_id]->rf_map.card, (phy_vars_ue[CC_id]->rf_map.chain)+i );
       free( phy_vars_ue[CC_id]->common_vars.rxdata[i] );
-      rxdata[i] = (int32_t*)malloc16_clear( 307200*sizeof(int32_t) );
+      rxdata[i] = (int32_t *)malloc16_clear( 307200*sizeof(int32_t) );
       phy_vars_ue[CC_id]->common_vars.rxdata[i] = rxdata[i]; // what about the "-N_TA_offset" ? // N_TA offset for TDD
     }
 
     for (i=0; i<frame_parms->nb_antennas_tx; i++) {
       LOG_I(PHY, "Mapping UE CC_id %d, tx_ant %d, freq %u on card %d, chain %d\n",
-	    CC_id, i, downlink_frequency[CC_id][i], phy_vars_ue[CC_id]->rf_map.card, (phy_vars_ue[CC_id]->rf_map.chain)+i );
+            CC_id, i, downlink_frequency[CC_id][i], phy_vars_ue[CC_id]->rf_map.card, (phy_vars_ue[CC_id]->rf_map.chain)+i );
       free( phy_vars_ue[CC_id]->common_vars.txdata[i] );
-      txdata[i] = (int32_t*)malloc16_clear( 307200*sizeof(int32_t) );
+      txdata[i] = (int32_t *)malloc16_clear( 307200*sizeof(int32_t) );
       phy_vars_ue[CC_id]->common_vars.txdata[i] = txdata[i];
     }
 
@@ -2041,6 +2013,7 @@ int setup_ue_buffers(PHY_VARS_UE **phy_vars_ue, openair0_config_t *openair0_cfg)
     // be careful when releasing memory!
     // because no "release_ue_buffers"-function is available, at least rxdata and txdata memory will leak (only some bytes)
   }
+
   return 0;
 }
 
@@ -2053,7 +2026,7 @@ int setup_ue_buffers(PHY_VARS_UE **phy_vars_ue, openair0_config_t *openair0_cfg)
 // playing the role of nfapi-pnf.
 
 //02/02/2018
-static void* timer_thread( void* param ) {
+static void *timer_thread( void *param ) {
   thread_top_init("timer_thread",1,870000L,1000000L,1000000L);
   timer_subframe =9;
   timer_frame    =1023;
@@ -2063,43 +2036,48 @@ static void* timer_thread( void* param ) {
   UE = PHY_vars_UE_g[0][0];
   //double t_diff;
   int external_timer = 0;
-
-
   wait_sync("timer_thread");
-
   opp_enabled = 1;
 
   // first check if we are receiving timing indications
   if(nfapi_mode==4) {
-  usleep(10000);
-  if (UE->instance_cnt_timer > 0) {
-    external_timer = 1;
-    int absSFm1 = ((emulator_absSF+10239)%10240);
-    timer_frame = absSFm1/10;
-    timer_subframe = absSFm1%10;
-    pthread_mutex_lock(&UE->timer_mutex);
-    UE->instance_cnt_timer = -1;
-    pthread_mutex_unlock(&UE->timer_mutex);
-    LOG_I(PHY,"Running with external timer\n");
-  }
-  else LOG_I(PHY,"Running with internal timer\n");
+    usleep(10000);
+
+    if (UE->instance_cnt_timer > 0) {
+      external_timer = 1;
+      int absSFm1 = ((emulator_absSF+10239)%10240);
+      timer_frame = absSFm1/10;
+      timer_subframe = absSFm1%10;
+      pthread_mutex_lock(&UE->timer_mutex);
+      UE->instance_cnt_timer = -1;
+      pthread_mutex_unlock(&UE->timer_mutex);
+      LOG_I(PHY,"Running with external timer\n");
+    } else LOG_I(PHY,"Running with internal timer\n");
   }
 
   struct timespec t_start;
+
   struct timespec t_now;
+
   struct timespec t_sleep;
+
   uint64_t T_0;
+
   uint64_t T_now;
+
   uint64_t T_next_SF;
+
   uint64_t T_sleep;
+
   uint64_t sf_cnt = 0; //Total Subframe counter
 
   clock_gettime(CLOCK_MONOTONIC, &t_start);
+
   T_0 = (uint64_t) t_start.tv_sec*1000000000 + t_start.tv_nsec;
+
   LOG_D(MAC, "timer_thread(), T_0 value: %" PRId64 "\n", T_0);
 
   while (!oai_exit) {
-
     // these are local subframe/frame counters to check that we are in synch with the fronthaul timing.
     // They are set on the first rx/tx in the underly FH routines.
     if (timer_subframe==9) {
@@ -2113,74 +2091,72 @@ static void* timer_thread( void* param ) {
     //AssertFatal( 0 == pthread_cond_signal(&phy_stub_ticking->cond_ticking), "");
     AssertFatal(pthread_mutex_lock(&phy_stub_ticking->mutex_ticking) ==0,"");
     phy_stub_ticking->ticking_var++;
+
     // This should probably be a call to pthread_cond_broadcast when we introduce support for multiple UEs (threads)
-    if(phy_stub_ticking->ticking_var == 0){
+    if(phy_stub_ticking->ticking_var == 0) {
       //AssertFatal(phy_stub_ticking->ticking_var == 0,"phy_stub_ticking->ticking_var = %d",
-      		//phy_stub_ticking->ticking_var);
+      //phy_stub_ticking->ticking_var);
       if (pthread_cond_signal(&phy_stub_ticking->cond_ticking) != 0) {
-	//LOG_E( PHY, "[SCHED][UE %d] ERROR pthread_cond_signal for UE RX thread\n", UE->Mod_id);
-	LOG_E( PHY, "timer_thread ERROR pthread_cond_signal for UE_thread\n");
-	exit_fun("nothing to add");
+        //LOG_E( PHY, "[SCHED][UE %d] ERROR pthread_cond_signal for UE RX thread\n", UE->Mod_id);
+        LOG_E( PHY, "timer_thread ERROR pthread_cond_signal for UE_thread\n");
+        exit_fun("nothing to add");
       }
-    }
-    else
-    	LOG_D(MAC, "timer_thread() Timing problem! ticking_var value:%d \n \n \n", phy_stub_ticking->ticking_var);
+    } else
+      LOG_D(MAC, "timer_thread() Timing problem! ticking_var value:%d \n \n \n", phy_stub_ticking->ticking_var);
 
     AssertFatal(pthread_mutex_unlock(&phy_stub_ticking->mutex_ticking) ==0,"");
     start_meas(&UE->timer_stats);
 
-
     //clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); // get initial time-stamp
     if (external_timer == 0) {
-    	clock_gettime(CLOCK_MONOTONIC, &t_now);
-    	sf_cnt++;
-    	T_next_SF = T_0 + sf_cnt*1000000;
-    	T_now =(uint64_t) t_now.tv_sec*1000000000 + t_now.tv_nsec;
-    	if(T_now > T_next_SF){
-    		t_sleep.tv_sec =0;
-    	    t_sleep.tv_nsec =0;
-    	}
-    	else{
-    		T_sleep = T_next_SF - T_now;
-    		t_sleep.tv_sec =0;
-    		t_sleep.tv_nsec = (__syscall_slong_t) T_sleep;
-    	}
+      clock_gettime(CLOCK_MONOTONIC, &t_now);
+      sf_cnt++;
+      T_next_SF = T_0 + sf_cnt*1000000;
+      T_now =(uint64_t) t_now.tv_sec*1000000000 + t_now.tv_nsec;
+
+      if(T_now > T_next_SF) {
+        t_sleep.tv_sec =0;
+        t_sleep.tv_nsec =0;
+      } else {
+        T_sleep = T_next_SF - T_now;
+        t_sleep.tv_sec =0;
+        t_sleep.tv_nsec = (__syscall_slong_t) T_sleep;
+      }
+
       nanosleep(&t_sleep, (struct timespec *)NULL);
       UE_tport_t pdu;
       pdu.header.packet_type = TTI_SYNC;
       pdu.header.absSF = (timer_frame*10)+timer_subframe;
-      if (nfapi_mode!=3){
-      multicast_link_write_sock(0,
-				(char *)&pdu,
-				sizeof(UE_tport_header_t));
-      }
 
-    }
-    else {
+      if (nfapi_mode!=3) {
+        multicast_link_write_sock(0,
+                                  (char *)&pdu,
+                                  sizeof(UE_tport_header_t));
+      }
+    } else {
       wait_on_condition(&UE->timer_mutex,&UE->timer_cond,&UE->instance_cnt_timer,"timer_thread");
       release_thread(&UE->timer_mutex,&UE->instance_cnt_timer,"timer_thread");
     }
 
-
     /*stop_meas(&UE->timer_stats);
     t_diff = get_time_meas_us(&UE->timer_stats);
 
     stop_meas(&UE->timer_stats);
     t_diff = get_time_meas_us(&UE->timer_stats);*/
   }
+
   free(phy_stub_ticking);
   pthread_cond_destroy(&phy_stub_ticking->cond_ticking);
   pthread_mutex_destroy(&phy_stub_ticking->mutex_ticking);
   return 0;
-
 }
 
 
 
 int init_timer_thread(void) {
   //PHY_VARS_UE *UE=PHY_vars_UE_g[0];
-	PHY_VARS_UE *UE=PHY_vars_UE_g[0][0];
-  phy_stub_ticking = (SF_ticking*)malloc(sizeof(SF_ticking));
+  PHY_VARS_UE *UE=PHY_vars_UE_g[0][0];
+  phy_stub_ticking = (SF_ticking *)malloc(sizeof(SF_ticking));
   pthread_mutex_init(&UE->timer_mutex,NULL);
   pthread_cond_init(&UE->timer_cond,NULL);
   UE->instance_cnt_timer = -1;
@@ -2197,8 +2173,7 @@ int init_timer_thread(void) {
 /* HACK: this function is needed to compile the UE
  * fix it somehow
  */
-int8_t find_dlsch(uint16_t rnti, PHY_VARS_eNB *eNB,find_type_t type)
-{
+int8_t find_dlsch(uint16_t rnti, PHY_VARS_eNB *eNB,find_type_t type) {
   printf("you cannot read this\n");
   abort();
 }
diff --git a/targets/RT/USER/lte-uesoftmodem.c b/targets/RT/USER/lte-uesoftmodem.c
index b19d440b0d09a10c12150e95557b89a0f76aecb4..f327b83cf9be31c61b32d49c80607cba563fafaf 100644
--- a/targets/RT/USER/lte-uesoftmodem.c
+++ b/targets/RT/USER/lte-uesoftmodem.c
@@ -441,10 +441,6 @@ static void get_options(void) {
 
   if (dumpframe  > 0)  mode = rx_dump_frame;
 
-# if BASIC_SIMULATOR
-  set_softmodem_optmask(SOFTMODEM_BASICSIM_BIT); //this BASIC_SIMULATOR should be a config option
-# endif
-
   for (CC_id=0; CC_id<MAX_NUM_CCs; CC_id++) {
     frame_parms[CC_id]->dl_CarrierFreq = downlink_frequency[0][0];
   }
@@ -755,7 +751,6 @@ int main( int argc, char **argv ) {
   cpuf=get_cpu_freq_GHz();
   pthread_cond_init(&sync_cond,NULL);
   pthread_mutex_init(&sync_mutex, NULL);
-#if defined(ENABLE_ITTI)
   printf("ITTI init\n");
   itti_init(TASK_MAX, THREAD_MAX, MESSAGES_ID_MAX, tasks_info, messages_info);
 
@@ -765,22 +760,22 @@ int main( int argc, char **argv ) {
   }
 
   MSC_INIT(MSC_E_UTRAN, THREAD_MAX+TASK_MAX);
-#endif
   init_opt();
-  uint32_t pdcp_initmask = ((!IS_SOFTMODEM_NOS1) || IS_SOFTMODEM_NOKRNMOD)? LINK_ENB_PDCP_TO_GTPV1U_BIT : (LINK_ENB_PDCP_TO_GTPV1U_BIT | PDCP_USE_NETLINK_BIT | LINK_ENB_PDCP_TO_IP_DRIVER_BIT);
+  uint32_t pdcp_initmask = (!IS_SOFTMODEM_NOS1 )? LINK_ENB_PDCP_TO_GTPV1U_BIT : (LINK_ENB_PDCP_TO_GTPV1U_BIT | PDCP_USE_NETLINK_BIT | LINK_ENB_PDCP_TO_IP_DRIVER_BIT);
 
-  if ( IS_SOFTMODEM_BASICSIM || (nfapi_mode == 3) ) {
+  if ( IS_SOFTMODEM_BASICSIM || IS_SOFTMODEM_RFSIM || (nfapi_mode == 3) ) {
     pdcp_initmask = pdcp_initmask | UE_NAS_USE_TUN_BIT;
   }
 
+  if ( IS_SOFTMODEM_NOKRNMOD)
+    pdcp_initmask = pdcp_initmask | UE_NAS_USE_TUN_BIT;
+
   pdcp_module_init( pdcp_initmask );
   //TTN for D2D
-#if (LTE_RRC_VERSION >= MAKE_VERSION(14, 0, 0))
   printf ("RRC control socket\n");
   rrc_control_socket_init();
   printf ("PDCP PC5S socket\n");
   pdcp_pc5_socket_init();
-#endif
   // to make a graceful exit when ctrl-c is pressed
   signal(SIGSEGV, signal_handler);
   signal(SIGINT, signal_handler);