                     float diffy  = y_i - y_j;
                     float diffz  = z_i - z_j;
 
-                    if ((diffct * diffct < diffx * diffx + diffy * diffy + diffz * diffz) && output) {
+                    if (i+j >= 0 && i+j<N && output && (diffct * diffct < diffx * diffx + diffy * diffy + diffz * diffz)) {
                         #if write_sums == 1
                         sum++;
                         #endif

                        row_idx[offset + block_start] = bx+tx;
                        #endif
                        #if use_shared == 1
                        //if (offset >= 0 && offset < shared_memory_size-1)
                            sh_col_idx[offset++] = i+j;
                        #else
                        col_idx[offset++] = i+j;

                float diffy = y_i - LDG(y,i+j);
                float diffz = z_i - LDG(z,i+j);

                if (diffct * diffct < diffx * diffx + diffy * diffy + diffz * diffz) {
                    #if write_sums == 1
                    sum++;
                    #endif
