/* globalias.c -- GlobAlias Queues Building Functions.
 *
 * This file is part of TUA.
 * 
 *   Copyright (C) 1991,96  Lele Gaifax
 *
 *   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.
 *
 */

#include    "tua.h"

#if USE_GLOB_ALIASES

#include    "globalias.h"

void
DEFUN (globalias_insert, (queue, glob_name, alias),
       glob_aliases_queue_t ** queue AND
       CONST char *glob_name AND
       CONST char *alias)
{
  if (*queue == QNULL)
    {
      *queue = (glob_aliases_queue_t *) xmalloc (sizeof (glob_aliases_queue_t));
      (*queue)->Name = savestring (glob_name);
      (*queue)->Alias = savestring (alias);
      (*queue)->Next = QNULL;
    }
  else
    {
      glob_aliases_queue_t *temp, *tail;

      temp = tail = *queue;

      while (temp != QNULL && strcmp (temp->Name, glob_name) != 0)
	{
	  tail = temp;
	  temp = temp->Next;
	}
      
      if (temp == QNULL)
	{
	  temp = (glob_aliases_queue_t *) xmalloc (sizeof (glob_aliases_queue_t));
	  temp->Next = QNULL;
	  temp->Name = savestring (glob_name);
	  temp->Alias = savestring (alias);
	  tail->Next = temp;
	}
    }
  return;
}

CONST char *
DEFUN (globalias_search, (queue, name),
       CONST glob_aliases_queue_t * queue AND
       CONST char *name)
{
  while (queue != QNULL && !wildmat (name, queue->Name))
    queue = queue->Next;

  if (queue == QNULL)
    return name;
  else
    return queue->Alias;
}

#ifdef TEST

static glob_aliases_queue_t *Root = QNULL;

main ()
{
  globalias_insert (&Root, "*ele", "Emanuele");
  globalias_insert (&Root, "ipo*[abc]", "secondo");
  printf ("gabriele -> %s\n", globalias_search (Root, "gabriele"));
  printf ("ipoKJHKJHa -> %s\n", globalias_search (Root, "ipoKJHKJHa"));
  printf ("ipoKJHKJHY -> %s\n", globalias_search (Root, "ipoKJHKJHY"));
  printf ("gabriele -> %s\n", globalias_search (Root, "gabriele"));
  printf ("ipoKJHKJHa -> %s\n", globalias_search (Root, "ipoKJHKJHa"));
  printf ("ipoKJHKJHY -> %s\n", globalias_search (Root, "ipoKJHKJHY"));
}

#endif /* TEST */

#endif /* if USE_GLOB_ALIASES */
