#include "../../lib/md2_impls/md2_0.h"

#include "../../lib/md2_impls/md2_common.h"

void md2_hash_0(size_t len, const uint8_t buf[len], uint8_t out[16]) {
  // === step 1 ===
  uint8_t* newBuf = md2_add_padding_and_space_for_checksum(buf, &len);
  if (newBuf == NULL) {
    return;
  }

  // === step 2 ===
  md2_checksum(len, newBuf);

  // === step 3 ===
  uint8_t* messageDigestBuf = calloc(48, sizeof(uint8_t));
  if (messageDigestBuf == NULL) {
    return;
  }

  // === step 4 ===
  // <= because we need to hash the last block (the checksum) too
  for (size_t i = 0; i <= (len) / 16; i++) {
    md2_first_loop(newBuf, messageDigestBuf, i);
    md2_second_loop(messageDigestBuf);
  }

  END_MARK
  memcpy(out, messageDigestBuf, 16);

  free(messageDigestBuf);
  free(newBuf);
}