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

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

void process_block_hash(uint8_t block[16], uint8_t messageDigestBuf[48]) {
  md2_first_loop(block, messageDigestBuf, 0);
  md2_second_loop(messageDigestBuf);
}

void apply_padding(size_t len, uint8_t buf[16]) {
  int paddingNeeded = 16 - (len % 16);
  uint8_t originalPadding = paddingNeeded;
  len += paddingNeeded;

  while (paddingNeeded > 0) {
    buf[len - paddingNeeded] = originalPadding;
    paddingNeeded--;
  }
}

void md2_hash_2(size_t len, const uint8_t buf[len], uint8_t out[16]) {
  FILE* file;
  struct stat file_stat;
  if (!open_file((char*)buf, &file, &file_stat)) {
    return;
  }

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

  // === step 4 ===
  uint8_t l = 0;
  uint8_t* checksum = calloc(16, sizeof(uint8_t));
  if (checksum == NULL) {
    return;
  }

  uint8_t* data = malloc(16);
  if (data == NULL) {
    return;
  }
  size_t bytes_left_to_read = file_stat.st_size;
  size_t bytes_left_to_process = 0;

  while (bytes_left_to_read != 0) {
    bytes_left_to_process = bytes_left_to_read >= 16 ? 16 : bytes_left_to_read;

    size_t size = fread(data, 1, bytes_left_to_process, file);
    if (size == 0 || ferror(file) || feof(file)) {
      if (errno == 0) errno = EIO;
      return;
    }

    CHECKSUM_START_MARK
    md2_process_block_checksum(data, checksum, &l);
    CHECKSUM_END_MARK
    process_block_hash(data, messageDigestBuf);

    bytes_left_to_read -= bytes_left_to_process;
  };

  apply_padding(bytes_left_to_process % 16, data);
  md2_process_block_checksum(data, checksum, &l);
  process_block_hash(data, messageDigestBuf);

  process_block_hash(checksum, messageDigestBuf);

  END_MARK
  memcpy(out, messageDigestBuf, 16);

  fclose(file);
  free(data);
  free(messageDigestBuf);
  free(checksum);
}
