                 Hscan[tx]=H[tx];
             }
             __syncthreads();
-            if (1 <= tx && tx < 8 )
-                Hscan[tx]+=Hscan[tx-1];
-            __syncthreads();
-            if (2 <= tx && tx < 8 )
-                Hscan[tx]+=Hscan[tx-2];
-            __syncthreads();
-            if (4 <= tx && tx < 8 )
-                Hscan[tx]+=Hscan[tx-4];
-            __syncthreads();
-
-            if(tx<7){
-                if(Hscan[tx+1] > medPos && Hscan[tx] < medPos){
-                    *retval=tx+1;
-                    *countAtMed=Hscan[tx];
-                }
-                else if(Hscan[tx]==medPos){
-                  if(Hscan[tx+1]>medPos){
-                     *retval=tx+1;
-                     *countAtMed=Hscan[tx];
-                  }
-                }
-            }
+            scanNeighbor(Hscan, 8, 1, tx);
+            __syncthreads();
+            scanNeighbor(Hscan, 8, 2, tx);
+            __syncthreads();
+            scanNeighbor(Hscan, 8, 4, tx);
+            __syncthreads();
+
+            findMedian(Hscan, 7, tx, retval, countAtMed, medPos);
         }
 
         __device__ void histogramMedianPar32LookupOnly(int* H,int* Hscan, const int medPos,int* retval, int* countAtMed){

            int tx = threadIdx.x;
            if (tx<8)
                luc[tx]=0;
        }

        __device__ void histogramMedianPar8LookupOnly(int* H,int* Hscan, const int medPos,int* retval, int* countAtMed){

            __syncthreads();

            histogramMultipleAdd8(HCoarse,histCoarse, 2*r+1);
            int cols_m_1=cols-1;

             for(int j=r;j<cols-r;j++){
