     int remaining_codewords = 0;
     
     // Select Segment
-    int segment_index = blockIdx.x * WARPS_NUM + warpidx;
+    const int block_idx = blockIdx.x + blockIdx.y * gridDim.x;
+    const int segment_index = block_idx * WARPS_NUM + warpidx;
     if ( segment_index >= segment_count )
         return;
     

    
    // Run encoder kernel
    dim3 thread(32 * WARPS_NUM);
    dim3 grid(gpujpeg_div_and_round_up(coder->segment_count, (thread.x / 32)));
    gpujpeg_huffman_encoder_encode_kernel<<<grid, thread>>>(
        coder->d_component, 
        coder->d_segment, 

    return 0;
}


dim3
gpujpeg_huffman_gpu_encoder_grid_size(int tblock_count)
{
    dim3 size(tblock_count);
    while(size.x > 0xffff) {
        size.x = (size.x + 1) >> 1;
        size.y <<= 1;
    }
    return size;
}




/** Documented at declaration */
int
gpujpeg_huffman_gpu_encoder_encode(struct gpujpeg_encoder* encoder, unsigned int * output_byte_count)
