#include <itk/luts.h>
#include <itk/bit_count.h>

#ifndef DO_ITK_INLINE
#include <itk/bit_count.inl>
#endif


unsigned
bit_count( const unsigned char *buf, unsigned width)
{
  unsigned bytes = width / 8;
  unsigned bits  = width % 8;
  unsigned count = 0;
  int      i;

  count += buf[ bytes] & lut_lmask[ bits];
  for (i = 0; i < bytes; ++i) {
    count += lut_bitcount[ buf[ i]];
  }
  return count;
}


unsigned
bit_count( const unsigned char *buf, unsigned start, unsigned end)
{
  unsigned start_byte = start / 8;
  unsigned end_byte   = end / 8;
  unsigned start_bits = 8 - (start % 8);
  unsigned end_bits   = end % 8;
  unsigned count      = 0;
  int      i;

  if (start_byte == end_byte) {
    count = lut_bitcount[ buf[ end_byte]
                        & lut_rmask[ start_bits]
                        & lut_lmask[ end_bits]];
  } else {
    count += lut_bitcount[ buf[ start_byte] & lut_rmask[ start_bits]];
    count += lut_bitcount[ buf[ end_byte  ] & lut_lmask[ end_bits  ]];
    for (i = start_byte + 1; i < end_byte; ++i) {
      count += lut_bitcount[ buf[ i]];
    }
  }
  return count;
}
