#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "lib.h"
#include "hashwild.h"
#define DMID 14
#include "debug.h"

#ifndef FALSE
#define FALSE 0
#define TRUE (!FALSE)
#endif


Hwild *hwild_new(void)
{
	Hwild *h;
	h = calloc(1,sizeof(Hwild));
	return h;
}
int hwild_add(Hwild *h, char *var, char *val)
{
	Hentry *e;
	int i; 
	i = lib_str_hash(var,MAX_HASHWILD);
	e = calloc(1,sizeof(Hentry));
	e->var = strdup(var);
	e->val = strdup(val);
	if (strchr(var,'*')!=NULL) {
		e->next = h->wildones;
		h->wildones = e;
		return TRUE;
	}
	if (sisdigit(var[0]) && strchr(var,'-')!=NULL) {
		e->next = h->wildones;
		h->wildones = e;
		return TRUE;
	}
	if (sisdigit(var[0]) && strchr(var,'/')!=NULL) {
		e->next = h->wildones;
		h->wildones = e;
		return TRUE;
	}
	e->next = h->table[i];
	h->table[i] = e;
	return TRUE;
}
int hwild_add_simple(Hwild *h, char *var, char *val)
{
	Hentry *e;
	int i; 
	i = lib_str_hash(var,MAX_HASHWILD);
	e = calloc(1,sizeof(Hentry));
	e->var = strdup(var);
	e->val = strdup(val);
	e->next = h->table[i];
	h->table[i] = e;
	return TRUE;
}

int hwild_find(Hwild *h, char *var, char *foundvar, char *val)
{
	int i;
	Hentry *e;
	i = lib_str_hash(var,MAX_HASHWILD);
	if (h==NULL) return FALSE;
	for (e = h->table[i]; e!=NULL; e=e->next) {
		if (strcmp(var,e->var)==0) {
			ncpy(val,e->val,BFSZ-1);
			ncpy(foundvar,e->var,BFSZ-1);
			return TRUE;
		}
	}
	for (e = h->wildones; e!=NULL; e=e->next) {
		if (lib_match_list(e->var,var)) {
			ncpy(val,e->val,BFSZ-1);
			ncpy(foundvar,e->var,BFSZ-1);
			return TRUE;			
		}
	}
	return FALSE;
}
int hwild_free(Hwild *h)
{
	int i;
	Hentry *e,*next;
	for (i=0; i<MAX_HASHWILD; i++) {
	  for (e = h->table[i]; e!=NULL; e=next) {
		  next = e->next;
		  free(e->var);
		  free(e->val);
		  free(e);
	  }
	}	
	for (e = h->wildones; e!=NULL; e=next) {
		  next = e->next;
		  free(e->var);
		  free(e->val);
		  free(e);
	}
	
	free(h);
	return FALSE;
}


