/*
 * Simple resource management base classes
 * Implementation file
 *
 * $Id$
 */

#include <stdlib.h>			// for NULL
#include "resource.h"


/* FUNCTIONS */

resource::resource() : ref(0) {
}

resource::~resource() {}

void resource::alloc() {
  if (ref==0) load();
  ref++;
}

void resource::dealloc() {
  if (ref>0) {
    ref--;
    if (ref==0) unload();
  } else {
    throw resource_exception("Resource already unloaded\n");
  }
}

resourceman::resourceman(int static_ids) : num_static_ids(static_ids) {
  int i;

  staticres = new resource*[static_ids];
  if (!staticres) throw resource_exception("Out of memory");

  for (i=0; i<num_static_ids; i++) {
    staticres[i] = NULL;
  }
}

resourceman::~resourceman() {
  int i;

  for (i=0; i<num_static_ids; i++) {
    if (staticres[i]) delete staticres[i];
  }
  delete staticres;
}

void resourceman::init_resource(int id, resource *r) {
  if (id<0 || id>=num_static_ids)
    throw resource_exception("@Bad resource ID: %d\n", id);

  if (!staticres[id]) {
    staticres[id] = r;
  } else {
    throw resource_exception("@Resource ID %d already initialized\n", id);
  }
}

resource *resourceman::allocate(int id) {
  if (id<0 || id>=num_static_ids)
    throw resource_exception("@Bad resource ID: %d\n", id);

  staticres[id]->alloc();
  return staticres[id];
}

void resourceman::deallocate(int id) {
  if (id<0 || id>=num_static_ids)
    throw resource_exception("@Bad resource ID: %d\n", id);

  staticres[id]->dealloc();
}
