/*
 * 4m v2.15 (history.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.
 *
 * Message history
 */

#include "4m.h"
#include "externs.h"


STRLIST *histhead, *histtail; /* head and tail of history list */

static int histnum = 0;  /* current number of history entries */
STRLIST *hp;  /* user current location in history list */

/* add a username to the list */
/* called whenever a user sends a personal message to another */

extern void strunlink ();
extern void strlinkhead ();
extern void putl ();
extern void free ();
extern int strcasecmp();

void histput(nick)
     char *nick;
{
    char *malloc();
    STRLIST *sp;

 /* hunt for user within list */
    for (sp = histhead; sp; sp = sp->next)
        if (strcasecmp(nick, sp->str) == 0) {
        /* found user -- put at head of list */
            strunlink(sp, &histhead, &histtail);
            strlinkhead(sp, &histhead, &histtail);
            hp = histhead;
            return;
        }
 /* user wasn't found */
    if (histnum < gv.phistory) {
    /* make a new entry for the user */
        if ((sp = (STRLIST *) malloc(sizeof(STRLIST) + strlen(nick))) == NULL) {
            putl("histput: out of memory for history entries",
                 PL_SCR);
            return;
        }
        strcpy(sp->str, nick);
        strlinkhead(sp, &histhead, &histtail);
        histnum++;
    } else {
    /* history list full, link user to head, remove tail */
        sp = histtail;
        strunlink(sp, &histhead, &histtail);
        free(sp);
        histnum--;
        if ((sp = (STRLIST *)
             malloc(sizeof(STRLIST) + strlen(nick))) == NULL) {
            putl("histput: out of memory for history entries",
                 PL_SCR);
            return;
        }
        strcpy(sp->str, nick);
        strlinkhead(sp, &histhead, &histtail);
        histnum++;
    }
    hp = histhead;
}

/* return a history entry */
/* repeatedly called, will cycle through history entries */

char *
histget()
{
    STRLIST *p = hp;

    hp = hp->next;
    if (hp == 0)
        hp = histhead;
    return (p->str);
}


/* return number of names in current history list */

int histcount()
{
    return (histnum);
}

void histclear()
{
    STRLIST *tmp, *p = hp;

    while (p) {
        tmp = p->next;
        free(p);
        p = tmp;
    }
    histnum = 0;
    hp = histhead = histtail = 0;
    putl("[Tab] History tab cleared.", PL_ALL);

    return;
}
