/* This is -*- C -*- */
/* vim: set sw=2: */
/* $Id$ */

/*
 * pos.c
 *
 * Copyright (C) 2003 The Free Software Foundation, Inc.
 *
 * Developed by Jon Trowbridge <trow@gnu.org>
 */

/*
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "pos.h"

static PartOfSpeechTag next_tag       = 1;
static GHashTable *pos_to_str_table   = NULL;
static GHashTable *pos_from_str_table = NULL;

#define POS_TAG_WILDCARD_STR "(*)"
#define POS_TAG_BREAK_STR    "(x)"

PartOfSpeechTag
pos_from_string (const char *str)
{
  gpointer ptag;
  PartOfSpeechTag tag;

  if (! strcmp (str, POS_TAG_WILDCARD_STR))
    return POS_TAG_WILDCARD;
  else if (! strcmp (str, POS_TAG_BREAK_STR))
    return POS_TAG_BREAK;

  if (pos_from_str_table == NULL)
    pos_from_str_table = g_hash_table_new (g_str_hash, g_str_equal);

  if (pos_to_str_table == NULL)
    pos_to_str_table = g_hash_table_new (NULL, NULL);

  ptag = g_hash_table_lookup (pos_from_str_table, str);
  if (ptag == NULL) {
    char *str_copy = g_strdup (str);
    tag = next_tag;
    ++next_tag;
    ptag = GINT_TO_POINTER ((gint)tag);
    g_hash_table_insert (pos_from_str_table, str_copy, ptag);
    g_hash_table_insert (pos_to_str_table, ptag, str_copy);
  } else {
    tag = GPOINTER_TO_INT (ptag);
  }
  
  return tag;
}

const char *
pos_to_string (PartOfSpeechTag tag)
{
  char *str = NULL;

  if (tag == POS_TAG_WILDCARD)
    return POS_TAG_WILDCARD_STR;
  else if (tag == POS_TAG_BREAK)
    return POS_TAG_BREAK_STR;

  if (pos_to_str_table != NULL) {
    str = g_hash_table_lookup (pos_to_str_table, GINT_TO_POINTER ((gint)tag));
  }

  if (tag < 0 || str == NULL)
    return "[Invalid]";

  return str;
}

/* ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** */

PyObject *
py_pos_from_string (PyObject *self, PyObject *args)
{
  char *str;
  PartOfSpeechTag tag;

  if (! PyArg_ParseTuple (args, "s", &str))
    return NULL;

  tag = pos_from_string (str);
  return Py_BuildValue ("i", tag);
}

PyObject *
py_pos_to_string (PyObject *self, PyObject *args)
{
  PartOfSpeechTag tag;
  const char *str;
  PyObject *retval;

  if (! PyArg_ParseTuple (args, "i", &tag))
    return NULL;

  str = pos_to_string (tag);
  retval = Py_BuildValue ("s", str);
  
  return retval;
}

