#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <dirent.h>

#define DIM_MAX 13

struct tabelem {
  char *key;
  void *info;
  };
struct telist {
  struct tabelem *el;
  struct telist *next;
  };
extern struct telist hashtab[DIM_MAX];
typedef struct telist **HASHTABLE ;

struct table
  { 
   HASHTABLE htable;
   struct telist *ls;
  };
 

 

 

/*DEFINIRE DIM_MAX && MAX_DIM(memo)*/





struct telist* init_list ()
{
	struct telist *p;
	p=calloc(1,sizeof(struct telist));
	return p;
}

struct telist* ins_list(struct tabelem *t, struct telist *p)
{
	struct telist *q;
	/*assert(p);*/
	assert(t);
	if (!p->el)
	{
		p->el=t;
		return p;
	}
	q=calloc(1,sizeof(struct telist));
	q->el=t;
	q->next=p;
	return q;
}

struct tabelem *init_tabelem(char *key, void *info)
{
	struct tabelem *p;
	assert(key);
	assert(info);
	p=calloc(1,sizeof(struct tabelem));
	p->key=key;
	p->info=info;
	return p;
}

struct tabelem* cerca_lista(char* key, struct telist *p)
{
	
	assert(key);
	assert(p);
	while((p->el)->key!=key)
	{
		p=p->next;
		if(p->next==NULL) return NULL;
	}
	return (p->el);
}

int hash_key(char* key)
{
	int a, z, q, k;
	z=0;
	assert(key);
	for (k=0; key!='\0'; k++, key++)
	{
		for(q=0; q<=k; q++)
		    a=((*key) * 256)%DIM_MAX;
	        z+=a;
	        z=z%DIM_MAX;
	}
	return z;
}

/* funzioni di table.c */

int table_full(struct table *t)
{/*ma ke cazzo vor di piena?????*/}

void table_init(struct table *t)
{
	t=calloc(1,sizeof(struct table));
}

struct tabelem *table_ins(struct table *t, char *key)
{
	int a;
	HASHTABLE h;
	struct telist *l;
	struct tabelem *tel;
	FILE *f;
        f=fopen(key , "r");
	tel=init_tabelem(key, f);
	t->ls=(ins_list(tel, t->ls));
	a=hash_key(key);
	h=t->htable;
	*(h+a)=(ins_list(tel, l));
	t->htable=h;
	fclose(f);
	return tel;
}

struct tabelem *table_search(struct table *t, char *key)
{
	int a;
	HASHTABLE h;
	struct tabelem *tel;
	h=t->htable;
	a=hash_key(key);
	tel=cerca_lista( key,*(h+a));
	return tel;
}

/* nel modulo nodes.c o qualcosa del genere*/

/* COMPILA FINO A QUI!!!!!!!!!*/

struct table *create_node_table(char *dirname)
{
  struct dirent **namelist;
  struct table *t;
  int n;

  table_init(t);
  n=scandir(".", &namelist, 0 );
  if (n < 0)
     perror("scandir");
  else
  while (n--)
  {
   t=table_ins(t, &namelist[n]->d_name);
  }
  return t;
}
