#include <string.h>
#include <stdlib.h>
#include "global.h"
#include "list.h"
#include "constants.h"
#include "window.h"

void init_head(top, max)
  head_ptr top;
  int max;
{
  top->top = NULL;
  top->curr = NULL;
  top->tail = NULL;
  top->count = 0;
  top->max = max;
}

extern server_ptr gsrv;

struct head_struct input;

void set_list_limit(head_ptr list, int limit)
{
  int change;
  list_ptr temp;
  int loop;

  if (limit<0) limit = 0;
  change = list->count - limit;
  list->max = limit;
  if (list->count > limit) list->count = limit;
  for (loop=0;loop<change;loop++)
  {
    temp = list->tail;
    list->tail = list->tail->newer;
    if (list->curr == temp) list->curr = list->tail;
    if (list->top == temp) list->top = list->tail;
    free(temp->text);
    free(temp);
  }
}

void set_hist_limit(int max)
{
  set_list_limit(&input, max);
}

void init_input_list(int max)
{
  init_head(&input, max);
}

void add_list(list, str, type)
  head_ptr list;
  char *str;
  int type;
{
  list_ptr temp;
  int size;

  if ((temp = (list_ptr)malloc(sizeof(struct list_struct))) == NULL)
  {
    say("Could not allocate space for malloc - add_list");
    return;
  }
  if ((temp->text = (char *)malloc(strlen(str)+1)) == NULL)
  {
    say("Could not allocate space for malloc - add_list2");
    return;
  }
  (void)strcpy(temp->text, str);
  temp->type = type;
  temp->newer = NULL;
  temp->older = list->top;
   
  if (list->top)
    list->top->newer = temp;
  if (!list->tail) list->tail = temp;
  list->top = temp;
  list->curr = NULL;
  (list->count)++;
  set_list_limit(list, list->max);
}

void add_input_list(str)
  char *str;
{
  add_list(&input, str, 0);
}

void get_prev_input(str, older)
  char *str;
  int older;
{
  if (older) {
    if (!input.curr) input.curr = input.top;
    else input.curr = input.curr->older;
  } else {
    if (!input.curr) input.curr = input.tail;
    else input.curr = input.curr->newer;
  }
  if (input.curr) (void)strcpy(str, input.curr->text);
  else str[0] = 0;
}
