#include "ms5611_crc.h"

bool ms5611PromCrcOk(uint16_t prom[8])
{
  const uint16_t crcRead = prom[7];
  uint16_t remainder = 0;

  //  The 4 CRC bits live in the low nibble of word 7 and must read as zero
  //  while the remainder is computed, so the whole low byte is masked off.
  prom[7] &= 0xFF00;

  for (uint8_t i = 0; i < 16; i++)
  {
    if (i & 1) remainder ^= (uint16_t)(prom[i >> 1] & 0x00FF);
    else       remainder ^= (uint16_t)(prom[i >> 1] >> 8);

    for (uint8_t bit = 8; bit > 0; bit--)
    {
      remainder = (remainder & 0x8000) ? (uint16_t)((remainder << 1) ^ 0x3000)
                                       : (uint16_t)(remainder << 1);
    }
  }

  prom[7] = crcRead;

  return (uint16_t)((remainder >> 12) & 0x000F) == (uint16_t)(crcRead & 0x000F);
}
