/*
 * This file is part of the Poliqarp suite.
 * 
 * Copyright (C) 2009 by Instytut Podstaw Informatyki Polskiej
 * Akademii Nauk (IPI PAN; Institute of Computer Science, Polish
 * Academy of Sciences; cf. www.ipipan.waw.pl).  All rights reserved.
 * 
 * This file may be distributed and/or modified under the terms of the
 * GNU General Public License version 2 as published by the Free Software
 * Foundation and appearing in the file gpl.txt included in the packaging
 * of this file.  (See http://www.gnu.org/licenses/translations.html for
 * unofficial translations.)
 * 
 * A commercial license is available from IPI PAN (contact
 * Michal.Ciesiolka@ipipan.waw.pl or ipi@ipipan.waw.pl for more
 * information).  Licensees holding a valid commercial license from IPI
 * PAN may use this file in accordance with that license.
 * 
 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
 * THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE.
 */

#include <assert.h>
#include <stdlib.h>

#include <bp/common.h>
#include <bp/ng/interp.h>
#include <bp/ng/list.h>
#include <bp/ng/segment.h>

static const size_t interp_hashtable_size = 16; /* wild guess */

void segment_create(struct segment *this, bool need_id_index)
{
   int rc;
   assert(this != NULL);
   this->space = true;
   this->orth = NULL;
   this->interps = list_empty;
   if (need_id_index) {
      this->ht = bp_malloc(sizeof *this->ht);
      rc = create_hash_table(this->ht, interp_hashtable_size,
         HASHTABLE_DUPLICATE_KEYS, NULL);
      if (rc != 0)
         bp_system_error("memory allocation error");
   }
   else
      this->ht = NULL;
}

void segment_destroy(struct segment *this)
{
   if (this == NULL)
      return;
   free(this->orth);
   this->orth = NULL;
   list_destroy(&this->interps, interp_free);
   if (this->ht != NULL) {
      destroy_hash_table(this->ht, NULL);
      free(this->ht);
      this->ht = NULL;
   }
}

void segment_add_interp(struct segment *this, struct interp *interp,
   const char *id)
{
   assert(this != NULL);
   if (id != NULL) {
      int rc = hash_table_set(this->ht, id, interp);
      if (rc != 0)
         bp_system_error("memory allocation error");
   }
   list_append(&this->interps, interp);
}

struct interp *segment_get_interp(struct segment *this, const char *id)
{
   assert(this != NULL);
   assert(this->ht != NULL);
   assert(id != NULL);
   return hash_table_get(this->ht, id);
}
