#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <limits.h>
#include "sbs.h"

List *
add_most_recent(char *name, List *head)
{
    List *lptr;
    char *sptr;
    char base[PATH_MAX];
    
    /* get the base part of name with out the version number to use
     * for comparisons */
    strncpy(base, name, sizeof(base));
    if((sptr = rindex(base, '.')) == NULL) {
	perror("Bad string index"); /* shouldn't happen */
	exit(1);
    }
    *sptr = '\0';

    /* search for a match on base in the list */

    lptr = head;
    while(lptr != NULL) {
	if((strncmp(base, lptr->str, strlen(base))) == 0) {
	    
	    if((get_version_num(name)) > (get_version_num(lptr->str))) {
		strncpy(lptr->str, name, sizeof(lptr->str));
		return head;
	    }
	}
	lptr = lptr->next;
    }

    /* Did not find the base name in the list, so we need to add name */

    lptr = (List *)malloc(sizeof(List));
    strncpy(lptr->str, name, sizeof(lptr->str));
    lptr->next = head;
    return lptr;
}


List *
dequeue(List **head)
{
    List *first = (*head);
    if((*head) != NULL) {
	(*head) = (*head)->next;
	first->next = NULL;
    }
    return first;
}
