// ----------------------------------------------------------------------------
//
// Copyright (C) Columbia University, 1994. All Rights Reserved.
// Sameer A. Nene, Shree K. Nayar, Hiroshi Murase
//
// See file LICENSE for details of software license agreement.
//
// ----------------------------------------------------------------------------
//
// registry.C
//
// Author:               Sameer Nene
// Date:                 05/17/94
// Version:              1.0
// Modification History:
// Bugs:
//
// Classes:
//   Entry
//   EntryLink
//   Registry
//   Registrar
//
// Notes:
//   This module contains implementation of classes declared in registry.h.
//   
// ----------------------------------------------------------------------------

#include "registry.h"
#include <string.h>

EntryLink* Registry::d_head_p = 0;
int Registrar::d_count = 0;

Entry::Entry(const char *name, CreateFP createFunc) :
d_name_p(new char[strlen(name) + 1]), d_createFunc(createFunc)
{
  strcpy(d_name_p, name);
}

Entry::~Entry()
{
  delete[] d_name_p;
}

const char *Entry::name() const
{
  return d_name_p;
}

Entry::CreateFP Entry::createFunc() const
{
  return d_createFunc;
}

EntryLink::EntryLink(EntryLink **where, const char *name, CreateFP createFunc)
: Entry(name, createFunc)
{
  d_next_p = *where;
  *where = this;
}

EntryLink::~EntryLink()
{
}

void Registry::add(const char *name, CreateFP createFunc)
{
  new EntryLink(&d_head_p, name, createFunc);
}

void Registry::destroy()
{
  EntryLink *t;
  
  while(d_head_p != 0) {
    t = d_head_p;
    d_head_p = d_head_p -> d_next_p;
    delete t;
  }
}

Entry* Registry::lookup(const char *name)
{
  for(EntryLink *p = d_head_p; p != 0; p = p -> d_next_p)
    if(!strcmp(p -> d_name_p, name))
      return p;
  
  return 0;
}

Registrar::Registrar(const char *name, CreateFP createFunc)
{
  Registry::add(name, createFunc);
  ++d_count;
}

Registrar::~Registrar()
{
  if(!--d_count)
    Registry::destroy();
}
