             break;
         }
         
-        gpujpeg_huffman_gpu_encoder_decompose(temp, nbits, temp2);
-
-        // Emit Huffman symbol for run length / number of bits
-        int i = (r << 4) + nbits;
-        gpujpeg_huffman_gpu_encoder_emit_bits(out_bits, data_compressed, d_table_ac->size[i], d_table_ac->code[i]);
-
-        // Write Category offset
-        gpujpeg_huffman_gpu_encoder_emit_bits(out_bits, data_compressed, nbits, temp2);
+        gpujpeg_huffman_gpu_encode_value(cword_size, cword_value, r, value, d_table_ac);
+        gpujpeg_huffman_gpu_encoder_emit_bits(out_bits, data_compressed, cword_size, cword_value);
     }
 
     return 0;

    if(0 == tid) {
        int & dc = *last_dc;
        result = gpujpeg_huffman_gpu_encoder_encode_block(out_size, dc, (short2*)s_in, data_compressed, d_table_dc, d_table_ac);
    }
    return __ballot(result);
    

}


__device__ static void
gpujpeg_huffman_gpu_encode_value(int & out_nbits, int & out_cword, const int preceding_zero_count, const int value,
                                 const struct gpujpeg_table_huffman_encoder * const d_table) {
    out_cword = value;
    int absolute = value;
    if ( value < 0 ) {
        // valu eis now absolute value of input
        absolute = -absolute;
        // For a negative input, want temp2 = bitwise complement of abs(input)
        // This code assumes we are on a two's complement machine
        out_cword--;
    }

    // Find the number of bits needed for the magnitude of the coefficient
    out_nbits = 0;
    while ( absolute ) {
        out_nbits++;
        absolute >>= 1;
    }
    
    // trim remaining bits
    out_cword &= (1 << out_nbits) - 1;
    
    // find prefix of the codeword and size of the prefix
    const int prefix_idx = preceding_zero_count * 16 + out_nbits;
    out_cword |= d_table->code[prefix_idx] << out_nbits;
    out_nbits += d_table->size[prefix_idx];
}


/**
