/*
 * 4m v2.15 (namelist.c)
 * (C) Copyright 1990 by Carrick Sean Casey
 * (C) Copyright 1993 by Scott Chasin and Michaeljon Miller
 *
 * 3-24-93 See file COPYING for copyright information.
 *
 * String list management
 */

#include "4m.h"


extern void strunlink ();
extern void strlinkhead ();
extern void perror ();
extern void free ();
extern STRLIST *strgetnode ();
extern int strcasecmp();

void nlput(nl, name)
     NAMLIST *nl;
     char *name;
{
    char *malloc();
    STRLIST *sp;

    for (sp = nl->head; sp; sp = sp->next)
        if (!strcasecmp(name, sp->str)) {
            strunlink(sp, &nl->head, &nl->tail);
            strlinkhead(sp, &nl->head, &nl->tail);
            nl->p = nl->head;
            return;
        }

    if (nl->num < nl->max) {
        if ((sp = (STRLIST *) malloc(sizeof(STRLIST) + strlen(name))) == NULL) {
            perror("nlput: out of memory for names");
            return;
        }
        strcpy(sp->str, name);
        strlinkhead(sp, &nl->head, &nl->tail);
        nl->num++;
    } else {
        sp = nl->tail;
        strunlink(sp, &nl->head, &nl->tail);
        free(sp);
        nl->num--;
        if ((sp = (STRLIST *)
             malloc(sizeof(STRLIST) + strlen(name))) == NULL) {
            perror("nlput: out of memory for names");
            return;
        }
        strcpy(sp->str, name);
        strlinkhead(sp, &nl->head, &nl->tail);
        nl->num++;
    }
    nl->p = nl->head;

    return;
}

char *
nlget(nl)
     NAMLIST *nl;
{
    STRLIST *p = nl->p;

    nl->p = nl->p->next;
    if (nl->p == 0)
        nl->p = nl->head;
    return (p->str);
}

int nlcount(nl)
     NAMLIST *nl;
{
    return (nl->num);
}

void nlinit(nl, max)
     NAMLIST *nl;
     int max;
{
    nl->num = 0;
    nl->p = nl->head = nl->tail = 0;
    nl->max = max;

    return;
}

int nldelete(nl, name)
     NAMLIST *nl;
     char *name;
{
    STRLIST *namep;

    if ((namep = strgetnode(name, nl->head, 1)) == NULL) {
       return (-1);
    } else {
        strunlink(namep, &nl->head, &nl->tail);
        nl->p = nl->head;
        if (nl->num > 0) {
            nl->num--;
            if (nl->num == 0)
                nl->p = 0;  /* just in case */
        }
    }

    return 0;
}

nlclear (nl)
  NAMLIST *nl;
{
  STRLIST *tmp, *p;

  if (nl == NULL) {
     printf("nlclear() has NULL nl\n");
     return;
  }

  p = nl->p;

  while (p)
  {
    tmp = p->next;
    free (p);
    p = tmp;
  } 
  nl->num = 0;
  nl->p = nl->head = nl->tail = 0;
}

