diff --git a/openair1/PHY/CODING/TESTBENCH/polartest.c b/openair1/PHY/CODING/TESTBENCH/polartest.c
index 6d50070b863df627b449ed7005a892cb032602fb..14f9db98b5aed1ec356637d8743ef104f7b5d386 100644
--- a/openair1/PHY/CODING/TESTBENCH/polartest.c
+++ b/openair1/PHY/CODING/TESTBENCH/polartest.c
@@ -158,9 +158,7 @@ int main(int argc, char *argv[]) {
 
 	int16_t channelOutput_int16[coderLength];
  
-	t_nrPolar_paramsPtr nrPolar_params = NULL, currentPtr = NULL;
-	nr_polar_init(&nrPolar_params, polarMessageType, testLength, aggregation_level);
-	currentPtr = nr_polar_params(nrPolar_params, polarMessageType, testLength, aggregation_level);
+	t_nrPolar_params currentPtr = nr_polar_params(polarMessageType, testLength, aggregation_level);
 
 #ifdef DEBUG_DCI_POLAR_PARAMS
 	uint32_t dci_pdu[4];
@@ -173,8 +171,7 @@ int main(int argc, char *argv[]) {
 	uint16_t size=41;
 	uint16_t rnti=3;
 	aggregation_level=8;
-	nr_polar_init(&nrPolar_params, 1, size, aggregation_level);
-	t_nrPolar_paramsPtr currentPtrDCI=nr_polar_params(nrPolar_params, 1, size, aggregation_level);
+	t_nrPolar_params * currentPtrDCI=nr_polar_params(1, size, aggregation_level);
 
 	polar_encoder_dci(dci_pdu, encoder_output, currentPtrDCI, rnti);
 	for (int i=0;i<54;i++)
diff --git a/openair1/PHY/CODING/nrPolar_tools/nr_polar_decoder.c b/openair1/PHY/CODING/nrPolar_tools/nr_polar_decoder.c
index 91d20b51bb70ddcde447eac729d8411144166e13..8f91d4b28854bd701734d0ba7484baf641c2231e 100644
--- a/openair1/PHY/CODING/nrPolar_tools/nr_polar_decoder.c
+++ b/openair1/PHY/CODING/nrPolar_tools/nr_polar_decoder.c
@@ -42,7 +42,7 @@
 int8_t polar_decoder(
 		double *input,
 		uint8_t *out,
-		t_nrPolar_paramsPtr polarParams,
+		t_nrPolar_params * polarParams,
 		uint8_t listSize,
 		uint8_t pathMetricAppr)
 {
@@ -282,7 +282,7 @@ int8_t polar_decoder(
 
 int8_t polar_decoder_aPriori(double *input,
 			     uint32_t *out,
-			     t_nrPolar_paramsPtr polarParams,
+			     t_nrPolar_params * polarParams,
 			     uint8_t listSize,
 			     uint8_t pathMetricAppr,
 			     double *aPrioriPayload)
@@ -538,7 +538,7 @@ int8_t polar_decoder_aPriori(double *input,
 
 int8_t polar_decoder_aPriori_timing(double *input,
 									uint32_t *out,
-									t_nrPolar_paramsPtr polarParams,
+									t_nrPolar_params * polarParams,
 									uint8_t listSize,
 									uint8_t pathMetricAppr,
 									double *aPrioriPayload,
@@ -793,7 +793,7 @@ int8_t polar_decoder_aPriori_timing(double *input,
 
 int8_t polar_decoder_dci(double *input,
 						 uint32_t *out,
-						 t_nrPolar_paramsPtr polarParams,
+						 t_nrPolar_params * polarParams,
 						 uint8_t listSize,
 						 uint8_t pathMetricAppr,
 						 uint16_t n_RNTI)
@@ -1073,7 +1073,7 @@ void init_polar_deinterleaver_table(t_nrPolar_params *polarParams) {
 
 uint32_t polar_decoder_int16(int16_t *input,
 			     uint64_t *out,
-			     t_nrPolar_params *polarParams)
+			     const t_nrPolar_params *polarParams)
 {
   
 
diff --git a/openair1/PHY/CODING/nrPolar_tools/nr_polar_defs.h b/openair1/PHY/CODING/nrPolar_tools/nr_polar_defs.h
index 68e9ef35714fcd2e868e07b2d8c80b8bb123e0d7..ef795cb26f250752c006aca8f543998ba22fe3ab 100644
--- a/openair1/PHY/CODING/nrPolar_tools/nr_polar_defs.h
+++ b/openair1/PHY/CODING/nrPolar_tools/nr_polar_defs.h
@@ -136,42 +136,41 @@ struct nrPolar_params {
   decoder_tree_t tree;
 } __attribute__ ((__packed__));
 typedef struct nrPolar_params t_nrPolar_params;
-typedef t_nrPolar_params *t_nrPolar_paramsPtr;
 
 void polar_encoder(uint32_t *input,
 				   uint32_t *output,
-				   t_nrPolar_paramsPtr polarParams);
+				   t_nrPolar_params* polarParams);
 
 void polar_encoder_dci(uint32_t *in,
 					   uint32_t *out,
-					   t_nrPolar_paramsPtr polarParams,
+					   t_nrPolar_params* polarParams,
 					   uint16_t n_RNTI);
 
 void polar_encoder_fast(uint64_t *A,
 			uint32_t *out,
 			int32_t crcmask,
-			t_nrPolar_paramsPtr polarParams);
+			t_nrPolar_params* polarParams);
 
 int8_t polar_decoder(double *input,
 		 	 	 	 uint8_t *output,
-					 t_nrPolar_paramsPtr polarParams,
+					 t_nrPolar_params* polarParams,
 					 uint8_t listSize,
 					 uint8_t pathMetricAppr);
 
 uint32_t polar_decoder_int16(int16_t *input,
 			     uint64_t *out,
-			     t_nrPolar_params *polarParams);
+			     const t_nrPolar_params *polarParams);
 
 int8_t polar_decoder_aPriori(double *input,
 							 uint32_t *output,
-							 t_nrPolar_paramsPtr polarParams,
+							 t_nrPolar_params* polarParams,
 							 uint8_t listSize,
 							 uint8_t pathMetricAppr,
 							 double *aPrioriPayload);
 
 int8_t polar_decoder_aPriori_timing(double *input,
 									uint32_t *output,
-									t_nrPolar_paramsPtr polarParams,
+									t_nrPolar_params* polarParams,
 									uint8_t listSize,
 									uint8_t pathMetricAppr,
 									double *aPrioriPayload,
@@ -180,7 +179,7 @@ int8_t polar_decoder_aPriori_timing(double *input,
 
 int8_t polar_decoder_dci(double *input,
 						 uint32_t *out,
-						 t_nrPolar_paramsPtr polarParams,
+						 t_nrPolar_params* polarParams,
 						 uint8_t listSize,
 						 uint8_t pathMetricAppr,
 						 uint16_t n_RNTI);
@@ -189,18 +188,12 @@ void generic_polar_decoder(t_nrPolar_params *,
 		decoder_node_t *);
 
 void build_decoder_tree(t_nrPolar_params *pp);
-void build_polar_tables(t_nrPolar_paramsPtr polarParams);
+void build_polar_tables(t_nrPolar_params* polarParams);
 void init_polar_deinterleaver_table(t_nrPolar_params *polarParams);
 
-void nr_polar_init(t_nrPolar_paramsPtr *polarParams,
-				   int8_t messageType,
-				   uint16_t messageLength,
-				   uint8_t aggregation_level);
+void nr_polar_print_polarParams(t_nrPolar_params* polarParams);
 
-void nr_polar_print_polarParams(t_nrPolar_paramsPtr polarParams);
-
-t_nrPolar_paramsPtr nr_polar_params (t_nrPolar_paramsPtr polarParams,
-									 int8_t messageType,
+t_nrPolar_params * nr_polar_params ( int8_t messageType,
 									 uint16_t messageLength,
 									 uint8_t aggregation_level);
 
diff --git a/openair1/PHY/CODING/nrPolar_tools/nr_polar_encoder.c b/openair1/PHY/CODING/nrPolar_tools/nr_polar_encoder.c
index 50d14d87e211f88481a849b55a0699acb34fafc5..d68df025cee492640bbfc58836ed09d89de7e129 100644
--- a/openair1/PHY/CODING/nrPolar_tools/nr_polar_encoder.c
+++ b/openair1/PHY/CODING/nrPolar_tools/nr_polar_encoder.c
@@ -42,7 +42,7 @@
 
 void polar_encoder(uint32_t *in,
 		   uint32_t *out,
-		   t_nrPolar_paramsPtr polarParams)
+		   t_nrPolar_params * polarParams)
 {
   if (polarParams->idx == 0){//PBCH
     /*
@@ -151,7 +151,7 @@ nr_bit2byte_uint32_8_t((uint32_t*)&B, polarParams->K, polarParams->nr_polar_B);*
 
 void polar_encoder_dci(uint32_t *in,
 		       uint32_t *out,
-		       t_nrPolar_paramsPtr polarParams,
+		       t_nrPolar_params * polarParams,
 		       uint16_t n_RNTI)
 {
 #ifdef DEBUG_POLAR_ENCODER_DCI
@@ -284,9 +284,9 @@ void polar_encoder_dci(uint32_t *in,
 #endif
 }
 
-static inline void polar_rate_matching(t_nrPolar_paramsPtr polarParams,void *in,void *out) __attribute__((always_inline));
+static inline void polar_rate_matching(t_nrPolar_params * polarParams,void *in,void *out) __attribute__((always_inline));
 
-static inline void polar_rate_matching(t_nrPolar_paramsPtr polarParams,void *in,void *out) {
+static inline void polar_rate_matching(t_nrPolar_params * polarParams,void *in,void *out) {
 
   if (polarParams->groupsize == 8) 
     for (int i=0;i<polarParams->encoderLength>>3;i++) ((uint8_t*)out)[i] = ((uint8_t *)in)[polarParams->rm_tab[i]];
@@ -296,7 +296,7 @@ static inline void polar_rate_matching(t_nrPolar_paramsPtr polarParams,void *in,
     }
 }
 
-void build_polar_tables(t_nrPolar_paramsPtr polarParams) {
+void build_polar_tables(t_nrPolar_params * polarParams) {
   
   // build table b -> c'
 
@@ -388,7 +388,7 @@ void build_polar_tables(t_nrPolar_paramsPtr polarParams) {
 void polar_encoder_fast(uint64_t *A,
 			uint32_t *out,
 			int32_t crcmask,
-			t_nrPolar_paramsPtr polarParams) {
+			t_nrPolar_params * polarParams) {
 
   AssertFatal(polarParams->K > 32, "K = %d < 33, is not supported yet\n",polarParams->K);
   AssertFatal(polarParams->K < 129, "K = %d > 128, is not supported yet\n",polarParams->K);
diff --git a/openair1/PHY/CODING/nr_polar_init.c b/openair1/PHY/CODING/nr_polar_init.c
index 93bcdecd6ef6387a02cb908657e37691e7a756d4..c95ba2b608bee73a76ba37f220d1c4a7091a3340 100644
--- a/openair1/PHY/CODING/nr_polar_init.c
+++ b/openair1/PHY/CODING/nr_polar_init.c
@@ -41,12 +41,12 @@ static int intcmp(const void *p1,const void *p2) {
   return(*(int16_t*)p1 > *(int16_t*)p2);
 }
 
-void nr_polar_init(t_nrPolar_paramsPtr *polarParams,
+static void nr_polar_init(t_nrPolar_params * *polarParams,
 		   int8_t messageType,
 		   uint16_t messageLength,
 		   uint8_t aggregation_level)
 {
-	t_nrPolar_paramsPtr currentPtr = *polarParams;
+	t_nrPolar_params * currentPtr = *polarParams;
 	uint16_t aggregation_prime = nr_polar_aggregation_prime(aggregation_level);
 
 	//Parse the list. If the node is already created, return without initialization.
@@ -58,7 +58,7 @@ void nr_polar_init(t_nrPolar_paramsPtr *polarParams,
 
 	//	printf("currentPtr %p (polarParams %p)\n",currentPtr,polarParams);
 	//Else, initialize and add node to the end of the linked list.
-	t_nrPolar_paramsPtr newPolarInitNode = malloc(sizeof(t_nrPolar_params));
+	t_nrPolar_params * newPolarInitNode = malloc(sizeof(t_nrPolar_params));
 
 	if (newPolarInitNode != NULL) {
 
@@ -170,30 +170,15 @@ void nr_polar_init(t_nrPolar_paramsPtr *polarParams,
 		//printf("decoder tree nodes %d\n",newPolarInitNode->tree.num_nodes);
 
 	} else {
-		AssertFatal(1 == 0, "[nr_polar_init] New t_nrPolar_paramsPtr could not be created");
+		AssertFatal(1 == 0, "[nr_polar_init] New t_nrPolar_params * could not be created");
 	}
 
-	currentPtr = *polarParams;
-	//If polarParams is empty:
-	if (currentPtr == NULL)
-	{
-		*polarParams = newPolarInitNode;
-		//printf("Creating first polarParams entry index %d, %p\n",newPolarInitNode->idx,*polarParams);
-		return;
-	}
-	//Else, add node to the end of the linked list.
-	while (currentPtr->nextPtr != NULL) {
-	  currentPtr = currentPtr->nextPtr;
-	}
-	currentPtr->nextPtr= newPolarInitNode;
-	printf("Adding new polarParams entry to list index %d,%p\n",
-	       newPolarInitNode->idx,
-	       currentPtr->nextPtr);
-
+	newPolarInitNode->nextPtr=*polarParams;
+	*polarParams=newPolarInitNode;
 	return;
 }
 
-void nr_polar_print_polarParams(t_nrPolar_paramsPtr polarParams)
+void nr_polar_print_polarParams(t_nrPolar_params * polarParams)
 {
 	uint8_t i = 0;
 	if (polarParams == NULL) {
@@ -208,23 +193,22 @@ void nr_polar_print_polarParams(t_nrPolar_paramsPtr polarParams)
 	return;
 }
 
-t_nrPolar_paramsPtr nr_polar_params (t_nrPolar_paramsPtr polarParams,
-				     int8_t messageType,
+t_nrPolar_params * nr_polar_params ( int8_t messageType,
 				     uint16_t messageLength,
 				     uint8_t aggregation_level)
 {
-	t_nrPolar_paramsPtr currentPtr = NULL;
-
+	static t_nrPolar_params * polarList = NULL;
+	nr_polar_init(&polarList, messageType,messageLength,aggregation_level);
+        t_nrPolar_params * polarParams=polarList;
+	const int tag=messageType * messageLength * nr_polar_aggregation_prime(aggregation_level);
 	while (polarParams != NULL) {
-		if (polarParams->idx ==
-				(messageType * messageLength * (nr_polar_aggregation_prime(aggregation_level)) )) {
-			currentPtr = polarParams;
-			break;
-		} else {
+		if (polarParams->idx == tag)
+		return polarParams;
 			polarParams = polarParams->nextPtr;
+
 		}
-	}
-	return currentPtr;
+		AssertFatal(false,"Polar Init tables internal failure\n");
+	return NULL;
 }
 
 uint16_t nr_polar_aggregation_prime (uint8_t aggregation_level)
diff --git a/openair1/PHY/INIT/nr_init.c b/openair1/PHY/INIT/nr_init.c
index 1866eac96d54e71d030d57fd899c9bab2943ecad..0f098a2a1ba1f075b282d1f48ea01d230a6e633b 100644
--- a/openair1/PHY/INIT/nr_init.c
+++ b/openair1/PHY/INIT/nr_init.c
@@ -126,11 +126,6 @@ int phy_init_nr_gNB(PHY_VARS_gNB *gNB,
   nr_init_pbch_dmrs(gNB);
   // Polar encoder init for PBCH
   
-  nr_polar_init(&gNB->nrPolar_params,
-		NR_POLAR_PBCH_MESSAGE_TYPE,
-		NR_POLAR_PBCH_PAYLOAD_BITS,
-		NR_POLAR_PBCH_AGGREGATION_LEVEL);
-
   //PDCCH DMRS init
   gNB->nr_gold_pdcch_dmrs = (uint32_t ***)malloc16(fp->slots_per_frame*sizeof(uint32_t**));
   uint32_t ***pdcch_dmrs             = gNB->nr_gold_pdcch_dmrs;
diff --git a/openair1/PHY/NR_TRANSPORT/nr_dci.c b/openair1/PHY/NR_TRANSPORT/nr_dci.c
index dba114ed8ad07e0318349b9bcc8e3bf31047f2bc..e7522e6b182b4fd6155b9a0922b1335f99ba43de 100644
--- a/openair1/PHY/NR_TRANSPORT/nr_dci.c
+++ b/openair1/PHY/NR_TRANSPORT/nr_dci.c
@@ -159,7 +159,6 @@ void nr_pdcch_scrambling(uint32_t *in,
 }
 
 uint8_t nr_generate_dci_top(NR_gNB_PDCCH pdcch_vars,
-			    t_nrPolar_paramsPtr *nrPolar_params,
                             uint32_t **gold_pdcch_dmrs,
                             int32_t* txdataF,
                             int16_t amp,
@@ -249,8 +248,7 @@ uint8_t nr_generate_dci_top(NR_gNB_PDCCH pdcch_vars,
   uint16_t Nid = (pdcch_params.search_space_type == NFAPI_NR_SEARCH_SPACE_TYPE_UE_SPECIFIC)?
   pdcch_params.scrambling_id : config.sch_config.physical_cell_id.value;
 
-  nr_polar_init(nrPolar_params, NR_POLAR_DCI_MESSAGE_TYPE, dci_alloc.size, dci_alloc.L);
-  t_nrPolar_paramsPtr currentPtr = nr_polar_params(*nrPolar_params, NR_POLAR_DCI_MESSAGE_TYPE, dci_alloc.size, dci_alloc.L);
+  t_nrPolar_params * currentPtr = nr_polar_params(NR_POLAR_DCI_MESSAGE_TYPE, dci_alloc.size, dci_alloc.L);
 
   polar_encoder_fast(dci_alloc.dci_pdu, encoder_output, pdcch_params.rnti,currentPtr);
 
diff --git a/openair1/PHY/NR_TRANSPORT/nr_dci.h b/openair1/PHY/NR_TRANSPORT/nr_dci.h
index 4bf250dbff2cb2c7c3fb749a2c63041542c6edda..7477bf4331fd4f7067c5fae0914de95d1aa432f3 100644
--- a/openair1/PHY/NR_TRANSPORT/nr_dci.h
+++ b/openair1/PHY/NR_TRANSPORT/nr_dci.h
@@ -33,7 +33,6 @@ uint16_t nr_get_dci_size(nfapi_nr_dci_format_e format,
                         nfapi_nr_config_request_t* config);
 
 uint8_t nr_generate_dci_top(NR_gNB_PDCCH pdcch_vars,
-                            t_nrPolar_paramsPtr *nrPolar_params,
                             uint32_t **gold_pdcch_dmrs,
                             int32_t* txdataF,
                             int16_t amp,
diff --git a/openair1/PHY/NR_TRANSPORT/nr_pbch.c b/openair1/PHY/NR_TRANSPORT/nr_pbch.c
index 2e2c99f106f496a178bbd682e675989c29b4d41f..ad76c803795208849c7cf723a7f263cec7d763a5 100644
--- a/openair1/PHY/NR_TRANSPORT/nr_pbch.c
+++ b/openair1/PHY/NR_TRANSPORT/nr_pbch.c
@@ -225,7 +225,6 @@ void nr_init_pbch_interleaver(uint8_t *interleaver) {
 }
 
 int nr_generate_pbch(NR_gNB_PBCH *pbch,
-                     t_nrPolar_paramsPtr polar_params,
                      uint8_t *pbch_pdu,
                      uint8_t *interleaver,
                      int32_t *txdataF,
@@ -307,7 +306,9 @@ int nr_generate_pbch(NR_gNB_PBCH *pbch,
 
 
   /// CRC, coding and rate matching
-  polar_encoder_fast (&a_reversed, (uint32_t*)pbch->pbch_e, 0, polar_params);
+  polar_encoder_fast (&a_reversed, (uint32_t*)pbch->pbch_e, 0, 
+		  nr_polar_params( NR_POLAR_PBCH_MESSAGE_TYPE, NR_POLAR_PBCH_PAYLOAD_BITS, NR_POLAR_PBCH_AGGREGATION_LEVEL)
+                     );
 #ifdef DEBUG_PBCH_ENCODING
   printf("Channel coding:\n");
   for (int i=0; i<NR_POLAR_PBCH_E_DWORD; i++)
diff --git a/openair1/PHY/NR_TRANSPORT/nr_transport.h b/openair1/PHY/NR_TRANSPORT/nr_transport.h
index c1a4052191d8d6c0c6ee1435c2af1de884014e5d..082a12a1d345ea521ebb762b0f3d53ba665d491c 100644
--- a/openair1/PHY/NR_TRANSPORT/nr_transport.h
+++ b/openair1/PHY/NR_TRANSPORT/nr_transport.h
@@ -85,7 +85,6 @@ void nr_pbch_scrambling(NR_gNB_PBCH *pbch,
 @returns 0 on success
  */
 int nr_generate_pbch(NR_gNB_PBCH *pbch,
-                     t_nrPolar_paramsPtr polar_params,
                      uint8_t *pbch_pdu,
                      uint8_t *interleaver,
                      int32_t *txdataF,
diff --git a/openair1/PHY/NR_UE_TRANSPORT/dci_nr.c b/openair1/PHY/NR_UE_TRANSPORT/dci_nr.c
index 0c25c0efdb20c503c5ff4a41016ea11d9e4422fc..c1d7fbcac2b277eb567ddc0f1a69b5d39ae77c61 100755
--- a/openair1/PHY/NR_UE_TRANSPORT/dci_nr.c
+++ b/openair1/PHY/NR_UE_TRANSPORT/dci_nr.c
@@ -1136,7 +1136,6 @@ void nr_dci_decoding_procedure0(int s,
   
   int coreset_nbr_cce_per_symbol=0;
 
-  t_nrPolar_paramsPtr nrPolar_params = pdcch_vars[eNB_id]->nrPolar_params;
   
 #ifdef NR_PDCCH_DCI_DEBUG
   printf("\t\t<-NR_PDCCH_DCI_DEBUG (nr_dci_decoding_procedure0)-> format_found is %d \n", *format_found);
@@ -1364,9 +1363,7 @@ void nr_dci_decoding_procedure0(int s,
 
       uint64_t dci_estimation[2]={0};
 
-      nr_polar_init(&nrPolar_params, 1, sizeof_bits, L2);
-
-      t_nrPolar_paramsPtr currentPtrDCI=nr_polar_params(nrPolar_params, 1, sizeof_bits, L2);
+      const t_nrPolar_params* currentPtrDCI=nr_polar_params(1, sizeof_bits, L2);
       decoderState = polar_decoder_int16(&pdcch_vars[eNB_id]->e_rx[CCEind*9*6*2],
 					 dci_estimation,
 					 currentPtrDCI);
diff --git a/openair1/PHY/NR_UE_TRANSPORT/nr_pbch.c b/openair1/PHY/NR_UE_TRANSPORT/nr_pbch.c
index 613e45cb8d68eb1f2bb1163ea77f4d18378d152f..2280ded196d5566d5f6779192a1620de321d73cb 100644
--- a/openair1/PHY/NR_UE_TRANSPORT/nr_pbch.c
+++ b/openair1/PHY/NR_UE_TRANSPORT/nr_pbch.c
@@ -566,15 +566,7 @@ int nr_rx_pbch( PHY_VARS_NR_UE *ue,
 
 
   //polar decoding de-rate matching
-
-  nr_polar_init(&nr_ue_pbch_vars->nrPolar_params,
-		NR_POLAR_PBCH_MESSAGE_TYPE,
-		NR_POLAR_PBCH_PAYLOAD_BITS,
-		NR_POLAR_PBCH_AGGREGATION_LEVEL);
-
-  AssertFatal(nr_ue_pbch_vars->nrPolar_params != NULL,"nr_ue_pbch_vars->nrPolar_params is null\n");
-
-  t_nrPolar_params *currentPtr = nr_polar_params(nr_ue_pbch_vars->nrPolar_params, NR_POLAR_PBCH_MESSAGE_TYPE, NR_POLAR_PBCH_PAYLOAD_BITS, NR_POLAR_PBCH_AGGREGATION_LEVEL);
+  const t_nrPolar_params *currentPtr = nr_polar_params( NR_POLAR_PBCH_MESSAGE_TYPE, NR_POLAR_PBCH_PAYLOAD_BITS, NR_POLAR_PBCH_AGGREGATION_LEVEL);
 
   decoderState = polar_decoder_int16(pbch_e_rx,(uint64_t*)&nr_ue_pbch_vars->pbch_a_prime,currentPtr);
  
diff --git a/openair1/PHY/defs_gNB.h b/openair1/PHY/defs_gNB.h
index 24a9fd45c825494f535f507f12f6b8ce3cb4971d..10b99eb113121661965ee034c2919b7deeb81bf8 100644
--- a/openair1/PHY/defs_gNB.h
+++ b/openair1/PHY/defs_gNB.h
@@ -391,7 +391,6 @@ typedef struct PHY_VARS_gNB_s {
   Sched_Rsp_t         Sched_INFO;
   NR_gNB_PDCCH        pdcch_vars;
   NR_gNB_PBCH         pbch;
-  t_nrPolar_paramsPtr nrPolar_params;
   LTE_eNB_PHICH       phich_vars[2];
 
   NR_gNB_COMMON       common_vars;
diff --git a/openair1/PHY/defs_nr_UE.h b/openair1/PHY/defs_nr_UE.h
index 483b3ab72db5d54aa11c883d9daaa1453f8d1241..32afa7721a1a5b152f34bc42d47767a61e7b5559 100644
--- a/openair1/PHY/defs_nr_UE.h
+++ b/openair1/PHY/defs_nr_UE.h
@@ -892,7 +892,6 @@ typedef struct {
   //Check for specific DCIFormat and AgregationLevel
   uint8_t dciFormat;
   uint8_t agregationLevel;
-  t_nrPolar_paramsPtr nrPolar_params;
   #ifdef NR_PDCCH_DEFS_NR_UE
   int nb_searchSpaces;
   // CORESET structure, where maximum number of CORESETs to be handled is 3 (according to 38.331 V15.1.0)
@@ -933,8 +932,6 @@ typedef struct {
   /// \brief Pointer to PBCH decoded output.
   /// - first index: ? [0..63] (hard coded)
   uint8_t *decoded_output;
-  /// polar decoder parameters
-  t_nrPolar_paramsPtr nrPolar_params;
   /// \brief Total number of PDU errors.
   uint32_t pdu_errors;
   /// \brief Total number of PDU errors 128 frames ago.
diff --git a/openair1/SCHED_NR/phy_procedures_nr_gNB.c b/openair1/SCHED_NR/phy_procedures_nr_gNB.c
index a7f8ef68840ffa041361b0770e809c79a6f66f08..bd8e7f6a306156e202662cc0d0a4e86e3530357c 100644
--- a/openair1/SCHED_NR/phy_procedures_nr_gNB.c
+++ b/openair1/SCHED_NR/phy_procedures_nr_gNB.c
@@ -149,7 +149,6 @@ void nr_common_signal_procedures (PHY_VARS_gNB *gNB,int frame, int slot) {
     nr_generate_pbch_dmrs(gNB->nr_gold_pbch_dmrs[n_hf][ssb_index],txdataF[0], AMP, ssb_start_symbol, cfg, fp);
 
     nr_generate_pbch(&gNB->pbch,
-                      gNB->nrPolar_params,
                       pbch_pdu,
                       gNB->nr_pbch_interleaver,
                       txdataF[0],
@@ -201,7 +200,6 @@ void phy_procedures_gNB_TX(PHY_VARS_gNB *gNB,
 
     if (nfapi_mode == 0 || nfapi_mode == 1){
       nr_generate_dci_top(gNB->pdcch_vars,
-                          &gNB->nrPolar_params,
                           gNB->nr_gold_pdcch_dmrs[slot],
                           gNB->common_vars.txdataF[0],
                           AMP, *fp, *cfg);
diff --git a/targets/ARCH/rfsimulator/simulator.c b/targets/ARCH/rfsimulator/simulator.c
index e68db002cf715495ae675bdbd9203e65ea536e92..a17327b03ecc5791cadc7cef76fbecc9d3205da8 100644
--- a/targets/ARCH/rfsimulator/simulator.c
+++ b/targets/ARCH/rfsimulator/simulator.c
@@ -82,6 +82,17 @@ void removeCirBuf(rfsimulator_state_t *bridge, int sock) {
   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\
@@ -108,32 +119,28 @@ void setblocking(int sock, enum blocking_t active) {
 
 static bool flushInput(rfsimulator_state_t *t);
 
-int fullwrite(int fd, void *_buf, int count, rfsimulator_state_t *t) {
+void fullwrite(int fd, void *_buf, int count, rfsimulator_state_t *t) {
   char *buf = _buf;
-  int ret = 0;
   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 -1;
+        flushInput(t);
+        continue;
+      } else
+        return;
     }
 
     count -= l;
     buf += l;
-    ret += l;
   }
-
-  return ret;
 }
 
 int server_start(openair0_device *device) {
@@ -143,9 +150,12 @@ int server_start(openair0_device *device) {
   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 }
+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, "");
@@ -162,9 +172,12 @@ int start_ue(openair0_device *device) {
   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 }
+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;
@@ -195,8 +208,7 @@ int rfsimulator_write(openair0_device *device, openair0_timestamp timestamp, voi
 
     if (ptr->conn_sock >= 0 ) {
       transferHeader header= {t->typeStamp, nsamps, nbAnt, timestamp};
-      int n=-1;
-      AssertFatal( fullwrite(ptr->conn_sock,&header, sizeof(header), t) == sizeof(header), "");
+      fullwrite(ptr->conn_sock,&header, sizeof(header), t);
       sample_t tmpSamples[nsamps][nbAnt];
 
       for(int a=0; a<nbAnt; a++) {
@@ -206,13 +218,8 @@ int rfsimulator_write(openair0_device *device, openair0_timestamp timestamp, voi
           tmpSamples[s][a]=in[s];
       }
 
-      n = fullwrite(ptr->conn_sock, (void *)tmpSamples, sampleToByte(nsamps,nbAnt), t);
-
-      if (n != sampleToByte(nsamps,nbAnt) ) {
-        LOG_E(HW,"rfsimulator: write error ret %d (wanted %ld) error %s\n", n, sampleToByte(nsamps,nbAnt), strerror(errno));
-        abort();
-      }
-
+      if (ptr->conn_sock >= 0 )
+        fullwrite(ptr->conn_sock, (void *)tmpSamples, sampleToByte(nsamps,nbAnt), t);
     }
   }
 
@@ -241,17 +248,11 @@ static bool flushInput(rfsimulator_state_t *t) {
       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) ) {
-        LOG_W(HW,"Lost socket\n");
-        removeCirBuf(t, fd);
-
-        if (t->typeStamp==MAGICUE)
-          exit(1);
-
+        socketError(t,fd);
         continue;
       }
 
@@ -292,7 +293,8 @@ static bool flushInput(rfsimulator_state_t *t) {
         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;
+        b->alreadyRead=true;
+
         if ( b->lastReceivedTS != b->th.timestamp) {
           int nbAnt= b->th.nbAnt;
 
@@ -331,7 +333,10 @@ static bool flushInput(rfsimulator_state_t *t) {
 }
 
 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); }
+  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);
@@ -351,7 +356,6 @@ int rfsimulator_read(openair0_device *device, openair0_timestamp *ptimestamp, vo
 
       t->nextTimestamp+=nsamps;
       LOG_W(HW,"Generated void samples for Rx: %ld\n", t->nextTimestamp);
-
       *ptimestamp = t->nextTimestamp-nsamps;
       return nsamps;
     }
@@ -443,8 +447,8 @@ int device_init(openair0_device *device, openair0_config_t *openair0_cfg) {
   }
 
   rfsimulator->typeStamp = strncasecmp(rfsimulator->ip,"enb",3) == 0 ?
-                          MAGICeNB:
-                          MAGICUE;
+                           MAGICeNB:
+                           MAGICUE;
   LOG_I(HW,"rfsimulator: running as %s\n", rfsimulator-> typeStamp == MAGICeNB ? "eNB" : "UE");
   device->trx_start_func       = rfsimulator->typeStamp == MAGICeNB ?
                                  server_start :
diff --git a/targets/RT/USER/nr-ue.c b/targets/RT/USER/nr-ue.c
index bfd143acee1875116671f15d1e7ee062546acf51..0c9cda5819c751e9ec984ef34f7046f440c4cccf 100644
--- a/targets/RT/USER/nr-ue.c
+++ b/targets/RT/USER/nr-ue.c
@@ -60,9 +60,9 @@
 #include "T.h"
 
 #ifdef XFORMS
-#include "PHY/TOOLS/nr_phy_scope.h"
+  #include "PHY/TOOLS/nr_phy_scope.h"
 
-extern char do_forms;
+  extern char do_forms;
 #endif
 
 
@@ -138,9 +138,9 @@ extern double cpuf;
 #define FIFO_PRIORITY   40
 
 typedef enum {
-    pss=0,
-    pbch=1,
-    si=2
+  pss=0,
+  pbch=1,
+  si=2
 } sync_mode_t;
 
 void init_UE_threads(PHY_VARS_NR_UE *UE);
@@ -155,71 +155,69 @@ int32_t **txdata;
 #define SAIF_ENABLED
 
 #ifdef SAIF_ENABLED
-uint64_t	g_ue_rx_thread_busy	= 0;
+  uint64_t  g_ue_rx_thread_busy = 0;
 #endif
 
 typedef struct eutra_band_s {
-    int16_t band;
-    uint32_t ul_min;
-    uint32_t ul_max;
-    uint32_t dl_min;
-    uint32_t dl_max;
-    lte_frame_type_t frame_type;
+  int16_t band;
+  uint32_t ul_min;
+  uint32_t ul_max;
+  uint32_t dl_min;
+  uint32_t dl_max;
+  lte_frame_type_t frame_type;
 } eutra_band_t;
 
 typedef struct band_info_s {
-    int nbands;
-    eutra_band_t band_info[100];
+  int nbands;
+  eutra_band_t band_info[100];
 } band_info_t;
 
 band_info_t bands_to_scan;
 
 static const eutra_band_t eutra_bands[] = {
-    { 1, 1920    * MHz, 1980    * MHz, 2110    * MHz, 2170    * MHz, FDD},
-    { 2, 1850    * MHz, 1910    * MHz, 1930    * MHz, 1990    * MHz, FDD},
-    { 3, 1710    * MHz, 1785    * MHz, 1805    * MHz, 1880    * MHz, FDD},
-    { 4, 1710    * MHz, 1755    * MHz, 2110    * MHz, 2155    * MHz, FDD},
-    { 5,  824    * MHz,  849    * MHz,  869    * MHz,  894    * MHz, FDD},
-    { 6,  830    * MHz,  840    * MHz,  875    * MHz,  885    * MHz, FDD},
-    { 7, 2500    * MHz, 2570    * MHz, 2620    * MHz, 2690    * MHz, FDD},
-    { 8,  880    * MHz,  915    * MHz,  925    * MHz,  960    * MHz, FDD},
-    { 9, 1749900 * KHz, 1784900 * KHz, 1844900 * KHz, 1879900 * KHz, FDD},
-    {10, 1710    * MHz, 1770    * MHz, 2110    * MHz, 2170    * MHz, FDD},
-    {11, 1427900 * KHz, 1452900 * KHz, 1475900 * KHz, 1500900 * KHz, FDD},
-    {12,  698    * MHz,  716    * MHz,  728    * MHz,  746    * MHz, FDD},
-    {13,  777    * MHz,  787    * MHz,  746    * MHz,  756    * MHz, FDD},
-    {14,  788    * MHz,  798    * MHz,  758    * MHz,  768    * MHz, FDD},
-    {17,  704    * MHz,  716    * MHz,  734    * MHz,  746    * MHz, FDD},
-    {20,  832    * MHz,  862    * MHz,  791    * MHz,  821    * MHz, FDD},
-    {22, 3510    * MHz, 3590    * MHz, 3410    * MHz, 3490    * MHz, FDD},
-    {33, 1900    * MHz, 1920    * MHz, 1900    * MHz, 1920    * MHz, TDD},
-    {34, 2010    * MHz, 2025    * MHz, 2010    * MHz, 2025    * MHz, TDD},
-    {35, 1850    * MHz, 1910    * MHz, 1850    * MHz, 1910    * MHz, TDD},
-    {36, 1930    * MHz, 1990    * MHz, 1930    * MHz, 1990    * MHz, TDD},
-    {37, 1910    * MHz, 1930    * MHz, 1910    * MHz, 1930    * MHz, TDD},
-    {38, 2570    * MHz, 2620    * MHz, 2570    * MHz, 2630    * MHz, TDD},
-    {39, 1880    * MHz, 1920    * MHz, 1880    * MHz, 1920    * MHz, TDD},
-    {40, 2300    * MHz, 2400    * MHz, 2300    * MHz, 2400    * MHz, TDD},
-    {41, 2496    * MHz, 2690    * MHz, 2496    * MHz, 2690    * MHz, TDD},
-    {42, 3400    * MHz, 3600    * MHz, 3400    * MHz, 3600    * MHz, TDD},
-    {43, 3600    * MHz, 3800    * MHz, 3600    * MHz, 3800    * MHz, TDD},
-    {44, 703    * MHz, 803    * MHz, 703    * MHz, 803    * MHz, TDD},
+  { 1, 1920    * MHz, 1980    * MHz, 2110    * MHz, 2170    * MHz, FDD},
+  { 2, 1850    * MHz, 1910    * MHz, 1930    * MHz, 1990    * MHz, FDD},
+  { 3, 1710    * MHz, 1785    * MHz, 1805    * MHz, 1880    * MHz, FDD},
+  { 4, 1710    * MHz, 1755    * MHz, 2110    * MHz, 2155    * MHz, FDD},
+  { 5,  824    * MHz,  849    * MHz,  869    * MHz,  894    * MHz, FDD},
+  { 6,  830    * MHz,  840    * MHz,  875    * MHz,  885    * MHz, FDD},
+  { 7, 2500    * MHz, 2570    * MHz, 2620    * MHz, 2690    * MHz, FDD},
+  { 8,  880    * MHz,  915    * MHz,  925    * MHz,  960    * MHz, FDD},
+  { 9, 1749900 * KHz, 1784900 * KHz, 1844900 * KHz, 1879900 * KHz, FDD},
+  {10, 1710    * MHz, 1770    * MHz, 2110    * MHz, 2170    * MHz, FDD},
+  {11, 1427900 * KHz, 1452900 * KHz, 1475900 * KHz, 1500900 * KHz, FDD},
+  {12,  698    * MHz,  716    * MHz,  728    * MHz,  746    * MHz, FDD},
+  {13,  777    * MHz,  787    * MHz,  746    * MHz,  756    * MHz, FDD},
+  {14,  788    * MHz,  798    * MHz,  758    * MHz,  768    * MHz, FDD},
+  {17,  704    * MHz,  716    * MHz,  734    * MHz,  746    * MHz, FDD},
+  {20,  832    * MHz,  862    * MHz,  791    * MHz,  821    * MHz, FDD},
+  {22, 3510    * MHz, 3590    * MHz, 3410    * MHz, 3490    * MHz, FDD},
+  {33, 1900    * MHz, 1920    * MHz, 1900    * MHz, 1920    * MHz, TDD},
+  {34, 2010    * MHz, 2025    * MHz, 2010    * MHz, 2025    * MHz, TDD},
+  {35, 1850    * MHz, 1910    * MHz, 1850    * MHz, 1910    * MHz, TDD},
+  {36, 1930    * MHz, 1990    * MHz, 1930    * MHz, 1990    * MHz, TDD},
+  {37, 1910    * MHz, 1930    * MHz, 1910    * MHz, 1930    * MHz, TDD},
+  {38, 2570    * MHz, 2620    * MHz, 2570    * MHz, 2630    * MHz, TDD},
+  {39, 1880    * MHz, 1920    * MHz, 1880    * MHz, 1920    * MHz, TDD},
+  {40, 2300    * MHz, 2400    * MHz, 2300    * MHz, 2400    * MHz, TDD},
+  {41, 2496    * MHz, 2690    * MHz, 2496    * MHz, 2690    * MHz, TDD},
+  {42, 3400    * MHz, 3600    * MHz, 3400    * MHz, 3600    * MHz, TDD},
+  {43, 3600    * MHz, 3800    * MHz, 3600    * MHz, 3800    * MHz, TDD},
+  {44, 703    * MHz, 803    * MHz, 703    * MHz, 803    * MHz, TDD},
 };
 
-PHY_VARS_NR_UE* init_nr_ue_vars(NR_DL_FRAME_PARMS *frame_parms,
-			  uint8_t UE_id,
-			  uint8_t abstraction_flag)
+PHY_VARS_NR_UE *init_nr_ue_vars(NR_DL_FRAME_PARMS *frame_parms,
+                                uint8_t UE_id,
+                                uint8_t abstraction_flag)
 
 {
-
-  PHY_VARS_NR_UE* ue;
+  PHY_VARS_NR_UE *ue;
 
   if (frame_parms!=(NR_DL_FRAME_PARMS *)NULL) { // if we want to give initial frame parms, allocate the PHY_VARS_UE structure and put them in
     ue = (PHY_VARS_NR_UE *)malloc(sizeof(PHY_VARS_NR_UE));
     memset(ue,0,sizeof(PHY_VARS_NR_UE));
     memcpy(&(ue->frame_parms), frame_parms, sizeof(NR_DL_FRAME_PARMS));
-  }
-  else ue = PHY_vars_UE_g[UE_id][0];
+  } else ue = PHY_vars_UE_g[UE_id][0];
 
   ue->Mod_id      = UE_id;
   ue->mac_enabled = 1;
@@ -227,97 +225,99 @@ PHY_VARS_NR_UE* init_nr_ue_vars(NR_DL_FRAME_PARMS *frame_parms,
   init_nr_ue_signal(ue,1,abstraction_flag);
   // intialize transport
   init_nr_ue_transport(ue,abstraction_flag);
-
   return(ue);
 }
 
-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);
-        attr.sched_policy = SCHED_DEADLINE;
-        attr.sched_runtime  = sched_runtime;
-        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));
-        LOG_I(HW,"[SCHED][eNB] %s deadline thread %lu started on CPU %d\n",
-              name, (unsigned long)gettid(), sched_getcpu());
-    }
+
+  if (sched_runtime!=0) {
+    struct sched_attr attr= {0};
+    attr.size = sizeof(attr);
+    attr.sched_policy = SCHED_DEADLINE;
+    attr.sched_runtime  = sched_runtime;
+    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));
+    LOG_I(HW,"[SCHED][eNB] %s deadline thread %lu started on CPU %d\n",
+          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");
-    /* 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};
-      for (int j = 0; j < CPU_SETSIZE; j++)
-        if (CPU_ISSET(j, cset))
-	  sprintf(txt+strlen(txt), " %d ", j);
-      printf("CPU Affinity of thread %s is %s\n", name, txt);
-    }
-    CPU_FREE(cset);
-#endif
 
-    // Lock memory from swapping. This is a process wide call (not constraint to this thread).
-    mlockall(MCL_CURRENT | MCL_FUTURE);
-    pthread_setname_np( pthread_self(), name );
-
-    // LTS: this sync stuff should be wrong
-    printf("waiting for sync (%s)\n",name);
-    pthread_mutex_lock(&sync_mutex);
-    printf("Locked sync_mutex, waiting (%s)\n",name);
-    while (sync_var<0)
-        pthread_cond_wait(&sync_cond, &sync_mutex);
-    pthread_mutex_unlock(&sync_mutex);
-    printf("started %s as PID: %ld\n",name, gettid());
+  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");
+  /* 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};
+
+    for (int j = 0; j < CPU_SETSIZE; j++)
+      if (CPU_ISSET(j, cset))
+        sprintf(txt+strlen(txt), " %d ", j);
+
+    printf("CPU Affinity of thread %s is %s\n", name, txt);
+  }
+
+  CPU_FREE(cset);
+#endif
+  // Lock memory from swapping. This is a process wide call (not constraint to this thread).
+  mlockall(MCL_CURRENT | MCL_FUTURE);
+  pthread_setname_np( pthread_self(), name );
+  // LTS: this sync stuff should be wrong
+  printf("waiting for sync (%s)\n",name);
+  pthread_mutex_lock(&sync_mutex);
+  printf("Locked sync_mutex, waiting (%s)\n",name);
+
+  while (sync_var<0)
+    pthread_cond_wait(&sync_cond, &sync_mutex);
+
+  pthread_mutex_unlock(&sync_mutex);
+  printf("started %s as PID: %ld\n",name, gettid());
 }
 
-void init_UE(int nb_inst)
-{
-    int inst;
-    NR_UE_MAC_INST_t *mac_inst;
-    for (inst=0; inst < nb_inst; inst++) {
-        //    UE->rfdevice.type      = NONE_DEV;
-        //PHY_VARS_NR_UE *UE = PHY_vars_UE_g[inst][0];
-        LOG_I(PHY,"Initializing memory for UE instance %d (%p)\n",inst,PHY_vars_UE_g[inst]);
-            PHY_vars_UE_g[inst][0] = init_nr_ue_vars(NULL,inst,0);
-        PHY_VARS_NR_UE *UE = PHY_vars_UE_g[inst][0];
-
-        AssertFatal((UE->if_inst = nr_ue_if_module_init(inst)) != NULL, "can not initial IF module\n");
-        nr_l3_init_ue();
-        nr_l2_init_ue();
-        
-        mac_inst = get_mac_inst(0);
-        mac_inst->if_module = UE->if_inst;
-        UE->if_inst->scheduled_response = nr_ue_scheduled_response;
-        UE->if_inst->phy_config_request = nr_ue_phy_config_request;
-        
-        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);
-		//UE = PHY_vars_UE_g[inst][0];
-		
-
-        AssertFatal(0 == pthread_create(&UE->proc.pthread_ue,
-                                        &UE->proc.attr_ue,
-                                        UE_thread,
-                                        (void*)UE), "");
-    }
+void init_UE(int nb_inst) {
+  int inst;
+  NR_UE_MAC_INST_t *mac_inst;
+
+  for (inst=0; inst < nb_inst; inst++) {
+    //    UE->rfdevice.type      = NONE_DEV;
+    //PHY_VARS_NR_UE *UE = PHY_vars_UE_g[inst][0];
+    LOG_I(PHY,"Initializing memory for UE instance %d (%p)\n",inst,PHY_vars_UE_g[inst]);
+    PHY_vars_UE_g[inst][0] = init_nr_ue_vars(NULL,inst,0);
+    PHY_VARS_NR_UE *UE = PHY_vars_UE_g[inst][0];
+    AssertFatal((UE->if_inst = nr_ue_if_module_init(inst)) != NULL, "can not initial IF module\n");
+    nr_l3_init_ue();
+    nr_l2_init_ue();
+    mac_inst = get_mac_inst(0);
+    mac_inst->if_module = UE->if_inst;
+    UE->if_inst->scheduled_response = nr_ue_scheduled_response;
+    UE->if_inst->phy_config_request = nr_ue_phy_config_request;
+    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);
+    //UE = PHY_vars_UE_g[inst][0];
+    AssertFatal(0 == pthread_create(&UE->proc.pthread_ue,
+                                    &UE->proc.attr_ue,
+                                    UE_thread,
+                                    (void *)UE), "");
+  }
 
   printf("UE threads created by %ld\n", gettid());
 #if 0
 #if defined(ENABLE_USE_MME)
   extern volatile int start_UE;
+
   while (start_UE == 0) {
     sleep(1);
   }
+
 #endif
 #endif
 }
@@ -329,290 +329,344 @@ void init_UE(int nb_inst)
  * \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 int __thread UE_thread_synch_retval;
-    int i, hw_slot_offset;
-    PHY_VARS_NR_UE *UE = (PHY_VARS_NR_UE*) arg;
-    int current_band = 0;
-    int current_offset = 0;
-    sync_mode_t sync_mode = pbch;
-    int CC_id = UE->CC_id;
-    int freq_offset=0;
-    char threadname[128];
-
-    cpu_set_t cpuset;
-    CPU_ZERO(&cpuset);
-    if ( threads.sync != -1 )
-        CPU_SET(threads.sync, &cpuset);
-    // this thread priority must be lower that the main acquisition thread
-    sprintf(threadname, "sync UE %d", UE->Mod_id);
-    init_thread(100000, 500000, FIFO_PRIORITY-1, &cpuset, threadname);
-
-    UE->is_synchronized = 0;
-
-    if (UE->UE_scan == 0) {
-        int ind;
-        for ( ind=0;
-                ind < sizeof(eutra_bands) / sizeof(eutra_bands[0]);
-                ind++) {
-            current_band = eutra_bands[ind].band;
-            LOG_D(PHY, "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 <= downlink_frequency[0][0] && eutra_bands[ind].dl_max >= downlink_frequency[0][0] ) {
-                for (i=0; i<4; i++)
-                    uplink_frequency_offset[CC_id][i] = eutra_bands[ind].ul_min - eutra_bands[ind].dl_min;
-                break;
-            }
-        }
-        AssertFatal( ind < sizeof(eutra_bands) / sizeof(eutra_bands[0]), "Can't find EUTRA band for frequency");
-
-        LOG_I( PHY, "[SCHED][UE] Check absolute frequency DL %"PRIu32", UL %"PRIu32" (oai_exit %d, rx_num_channels %d)\n",
-               downlink_frequency[0][0], downlink_frequency[0][0]+uplink_frequency_offset[0][0],
-               oai_exit, openair0_cfg[0].rx_num_channels);
+  static int __thread UE_thread_synch_retval;
+  int i, hw_slot_offset;
+  PHY_VARS_NR_UE *UE = (PHY_VARS_NR_UE *) arg;
+  int current_band = 0;
+  int current_offset = 0;
+  sync_mode_t sync_mode = pbch;
+  int CC_id = UE->CC_id;
+  int freq_offset=0;
+  char threadname[128];
+  cpu_set_t cpuset;
+  CPU_ZERO(&cpuset);
+
+  if ( threads.sync != -1 )
+    CPU_SET(threads.sync, &cpuset);
+
+  // this thread priority must be lower that the main acquisition thread
+  sprintf(threadname, "sync UE %d", UE->Mod_id);
+  init_thread(100000, 500000, FIFO_PRIORITY-1, &cpuset, threadname);
+  UE->is_synchronized = 0;
+
+  if (UE->UE_scan == 0) {
+    int ind;
+
+    for ( ind=0;
+          ind < sizeof(eutra_bands) / sizeof(eutra_bands[0]);
+          ind++) {
+      current_band = eutra_bands[ind].band;
+      LOG_D(PHY, "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 <= downlink_frequency[0][0] && eutra_bands[ind].dl_max >= downlink_frequency[0][0] ) {
+        for (i=0; i<4; i++)
+          uplink_frequency_offset[CC_id][i] = eutra_bands[ind].ul_min - eutra_bands[ind].dl_min;
+
+        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];
-            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].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;
-            else //FDD
-                openair0_cfg[UE->rf_map.card].duplex_mode = duplex_mode_TDD;
-        }
-        sync_mode = pbch;
+    AssertFatal( ind < sizeof(eutra_bands) / sizeof(eutra_bands[0]), "Can't find EUTRA band for frequency");
+    LOG_I( PHY, "[SCHED][UE] Check absolute frequency DL %"PRIu32", UL %"PRIu32" (oai_exit %d, rx_num_channels %d)\n",
+           downlink_frequency[0][0], downlink_frequency[0][0]+uplink_frequency_offset[0][0],
+           oai_exit, openair0_cfg[0].rx_num_channels);
+
+    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];
+      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].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;
+      else //FDD
+        openair0_cfg[UE->rf_map.card].duplex_mode = duplex_mode_TDD;
+    }
 
-    } else {
-        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;
-            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;
-        }
+    sync_mode = pbch;
+  } else {
+    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;
+      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;
     }
+  }
 
-    //    AssertFatal(UE->rfdevice.trx_start_func(&UE->rfdevice) == 0, "Could not start the device\n");
+  //    AssertFatal(UE->rfdevice.trx_start_func(&UE->rfdevice) == 0, "Could not start the device\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), "");
+  while (oai_exit==0) {
+    AssertFatal ( 0== pthread_mutex_lock(&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
+    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 );
 
-            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;
-            }
+    AssertFatal ( 0== pthread_mutex_unlock(&UE->proc.mutex_synch), "");
 
-            if (current_band==bands_to_scan.nbands) {
-                current_band=0;
-                oai_exit=1;
-            }
+    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
 
-            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;
+        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;
+        }
 
-                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 (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;
+          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;
 
-            break;
+          if (UE->UE_scan_carrier) {
+            openair0_cfg[UE->rf_map.card].autocal[UE->rf_map.chain+i] = 1;
+          }
+        }
 
-        case pbch:
+        break;
 
+      case pbch:
 #if DISABLE_LOG_X
-            printf("[UE thread Synch] Running Initial Synch (mode %d)\n",UE->mode);
+        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);
+        LOG_I(PHY, "[UE thread Synch] Running Initial Synch (mode %d)\n",UE->mode);
 #endif
-            if (nr_initial_sync( UE, UE->mode ) == 0) {
-
-	      //write_output("txdata_sym.m", "txdata_sym", UE->common_vars.rxdata[0], (10*UE->frame_parms.samples_per_slot), 1, 1);
-
-		freq_offset = UE->common_vars.freq_offset; // frequency offset computed with pss in initial sync
-                hw_slot_offset = (UE->rx_offset<<1) / UE->frame_parms.samples_per_slot;
-                printf("Got synch: hw_slot_offset %d, carrier off %d Hz, rxgain %d (DL %u, UL %u), UE_scan_carrier %d\n",
-                       hw_slot_offset,
-                       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 (freq_offset >= 0)
-                            openair0_cfg[UE->rf_map.card].rx_freq[UE->rf_map.chain+i] += abs(freq_offset);
-			  else
-                            openair0_cfg[UE->rf_map.card].rx_freq[UE->rf_map.chain+i] -= abs(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];
-		    }
-
-                    // 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;
-                    }
-
-		if (UE->mode != loop_through_memory) {
-		  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);
-		  //nr_init_frame_parms_ue(&UE->frame_parms);
-		  /*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;
+
+        if (nr_initial_sync( UE, UE->mode ) == 0) {
+          //write_output("txdata_sym.m", "txdata_sym", UE->common_vars.rxdata[0], (10*UE->frame_parms.samples_per_slot), 1, 1);
+          freq_offset = UE->common_vars.freq_offset; // frequency offset computed with pss in initial sync
+          hw_slot_offset = (UE->rx_offset<<1) / UE->frame_parms.samples_per_slot;
+          printf("Got synch: hw_slot_offset %d, carrier off %d Hz, rxgain %d (DL %u, UL %u), UE_scan_carrier %d\n",
+                 hw_slot_offset,
+                 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 (freq_offset >= 0)
+              openair0_cfg[UE->rf_map.card].rx_freq[UE->rf_map.chain+i] += abs(freq_offset);
+            else
+              openair0_cfg[UE->rf_map.card].rx_freq[UE->rf_map.chain+i] -= abs(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];
+          }
+
+          // 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;
+          }
+
+          if (UE->mode != loop_through_memory) {
+            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);
+            //nr_init_frame_parms_ue(&UE->frame_parms);
+            /*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_subframe,
+                         fd);
+                  LOG_I(PHY,"Dummping Frame ... bye bye \n");
+                  fclose(fd);
+                  exit(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_subframe,
-                                       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_subframe,
-                                   fd);
-                            LOG_I(PHY,"Dummping Frame ... bye bye \n");
-                            fclose(fd);
-                            exit(0);
-                        }
-                        //mac_xface->macphy_exit("No cell synchronization found, abandoning"); new mac
-                        return &UE_thread_synch_retval; // not reached
-                    }
+                  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_subframe,
+                       fd);
+                LOG_I(PHY,"Dummping Frame ... bye bye \n");
+                fclose(fd);
+                exit(0);
+              }
+
+              //mac_xface->macphy_exit("No cell synchronization found, abandoning"); new mac
+              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 );
+          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 );
+          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
 
-                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;
-                }
-		if (UE->mode != loop_through_memory)
-		  UE->rfdevice.trx_set_freq_func(&UE->rfdevice,&openair0_cfg[0],0);
-            }// initial_sync=0
-            break;
-        case si:
-        default:
-            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;
+          }
+
+          if (UE->mode != loop_through_memory)
+            UE->rfdevice.trx_set_freq_func(&UE->rfdevice,&openair0_cfg[0],0);
+        }// initial_sync=0
+
+        break;
+
+      case si:
+      default:
+        break;
+    }
 
 #if 0 //defined XFORMS
-	if (do_forms) {
-	  extern FD_lte_phy_scope_ue  *form_ue[NUMBER_OF_UE_MAX];
-	  
-	  phy_scope_UE(form_ue[0],
-		       PHY_vars_UE_g[0][0],
-		       0,0,1);
-	}
-#endif
 
-        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), "");
+    if (do_forms) {
+      extern FD_lte_phy_scope_ue  *form_ue[NUMBER_OF_UE_MAX];
+      phy_scope_UE(form_ue[0],
+                   PHY_vars_UE_g[0][0],
+                   0,0,1);
+    }
 
-        VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME( VCD_SIGNAL_DUMPER_FUNCTIONS_UE_THREAD_SYNCH, 0 );
-    }  // while !oai_exit
+#endif
+    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
+
+  return &UE_thread_synch_retval;
+}
 
-    return &UE_thread_synch_retval;
+void processSubframeRX( PHY_VARS_NR_UE *UE, UE_nr_rxtx_proc_t *proc) {
+  // Process Rx data for one sub-frame
+  if (slot_select_nr(&UE->frame_parms, proc->frame_tx, proc->nr_tti_tx) & NR_DOWNLINK_SLOT) {
+    //clean previous FAPI MESSAGE
+    UE->rx_ind.number_pdus = 0;
+    UE->dci_ind.number_of_dcis = 0;
+    //clean previous FAPI MESSAGE
+    // call L2 for DL_CONFIG (DCI)
+    UE->dcireq.module_id = UE->Mod_id;
+    UE->dcireq.gNB_index = 0;
+    UE->dcireq.cc_id     = 0;
+    UE->dcireq.frame     = proc->frame_rx;
+    UE->dcireq.slot      = proc->nr_tti_rx;
+    nr_ue_dcireq(&UE->dcireq); //to be replaced with function pointer later
+    NR_UE_MAC_INST_t *UE_mac = get_mac_inst(0);
+    UE_mac->scheduled_response.dl_config = &UE->dcireq.dl_config_req;
+    UE_mac->scheduled_response.slot = proc->nr_tti_rx;
+    nr_ue_scheduled_response(&UE_mac->scheduled_response);
+    //write_output("uerxdata_frame.m", "uerxdata_frame", UE->common_vars.rxdata[0], UE->frame_parms.samples_per_frame, 1, 1);
+    printf("Processing slot %d\n",proc->nr_tti_rx);
+#ifdef UE_SLOT_PARALLELISATION
+    phy_procedures_slot_parallelization_nrUE_RX( UE, proc, 0, 0, 1, UE->mode, no_relay, NULL );
+#else
+    phy_procedures_nrUE_RX( UE, proc, 0, 1, UE->mode);
+    //            printf(">>> nr_ue_pdcch_procedures ended\n");
+#endif
+  }
+
+  if (UE->mac_enabled==1) {
+    //  trigger L2 to run ue_scheduler thru IF module
+    //  [TODO] mapping right after NR initial sync
+    if(UE->if_inst != NULL && UE->if_inst->ul_indication != NULL) {
+      UE->ul_indication.module_id = 0;
+      UE->ul_indication.gNB_index = 0;
+      UE->ul_indication.cc_id = 0;
+      UE->ul_indication.frame = proc->frame_rx;
+      UE->ul_indication.slot = proc->nr_tti_rx;
+      UE->if_inst->ul_indication(&UE->ul_indication);
+    }
+  }
 }
 
 /*!
@@ -624,146 +678,173 @@ static void *UE_thread_synch(void *arg) {
  */
 
 static void *UE_thread_rxn_txnp4(void *arg) {
-    static __thread int UE_thread_rxtx_retval;
-    struct nr_rxtx_thread_data *rtd = arg;
-    UE_nr_rxtx_proc_t *proc = rtd->proc;
-    PHY_VARS_NR_UE    *UE   = rtd->UE;
-
-    //proc->counter_decoder = 0;
-    proc->instance_cnt_rxtx=-1;
-    proc->subframe_rx=proc->sub_frame_start;
-
-    proc->dci_err_cnt=0;
-    char threadname[256];
-    sprintf(threadname,"UE_%d_proc_%d", UE->Mod_id, proc->sub_frame_start);
-    cpu_set_t cpuset;
-    CPU_ZERO(&cpuset);
-    char timing_proc_name[256];
-    sprintf(timing_proc_name,"Delay to process sub-frame proc %d",proc->sub_frame_start);
-
-    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);
-
-    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");
-        }
-
-//        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
-        if (slot_select_nr(&UE->frame_parms, proc->frame_tx, proc->nr_tti_tx) & NR_DOWNLINK_SLOT) {
-
-            //clean previous FAPI MESSAGE
-            UE->rx_ind.number_pdus = 0;
-            UE->dci_ind.number_of_dcis = 0;
-            //clean previous FAPI MESSAGE
-
-	    // call L2 for DL_CONFIG (DCI)
-	    UE->dcireq.module_id = UE->Mod_id;
-	    UE->dcireq.gNB_index = 0;
-	    UE->dcireq.cc_id     = 0;
-	    UE->dcireq.frame     = proc->frame_rx;
-	    UE->dcireq.slot      = proc->nr_tti_rx;
-	    nr_ue_dcireq(&UE->dcireq); //to be replaced with function pointer later
-
-	    NR_UE_MAC_INST_t *UE_mac = get_mac_inst(0);
-	    UE_mac->scheduled_response.dl_config = &UE->dcireq.dl_config_req;
-	    UE_mac->scheduled_response.slot = proc->nr_tti_rx;
-	    nr_ue_scheduled_response(&UE_mac->scheduled_response);
-	    
-#ifdef UE_SLOT_PARALLELISATION
-            phy_procedures_slot_parallelization_nrUE_RX( UE, proc, 0, 0, 1, UE->mode, no_relay, NULL );
-#else
-            phy_procedures_nrUE_RX( UE, proc, 0, 1, UE->mode);
-	    //            printf(">>> nr_ue_pdcch_procedures ended\n");
-
-#endif
-        }
-
-#if UE_TIMING_TRACE
-        start_meas(&UE->generic_stat);
-#endif
-	//printf(">>> mac init\n");
-
-        if (UE->mac_enabled==1) {
-
-            //  trigger L2 to run ue_scheduler thru IF module
-            //  [TODO] mapping right after NR initial sync
-            if(UE->if_inst != NULL && UE->if_inst->ul_indication != NULL){
-                UE->ul_indication.module_id = 0;
-                UE->ul_indication.gNB_index = 0;
-                UE->ul_indication.cc_id = 0;
-                UE->ul_indication.frame = proc->frame_rx; 
-                UE->ul_indication.slot = proc->nr_tti_rx;
-                
-                UE->if_inst->ul_indication(&UE->ul_indication);
-            }
-	}
-    
-#if UE_TIMING_TRACE
-        stop_meas(&UE->generic_stat);
-#endif
-	//printf(">>> mac ended\n");
+  struct nr_rxtx_thread_data *rtd = arg;
+  UE_nr_rxtx_proc_t *proc = rtd->proc;
+  PHY_VARS_NR_UE    *UE   = rtd->UE;
+  //proc->counter_decoder = 0;
+  proc->instance_cnt_rxtx=-1;
+  proc->subframe_rx=proc->sub_frame_start;
+  proc->dci_err_cnt=0;
+  char threadname[256];
+  sprintf(threadname,"UE_%d_proc_%d", UE->Mod_id, proc->sub_frame_start);
+  cpu_set_t cpuset;
+  CPU_ZERO(&cpuset);
+  char timing_proc_name[256];
+  sprintf(timing_proc_name,"Delay to process sub-frame proc %d",proc->sub_frame_start);
+
+  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);
+
+  while (!oai_exit) {
+    AssertFatal( 0 == pthread_mutex_lock(&proc->mutex_rxtx), "[SCHED][UE] error locking mutex for UE RXTX\n" );
+
+    while (proc->instance_cnt_rxtx < 0) {
+      // most of the time, the thread is waiting here
+      pthread_cond_wait( &proc->cond_rxtx, &proc->mutex_rxtx );
+    }
 
-        // Prepare the future Tx data
+    AssertFatal ( 0== pthread_mutex_unlock(&proc->mutex_rxtx), "[SCHED][UE] error unlocking mutex for UE RXn_TXnp4\n" );
+    processSubframeRX(UE, proc);
+    //printf(">>> mac ended\n");
+    // Prepare the future Tx data
 #if 0
 #ifndef NO_RAT_NR
-        if (slot_select_nr(&UE->frame_parms, proc->frame_tx, proc->nr_tti_tx) & NR_UPLINK_SLOT)
+
+    if (slot_select_nr(&UE->frame_parms, proc->frame_tx, proc->nr_tti_tx) & NR_UPLINK_SLOT)
 #else
-        if ((subframe_select( &UE->frame_parms, proc->subframe_tx) == SF_UL) ||
-                (UE->frame_parms.frame_type == FDD) )
+    if ((subframe_select( &UE->frame_parms, proc->subframe_tx) == SF_UL) ||
+        (UE->frame_parms.frame_type == FDD) )
 #endif
-            if (UE->mode != loop_through_memory)
-                phy_procedures_nrUE_TX(UE,proc,0,0,UE->mode,no_relay);
-                //phy_procedures_UE_TX(UE,proc,0,0,UE->mode,no_relay);
+      if (UE->mode != loop_through_memory)
+        phy_procedures_nrUE_TX(UE,proc,0,0,UE->mode,no_relay);
+
+    //phy_procedures_UE_TX(UE,proc,0,0,UE->mode,no_relay);
 #endif
 #if 0
-        if ((subframe_select( &UE->frame_parms, proc->subframe_tx) == SF_S) &&
-                (UE->frame_parms.frame_type == TDD))
-            if (UE->mode != loop_through_memory)
-                //phy_procedures_UE_S_TX(UE,0,0,no_relay);
+
+    if ((subframe_select( &UE->frame_parms, proc->subframe_tx) == SF_S) &&
+        (UE->frame_parms.frame_type == TDD))
+      if (UE->mode != loop_through_memory)
+        //phy_procedures_UE_S_TX(UE,0,0,no_relay);
         updateTimes(current, &t3, 10000, timing_proc_name);
-#endif
 
-        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");
-        }
-        proc->instance_cnt_rxtx--;
+#endif
+    AssertFatal( 0 == pthread_mutex_lock(&proc->mutex_rxtx), "[SCHED][UE] error locking mutex for UE RXTX\n" );
+    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");
-        }
+    AssertFatal (0 == pthread_mutex_unlock(&proc->mutex_rxtx), "[SCHED][UE] error unlocking mutex for UE RXTX\n" );
+  }
+
+  // thread finished
+  free(arg);
+  return NULL;
+}
+
+void readFrame(PHY_VARS_NR_UE *UE,  openair0_timestamp *timestamp) {
+  void *rxp[NB_ANTENNAS_RX];
+  void *dummy_tx[UE->frame_parms.nb_antennas_tx];
+
+  for (int i=0; i<UE->frame_parms.nb_antennas_tx; i++)
+    dummy_tx[i]=malloc16_clear(UE->frame_parms.samples_per_subframe*4);
+
+  for(int x=0; x<10; x++) {
+    for (int i=0; i<UE->frame_parms.nb_antennas_rx; i++)
+      rxp[i] = ((void *)&UE->common_vars.rxdata[i][0]) + 4*x*UE->frame_parms.samples_per_subframe;
+
+    AssertFatal( UE->frame_parms.samples_per_subframe ==
+                 UE->rfdevice.trx_read_func(&UE->rfdevice,
+                                            timestamp,
+                                            rxp,
+                                            UE->frame_parms.samples_per_subframe,
+                                            UE->frame_parms.nb_antennas_rx), "");
+  }
+
+  for (int i=0; i<UE->frame_parms.nb_antennas_tx; i++)
+    free(dummy_tx[i]);
+}
+
+void trashFrame(PHY_VARS_NR_UE *UE, openair0_timestamp *timestamp) {
+  void *dummy_tx[UE->frame_parms.nb_antennas_tx];
+
+  for (int i=0; i<UE->frame_parms.nb_antennas_tx; i++)
+    dummy_tx[i]=malloc16_clear(UE->frame_parms.samples_per_subframe*4);
+
+  void *dummy_rx[UE->frame_parms.nb_antennas_rx];
+
+  for (int i=0; i<UE->frame_parms.nb_antennas_rx; i++)
+    dummy_rx[i]=malloc16(UE->frame_parms.samples_per_subframe*4);
+
+  for (int sf=0; sf<NR_NUMBER_OF_SUBFRAMES_PER_FRAME; sf++) {
+    //      printf("Reading dummy sf %d\n",sf);
+    UE->rfdevice.trx_read_func(&UE->rfdevice,
+                               timestamp,
+                               dummy_rx,
+                               UE->frame_parms.samples_per_subframe,
+                               UE->frame_parms.nb_antennas_rx);
+    usleep(500); // this sleep improves in the case of simulated RF and doesn't harm with true radio
+  }
+
+  for (int i=0; i<UE->frame_parms.nb_antennas_tx; i++)
+    free(dummy_tx[i]);
+
+  for (int i=0; i<UE->frame_parms.nb_antennas_rx; i++)
+    free(dummy_rx[i]);
+}
+
+void syncInFrame(PHY_VARS_NR_UE *UE, openair0_timestamp *timestamp) {
+  if (UE->no_timing_correction==0) {
+    LOG_I(PHY,"Resynchronizing RX by %d samples (mode = %d)\n",UE->rx_offset,UE->mode);
+    void *dummy_tx[UE->frame_parms.nb_antennas_tx];
+
+    for (int i=0; i<UE->frame_parms.nb_antennas_tx; i++)
+      dummy_tx[i]=malloc16_clear(UE->frame_parms.samples_per_subframe*4);
+
+    for ( int size=UE->rx_offset ; size > 0 ; size -= UE->frame_parms.samples_per_subframe ) {
+      int unitTransfer=size>UE->frame_parms.samples_per_subframe ? UE->frame_parms.samples_per_subframe : size ;
+      AssertFatal(unitTransfer ==
+                  UE->rfdevice.trx_read_func(&UE->rfdevice,
+                                             timestamp,
+                                             (void **)UE->common_vars.rxdata,
+                                             unitTransfer,
+                                             UE->frame_parms.nb_antennas_rx),"");
     }
 
-// thread finished
-    free(arg);
-    return &UE_thread_rxtx_retval;
+    for (int i=0; i<UE->frame_parms.nb_antennas_tx; i++)
+      free(dummy_tx[i]);
+  }
+}
+
+int computeSamplesShift(PHY_VARS_NR_UE *UE) {
+  if ( getenv("RFSIMULATOR") != 0) {
+    LOG_E(PHY,"SET rx_offset %d \n",UE->rx_offset);
+    //UE->rx_offset_diff=0;
+    return 0;
+  }
+
+  // compute TO compensation that should be applied for this frame
+  if ( UE->rx_offset < 5*UE->frame_parms.samples_per_slot  &&
+       UE->rx_offset > 0 )
+    return -1 ;
+
+  if ( UE->rx_offset > 5*UE->frame_parms.samples_per_slot &&
+       UE->rx_offset < 10*UE->frame_parms.samples_per_slot )
+    return 1;
+
+  return 0;
 }
 
 /*!
@@ -777,389 +858,269 @@ static void *UE_thread_rxn_txnp4(void *arg) {
  */
 
 void *UE_thread(void *arg) {
+  PHY_VARS_NR_UE *UE = (PHY_VARS_NR_UE *) arg;
+  //  int tx_enabled = 0;
+  openair0_timestamp timestamp;
+  void *rxp[NB_ANTENNAS_RX], *txp[NB_ANTENNAS_TX];
+  int start_rx_stream = 0;
+  int i;
+  char threadname[128];
+  int th_id;
+  const uint16_t table_sf_slot[20] = {0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9};
+
+  for (int i=0; i<  RX_NB_TH_MAX; i++ )
+    UE->proc.proc_rxtx[i].counter_decoder = 0;
+
+  static uint8_t thread_idx = 0;
+  cpu_set_t cpuset;
+  CPU_ZERO(&cpuset);
+
+  if ( threads.main != -1 )
+    CPU_SET(threads.main, &cpuset);
+
+  sprintf(threadname, "Main UE %d", UE->Mod_id);
+  init_thread(100000, 500000, FIFO_PRIORITY, &cpuset,threadname);
+
+  if ((oaisim_flag == 0) && (UE->mode !=loop_through_memory))
+    AssertFatal(0== openair0_device_load(&(UE->rfdevice), &openair0_cfg[0]), "");
+
+  UE->rfdevice.host_type = RAU_HOST;
+  init_UE_threads(UE);
+#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 nb_slot_frame = 10*UE->frame_parms.slots_per_subframe;
+  int slot_nr=-1;
 
-    PHY_VARS_NR_UE *UE = (PHY_VARS_NR_UE *) arg;
-    //  int tx_enabled = 0;
-    openair0_timestamp timestamp;
-    void* rxp[NB_ANTENNAS_RX], *txp[NB_ANTENNAS_TX];
-    int start_rx_stream = 0;
-    int i;
-    char threadname[128];
-    int th_id;
-    for (int i=0; i<  RX_NB_TH_MAX; i++ ) 
-       UE->proc.proc_rxtx[i].counter_decoder = 0;
-
-    static uint8_t thread_idx = 0;
-    uint16_t table_sf_slot[20] = {0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9};
-
-
-    cpu_set_t cpuset;
-    CPU_ZERO(&cpuset);
-    if ( threads.main != -1 )
-        CPU_SET(threads.main, &cpuset);
-    sprintf(threadname, "Main UE %d", UE->Mod_id);
-    init_thread(100000, 500000, FIFO_PRIORITY, &cpuset,threadname);
-    
-    if ((oaisim_flag == 0) && (UE->mode !=loop_through_memory))
-        AssertFatal(0== openair0_device_load(&(UE->rfdevice), &openair0_cfg[0]), "");
-    UE->rfdevice.host_type = RAU_HOST;
+  //int cumulated_shift=0;
+  if ((oaisim_flag == 0) && (UE->mode != loop_through_memory))
+    AssertFatal(UE->rfdevice.trx_start_func(&UE->rfdevice) == 0, "Could not start the device\n");
 
-    init_UE_threads(UE);
+  while (!oai_exit) {
+    AssertFatal ( 0== pthread_mutex_lock(&UE->proc.mutex_synch), "");
+    int instance_cnt_synch = UE->proc.instance_cnt_synch;
+    int is_synchronized    = UE->is_synchronized;
+    AssertFatal ( 0== pthread_mutex_unlock(&UE->proc.mutex_synch), "");
+
+    if (is_synchronized == 0) {
+#if BASIC_SIMULATOR
+
+      while (!((instance_cnt_synch = UE->proc.instance_cnt_synch) < 0)) {
+        printf("ue sync not ready\n");
+        usleep(500*1000);
+      }
 
-#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 nb_slot_frame = 10*UE->frame_parms.slots_per_subframe;
-    int slot_nr=-1;
-    //int cumulated_shift=0;
-    if ((oaisim_flag == 0) && (UE->mode != loop_through_memory))
-      AssertFatal(UE->rfdevice.trx_start_func(&UE->rfdevice) == 0, "Could not start the device\n");
-    while (!oai_exit) {
-        AssertFatal ( 0== pthread_mutex_lock(&UE->proc.mutex_synch), "");
-        int instance_cnt_synch = UE->proc.instance_cnt_synch;
-        int is_synchronized    = UE->is_synchronized;
-        AssertFatal ( 0== pthread_mutex_unlock(&UE->proc.mutex_synch), "");
-
-        if (is_synchronized == 0) {
+      if (UE->mode != loop_through_memory) {
+        if (instance_cnt_synch < 0) {  // we can invoke the synch
+          // grab 10 ms of signal and wakeup synch thread
+          readFrame(UE, &timestamp);
+          AssertFatal( 0 == pthread_mutex_lock(&UE->proc.mutex_synch), "");
+          AssertFatal( 0 == ++UE->proc.instance_cnt_synch, "[SCHED][UE] UE sync thread busy!!\n" );
+          AssertFatal( 0 == pthread_cond_signal(&UE->proc.cond_synch), "");
+          AssertFatal( 0 == pthread_mutex_unlock(&UE->proc.mutex_synch), "");
+        } else {
+          // grab 10 ms of signal into dummy buffer to wait result of sync detection
+          trashFrame(UE, &timestamp);
+        }
+      }
+
+      continue;
+    }
+
+    if (start_rx_stream==0) {
+      start_rx_stream=1;
+
+      if (UE->mode != loop_through_memory) {
+        syncInFrame(UE, &timestamp);
+        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=1; th_id < RX_NB_TH; th_id++) {
+          UE->proc.proc_rxtx[th_id].frame_rx = UE->proc.proc_rxtx[0].frame_rx;
+        }
+
+        //printf("first stream frame rx %d\n",UE->proc.proc_rxtx[0].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),"");
+        //write_output("txdata_sym.m", "txdata_sym", UE->common_vars.rxdata[0], (UE->frame_parms.ofdm_symbol_size+UE->frame_parms.nb_prefix_samples0), 1, 1);
+        //nr_slot_fep(UE,0, 0, 0, 1, 1, NR_PDCCH_EST);
+      } //UE->mode != loop_through_memory
+      else
+        rt_sleep_ns(1000*1000);
+
+      continue;
+    }
+
+    thread_idx++;
+    thread_idx%=RX_NB_TH;
+    //printf("slot_nr %d nb slot frame %d\n",slot_nr, nb_slot_frame);
+    slot_nr++;
+    slot_nr %= nb_slot_frame;
+    UE_nr_rxtx_proc_t *proc = &UE->proc.proc_rxtx[thread_idx];
+    // update thread index for received subframe
+    UE->current_thread_id[slot_nr] = thread_idx;
 #if BASIC_SIMULATOR
-	  while (!((instance_cnt_synch = UE->proc.instance_cnt_synch) < 0)) {
-	    printf("ue sync not ready\n");
-	    usleep(500*1000);
-	  }
+
+    for (int t = 0; t < RX_NB_TH; 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_W(PHY,"is_synchro %d\n" ,  is_synchronized );
-            if (instance_cnt_synch < 0) {  // we can invoke the synch
-                // grab 10 ms of signal and wakeup synch thread
-	if (UE->mode != loop_through_memory) {
-	  void *dummy_tx[UE->frame_parms.nb_antennas_tx];
-	  for (int i=0; i<UE->frame_parms.nb_antennas_tx; i++)
-	    dummy_tx[i]=malloc16_clear(UE->frame_parms.samples_per_subframe*4);
-	  for(int x=0; x<10; x++) {
-	    for (int i=0; i<UE->frame_parms.nb_antennas_rx; i++)
-	      rxp[i] = ((void*)&UE->common_vars.rxdata[i][0]) + 4*x*UE->frame_parms.samples_per_subframe;
-	    AssertFatal( UE->frame_parms.samples_per_subframe ==
-			 UE->rfdevice.trx_read_func(&UE->rfdevice,
-						    &timestamp,
-						    rxp,
-						    UE->frame_parms.samples_per_subframe,
-						    UE->frame_parms.nb_antennas_rx), "");
-	  }
-	  for (int i=0; i<UE->frame_parms.nb_antennas_tx; i++)
-	    free(dummy_tx[i]);
-	}
-	AssertFatal( 0 == pthread_mutex_lock(&UE->proc.mutex_synch), "");
-	AssertFatal( 0 == ++UE->proc.instance_cnt_synch, "[SCHED][UE] UE sync thread busy!!\n" );
-        AssertFatal( 0 == pthread_cond_signal(&UE->proc.cond_synch), "");
-	AssertFatal( 0 == pthread_mutex_unlock(&UE->proc.mutex_synch), "");
+    LOG_D(PHY,"Process slot %d thread Idx %d \n", slot_nr, UE->current_thread_id[slot_nr]);
+    proc->nr_tti_rx=slot_nr;
+    proc->subframe_rx=table_sf_slot[slot_nr];
+    proc->frame_tx = proc->frame_rx;
+    proc->nr_tti_tx= slot_nr + DURATION_RX_TO_TX;
+
+    if (proc->nr_tti_tx > nb_slot_frame) {
+      proc->frame_tx = (proc->frame_tx + 1)%MAX_FRAME_NUMBER;
+      proc->nr_tti_tx %= nb_slot_frame;
+    }
+    if(slot_nr == 0) {
+      UE->proc.proc_rxtx[0].frame_rx++;
+      
+      //UE->proc.proc_rxtx[1].frame_rx++;
+      for (th_id=1; th_id < RX_NB_TH; th_id++) {
+	UE->proc.proc_rxtx[th_id].frame_rx = UE->proc.proc_rxtx[0].frame_rx;
+      }
+    }
+    
+    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+
+						    slot_nr*UE->frame_parms.samples_per_slot];
+
+      for (i=0; i<UE->frame_parms.nb_antennas_tx; i++)
+        txp[i] = (void *)&UE->common_vars.txdata[i][((slot_nr+2)%NR_NUMBER_OF_SUBFRAMES_PER_FRAME)*UE->frame_parms.samples_per_slot];
+
+      int readBlockSize, writeBlockSize;
+
+      if (slot_nr<(nb_slot_frame - 1)) {
+        readBlockSize=UE->frame_parms.samples_per_slot;
+        writeBlockSize=UE->frame_parms.samples_per_slot;
       } else {
-	// grab 10 ms of signal into dummy buffer to wait result of sync detection
-	if (UE->mode != loop_through_memory) {
-	  void *dummy_tx[UE->frame_parms.nb_antennas_tx];
-	  for (int i=0; i<UE->frame_parms.nb_antennas_tx; i++)
-	    dummy_tx[i]=malloc16_clear(UE->frame_parms.samples_per_subframe*4);
-	  void *dummy_rx[UE->frame_parms.nb_antennas_rx];
-	  for (int i=0; i<UE->frame_parms.nb_antennas_rx; i++)
-	    dummy_rx[i]=malloc16(UE->frame_parms.samples_per_subframe*4);
-	  for (int sf=0; sf<NR_NUMBER_OF_SUBFRAMES_PER_FRAME; sf++) {
-	    //	    printf("Reading dummy sf %d\n",sf);
-	    UE->rfdevice.trx_read_func(&UE->rfdevice,
-				       &timestamp,
-				       dummy_rx,
-				       UE->frame_parms.samples_per_subframe,
-				       UE->frame_parms.nb_antennas_rx);
-	   usleep(500); // this sleep improves in the case of simulated RF and doesn't harm with true radio
-	  
-	  }
-	  for (int i=0; i<UE->frame_parms.nb_antennas_tx; i++)
-	    free(dummy_tx[i]);
-	  for (int i=0; i<UE->frame_parms.nb_antennas_rx; i++)
-	    free(dummy_rx[i]);
-	}
-            }
+        UE->rx_offset_diff = computeSamplesShift(UE);
+        readBlockSize=UE->frame_parms.samples_per_slot -
+                      UE->frame_parms.ofdm_symbol_size -
+                      UE->frame_parms.nb_prefix_samples0 -
+                      UE->rx_offset_diff;
+        writeBlockSize=UE->frame_parms.samples_per_slot -
+                       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_slot) -
+                       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( slot_nr==(nb_slot_frame-1)) {
+        // 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,
+                                                 &timestamp,
+                                                 (void **)UE->common_vars.rxdata,
+                                                 first_symbols,
+                                                 UE->frame_parms.nb_antennas_rx),"");
+        else
+          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,"");
 
-        } // 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);
-		    void *dummy_tx[UE->frame_parms.nb_antennas_tx];
-		    for (int i=0; i<UE->frame_parms.nb_antennas_tx; i++)
-		      dummy_tx[i]=malloc16_clear(UE->frame_parms.samples_per_subframe*4);
-		    for ( int size=UE->rx_offset ; size > 0 ; size -= UE->frame_parms.samples_per_subframe ) { 
-		      int unitTransfer=size>UE->frame_parms.samples_per_subframe ? UE->frame_parms.samples_per_subframe : size ;
-		      AssertFatal(unitTransfer ==
-				  UE->rfdevice.trx_read_func(&UE->rfdevice,
-							     &timestamp,
-							     (void**)UE->common_vars.rxdata,
-							     unitTransfer,
-							     UE->frame_parms.nb_antennas_rx),"");
-		    }
-		    for (int i=0; i<UE->frame_parms.nb_antennas_tx; i++)
-		      free(dummy_tx[i]);
-                    }
-                    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=1; th_id < RX_NB_TH; th_id++) {
-                        UE->proc.proc_rxtx[th_id].frame_rx = UE->proc.proc_rxtx[0].frame_rx;
-                    }
-                    
-                    //printf("first stream frame rx %d\n",UE->proc.proc_rxtx[0].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),"");
-                    //write_output("txdata_sym.m", "txdata_sym", UE->common_vars.rxdata[0], (UE->frame_parms.ofdm_symbol_size+UE->frame_parms.nb_prefix_samples0), 1, 1);
-                    //nr_slot_fep(UE,0, 0, 0, 1, 1, NR_PDCCH_EST);
-                } //UE->mode != loop_through_memory
-                else
-                    rt_sleep_ns(1000*1000);
-
-            } else {
-                thread_idx++;
-                if(thread_idx>=RX_NB_TH)
-                    thread_idx = 0;
-
-                //printf("slot_nr %d nb slot frame %d\n",slot_nr, nb_slot_frame);
-
-                slot_nr++;
-                slot_nr %= nb_slot_frame;               
-                UE_nr_rxtx_proc_t *proc = &UE->proc.proc_rxtx[thread_idx];
-                // update thread index for received subframe
-                UE->current_thread_id[slot_nr] = thread_idx;
 
-#if BASIC_SIMULATOR
-                {
-                  int t;
-                  for (t = 0; t < RX_NB_TH; 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 slot %d thread Idx %d \n", slot_nr, UE->current_thread_id[slot_nr]);
-
-
-                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+
-                                 slot_nr*UE->frame_parms.samples_per_slot];
-                    for (i=0; i<UE->frame_parms.nb_antennas_tx; i++)
-		      txp[i] = (void*)&UE->common_vars.txdata[i][((slot_nr+2)%NR_NUMBER_OF_SUBFRAMES_PER_FRAME)*UE->frame_parms.samples_per_slot];
-
-                    int readBlockSize, writeBlockSize;
-                    if (slot_nr<(nb_slot_frame - 1)) {
-                        readBlockSize=UE->frame_parms.samples_per_slot;
-                        writeBlockSize=UE->frame_parms.samples_per_slot;
-                    } else {
-                        // set TO compensation to zero
-                        UE->rx_offset_diff = 0;
-                        // compute TO compensation that should be applied for this frame
-                        if ( UE->rx_offset < 5*UE->frame_parms.samples_per_slot  &&
-                                UE->rx_offset > 0 )
-                            UE->rx_offset_diff = -1 ;
-                        if ( UE->rx_offset > 5*UE->frame_parms.samples_per_slot &&
-                                UE->rx_offset < 10*UE->frame_parms.samples_per_slot )
-                            UE->rx_offset_diff = 1;
-
-
-		        
-                        if ( getenv("RFSIMULATOR") != 0) {
-                           LOG_E(PHY,"AbsSubframe %d.%d TTI SET rx_off_diff to %d rx_offset %d \n",
-                           proc->frame_rx,slot_nr,UE->rx_offset_diff,UE->rx_offset);
-			   //UE->rx_offset_diff=0;	
-                        }
-                        readBlockSize=UE->frame_parms.samples_per_slot -
-                                      UE->frame_parms.ofdm_symbol_size -
-                                      UE->frame_parms.nb_prefix_samples0 -
-                                      UE->rx_offset_diff;
-                        writeBlockSize=UE->frame_parms.samples_per_slot -
-                                       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_slot) -
-                                         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( slot_nr==(nb_slot_frame-1)) {
-                        // 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,
-                                                                   &timestamp,
-                                                                   (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(slot_nr == 0) {
-                        UE->proc.proc_rxtx[0].frame_rx++;
-                        //UE->proc.proc_rxtx[1].frame_rx++;
-                        for (th_id=1; th_id < RX_NB_TH; th_id++) {
-                            UE->proc.proc_rxtx[th_id].frame_rx = UE->proc.proc_rxtx[0].frame_rx;
-                        }
 #ifdef SAIF_ENABLED
-			if (!(proc->frame_rx%4000))
-			  {
-			    printf("frame_rx=%d rx_thread_busy=%ld - rate %8.3f\n",
-				   proc->frame_rx, g_ue_rx_thread_busy,
-				   (float)g_ue_rx_thread_busy/(proc->frame_rx*10+1)*100.0);
-			    fflush(stdout);
-			  }
+
+        if (!(proc->frame_rx%4000)) {
+          printf("frame_rx=%d rx_thread_busy=%ld - rate %8.3f\n",
+                 proc->frame_rx, g_ue_rx_thread_busy,
+                 (float)g_ue_rx_thread_busy/(proc->frame_rx*10+1)*100.0);
+          fflush(stdout);
+        }
+
 #endif
-                    }
-                    //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->nr_tti_rx=slot_nr;
-                    proc->subframe_rx=table_sf_slot[slot_nr];
-		    
-                    proc->frame_tx = proc->frame_rx;
-                    proc->nr_tti_tx= slot_nr + DURATION_RX_TO_TX;
-                    if (proc->nr_tti_tx > nb_slot_frame) {
-                      proc->frame_tx = (proc->frame_tx + 1)%MAX_FRAME_NUMBER;
-                      proc->nr_tti_tx %= nb_slot_frame;
-                    }
-                    proc->subframe_tx=proc->nr_tti_rx;
-                    proc->timestamp_tx = timestamp+
-                                         (DURATION_RX_TO_TX*UE->frame_parms.samples_per_slot)-
-                                         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) {
-                      if (pthread_cond_signal(&proc->cond_rxtx) != 0) {
-                        LOG_E( PHY, "[SCHED][UE %d] ERROR pthread_cond_signal for UE RX thread\n", UE->Mod_id);
-                        exit_fun("nothing to add");
-                      }
-                    } else {
+
+      //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_tx=proc->nr_tti_rx;
+      proc->timestamp_tx = timestamp+
+                           (DURATION_RX_TO_TX*UE->frame_parms.samples_per_slot)-
+                           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) {
 #ifdef SAIF_ENABLED
-						g_ue_rx_thread_busy++;
+        g_ue_rx_thread_busy++;
 #endif
-	              if ( getenv("RFSIMULATOR") != NULL ) {
-		         do {
-			    AssertFatal (pthread_mutex_unlock(&proc->mutex_rxtx) == 0, "");
-			    usleep(100);
-			    AssertFatal (pthread_mutex_lock(&proc->mutex_rxtx) == 0, "");
-			 } while ( proc->instance_cnt_rxtx >= 0);
-
-		      } else
-                      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 > 4)
-                      {
-                        char exit_fun_string[256];
-                        sprintf(exit_fun_string,"[SCHED][UE %d] !!! UE instance_cnt_rxtx > 2 (IC %d) (Proc %d)!!",
-                        			UE->Mod_id, proc->instance_cnt_rxtx,
-                        			UE->current_thread_id[slot_nr]);
-          				printf("%s\n",exit_fun_string);
-          				fflush(stdout);
-          				sleep(1);
-					exit_fun(exit_fun_string);
-                      }
-                    }
-
-                    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);
-                } //UE->mode != loop_through_memory
-                else {
-		  proc->nr_tti_rx=slot_nr;
-		  proc->subframe_rx=table_sf_slot[slot_nr];
-		  if(slot_nr == 0) {
-		    for (th_id=0; th_id < RX_NB_TH; th_id++) {
-		      UE->proc.proc_rxtx[th_id].frame_rx++;
-		    }
-		  }
-		  proc->frame_tx = proc->frame_rx;
-		  proc->nr_tti_tx= slot_nr + DURATION_RX_TO_TX;
-		  if (proc->nr_tti_tx > nb_slot_frame) {
-		    proc->frame_tx = (proc->frame_tx + 1)%MAX_FRAME_NUMBER;
-		    proc->nr_tti_tx %= nb_slot_frame;
-		  }
-		  proc->subframe_tx=table_sf_slot[proc->nr_tti_tx];
-
-		  if (slot_select_nr(&UE->frame_parms, proc->frame_tx, proc->nr_tti_tx) & NR_DOWNLINK_SLOT) {
-		    
-		    //clean previous FAPI MESSAGE
-		    UE->rx_ind.number_pdus = 0;
-		    UE->dci_ind.number_of_dcis = 0;
-		    //clean previous FAPI MESSAGE
-		    
-		    // call L2 for DL_CONFIG (DCI)
-		    UE->dcireq.module_id = UE->Mod_id;
-		    UE->dcireq.gNB_index = 0;
-		    UE->dcireq.cc_id     = 0;
-		    UE->dcireq.frame     = proc->frame_rx;
-		    UE->dcireq.slot      = proc->nr_tti_rx;
-		    nr_ue_dcireq(&UE->dcireq); //to be replaced with function pointer later
-
-		    NR_UE_MAC_INST_t *UE_mac = get_mac_inst(0);
-		    UE_mac->scheduled_response.dl_config = &UE->dcireq.dl_config_req;
-		    UE_mac->scheduled_response.slot = proc->nr_tti_rx;
-		    nr_ue_scheduled_response(&UE_mac->scheduled_response);
-		    
-		    //write_output("uerxdata_frame.m", "uerxdata_frame", UE->common_vars.rxdata[0], UE->frame_parms.samples_per_frame, 1, 1);
-
-		    printf("Processing slot %d\n",proc->nr_tti_rx);
-		    phy_procedures_nrUE_RX( UE, proc, 0, 1, UE->mode);
-		  }
-		  
-		  if(UE->if_inst != NULL && UE->if_inst->ul_indication != NULL){
-		    UE->ul_indication.module_id = 0;
-		    UE->ul_indication.gNB_index = 0;
-		    UE->ul_indication.cc_id = 0;
-		    UE->ul_indication.frame = proc->frame_rx; 
-		    UE->ul_indication.slot = proc->nr_tti_rx;
-		    
-		    UE->if_inst->ul_indication(&UE->ul_indication);
-		  }
-		  
-		  getchar();
-		} // else loop_through_memory
-            } // start_rx_stream==1
-        } // UE->is_synchronized==1
-	
-    } // while !oai_exit
-    return NULL;
+
+        if ( getenv("RFSIMULATOR") != NULL ) {
+          do {
+            AssertFatal (pthread_mutex_unlock(&proc->mutex_rxtx) == 0, "");
+            usleep(100);
+            AssertFatal (pthread_mutex_lock(&proc->mutex_rxtx) == 0, "");
+          } while ( proc->instance_cnt_rxtx >= 0);
+        } else
+          LOG_E( PHY, "[SCHED][UE %d] !! UE RX thread busy (IC %d)!!\n", UE->Mod_id, proc->instance_cnt_rxtx);
+
+        AssertFatal( proc->instance_cnt_rxtx <= 4, "[SCHED][UE %d] !!! UE instance_cnt_rxtx > 2 (IC %d) (Proc %d)!!",
+                     UE->Mod_id, proc->instance_cnt_rxtx,
+                     UE->current_thread_id[slot_nr]);
+      }
+
+      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);
+    } //UE->mode != loop_through_memory
+    else {
+
+      processSubframeRX(UE,proc);
+      getchar();
+    } // else loop_through_memory
+  } // while !oai_exit
+
+  return NULL;
 }
 
 /*!
@@ -1175,84 +1136,78 @@ void *UE_thread(void *arg) {
  * and the locking between them.
  */
 void init_UE_threads(PHY_VARS_NR_UE *UE) {
-    struct nr_rxtx_thread_data *rtd;
-
-    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;
-
-    // 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 nr_rxtx_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_thread_rxn_txnp4, rtd);
-
+  struct nr_rxtx_thread_data *rtd;
+  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;
+  // the threads are not yet active, therefore access is allowed without locking
+  for (int i=0; i<RX_NB_TH; i++) {
+    rtd = calloc(1, sizeof(struct nr_rxtx_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=RX_NB_TH;
+    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,RX_NB_TH, i);
+    pthread_create(&UE->proc.proc_rxtx[i].pthread_rxtx, NULL, UE_thread_rxn_txnp4, rtd);
 #ifdef UE_DLSCH_PARALLELISATION
-        pthread_mutex_init(&UE->proc.proc_rxtx[i].mutex_dlsch_td,NULL);
-        pthread_cond_init(&UE->proc.proc_rxtx[i].cond_dlsch_td,NULL);
-        pthread_create(&UE->proc.proc_rxtx[i].pthread_dlsch_td,NULL,nr_dlsch_decoding_2thread0, rtd);
-        //thread 2
-        pthread_mutex_init(&UE->proc.proc_rxtx[i].mutex_dlsch_td1,NULL);
-        pthread_cond_init(&UE->proc.proc_rxtx[i].cond_dlsch_td1,NULL);
-        pthread_create(&UE->proc.proc_rxtx[i].pthread_dlsch_td1,NULL,nr_dlsch_decoding_2thread1, rtd);
+    pthread_mutex_init(&UE->proc.proc_rxtx[i].mutex_dlsch_td,NULL);
+    pthread_cond_init(&UE->proc.proc_rxtx[i].cond_dlsch_td,NULL);
+    pthread_create(&UE->proc.proc_rxtx[i].pthread_dlsch_td,NULL,nr_dlsch_decoding_2thread0, rtd);
+    //thread 2
+    pthread_mutex_init(&UE->proc.proc_rxtx[i].mutex_dlsch_td1,NULL);
+    pthread_cond_init(&UE->proc.proc_rxtx[i].cond_dlsch_td1,NULL);
+    pthread_create(&UE->proc.proc_rxtx[i].pthread_dlsch_td1,NULL,nr_dlsch_decoding_2thread1, rtd);
 #endif
-
 #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);
+    //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);
 }
 
 
 #ifdef OPENAIR2
-/*
-void fill_ue_band_info(void) {
-
-    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;
-            }
-    }
-}*/
+  /*
+  void fill_ue_band_info(void) {
+
+  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;
+  }
+  }
+  }*/
 #endif
 
 /*