/* These routines manage a sorted linked list.
 *
 * $Log: list.c,v $
 * Revision 1.2  1997/06/04 01:12:19  david
 * ANSI-fied the program.
 *
 */

#include <stdio.h>
#include "list.h"

static char *SccsId = "$Id: list.c,v 1.2 1997/06/04 01:12:19 david Exp $";

/* Insert data item 'ptr' into list.
   Return NULL if ok or data pointer if already in list.
*/
/* root = Pointer to Root of list */
/* ptr =  Pointer to data item */
/* compare_function = Pointer to compare function */
char *list_insert( struct list **root, char *ptr, int (*compare_function(void)))
{
struct list *p, *q, *temp;
register int not_found;

for ( p = *root, q = NULL; p != NULL; q = p, p = p->next )
   {
   if ( (not_found = (*compare_function) ( p->data, ptr )) == 0 )
      return p->data; /* Error - Already in list */

   if ( not_found > 0 )
      break;
   }

if ( (temp = (struct list *) malloc( sizeof( struct list ) )) == NULL )
   {
   fprintf( stderr, "list: *** Out of Memory ***\n" );
   exit( 1 );
   }

temp->data = ptr;
temp->next = NULL;

if ( *root == NULL || q == NULL )
   {
   temp->next = *root; /* Insert first */
   *root = temp;
   }
 else
   if ( p == NULL )
      q->next = temp; /* Insert last */
    else
      {
      temp->next = p;
      q->next = temp;
      }

return NULL; /* Everything OK */
}

/* Find 'ptr' data value in list and return 'data'.  Otherwise, return NULL */
/* ptr = Pointer to data */
char *list_find( struct list *root, char *ptr, int (*compare_function(void)) )
{
struct list *p;

for ( p = root; p != NULL; p = p->next )
   if ( (*compare_function) ( p->data, ptr ) == 0 )
      return p->data;

return NULL;
}

struct list *list_next( struct list *ptr )
{
if ( ptr == NULL )
   return NULL;

return ptr->next;
}

char *list_data( struct list *ptr )
{
if ( ptr == NULL )
   return NULL;

return ptr->data;
}
