#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include <ctype.h>
//
#include "proto.h"
#include "dictionary.h"


CHARACTER *dictionary[65536];
U32 used_characters = 0;

static U32 useddepths[65536/32], usedids[65536/32];


void dictionary_init() {

  U32 i;

  for (i = 0; i < 65536/32; i++)
    useddepths[i] = usedids[i] = 0;
}


S32 is_depth_used(U16 depth) {

  if (useddepths[depth>>5] & (1<<(depth &31)))  return 1;

  return 0;
}


void use_depth(U16 depth, S32 use) {

  if (use)
    useddepths[depth>>5] |= 1<<(depth &31);
  else
    useddepths[depth>>5] &= ~(1<<(depth &31));
}


S32 is_id_used(U16 id) {

  if (get_character_type(id) == CHARACTER_NOT_FOUND)  return 0;
  return 1;
}


void use_id(U16 id) {

  usedids[id>>5] |= 1<<(id &31);
}


S32 get_character_type(U16 id) {

  U32 i;

  for (i = 0; i < used_characters; i++)
    if (dictionary[i]->id == id)         return dictionary[i]->type;

  return CHARACTER_NOT_FOUND;
}


S32 add_character(U16 id, void *data, S32 type) {

  CHARACTER *character;

  if (is_id_used(id)) {
    fprintf(stderr, "Dublicate character ID (%d)\n", id);
    return 1;
  }

  character = malloc(sizeof(CHARACTER));
  if (!character) {
    fprintf(stderr, "No room\n");
    return 1;
  }
  character->type     = type;
  character->data.raw = data;
  character->id       = id;
  character->used     = 0;
  dictionary[used_characters++] = character;

  return 0;
}
