#include<stdio.h>
#include<string.h>

struct elm{
  char ch;
  int pos;
  struct elm *next_o;
  struct elm *level_d;
};

struct elm *head;
int ncelle=1,nchar=0;

void init(struct elm *ptr)
{
 ptr->pos=0;
 ptr->ch=0;
} 

void insert(char *arr)
{
  struct elm *tmp;
  int j;
  
  tmp=head;

  for(j=0;j<strlen(arr);j++)
    {
      nchar++;
      while((tmp->ch!=arr[j])&&(tmp->ch!=0))           //cerca un char uguale o uno vuoto
	tmp=tmp->next_o;
      if(tmp->ch==0)                                   //é vuoto
      	{
         tmp->ch=arr[j];
         tmp->next_o=(struct elm*)malloc(sizeof(struct elm));   //crea una cella sullo stesso livello
         tmp->level_d=(struct elm*)malloc(sizeof(struct elm));  //crea una cella di sottolivello
         init(tmp->next_o);
         init(tmp->level_d);
	 ncelle++;
	}
      if(j==strlen(arr)-1) tmp->pos=1;                //se alla fine pos=1 =>esiste
      tmp=tmp->level_d;
    }
}

int cerca(char *arr)
{
    struct elm *tmp;
    int j;
  
    tmp=head;
    for(j=0;j<strlen(arr);j++)
    {
      while((arr[j]!=tmp->ch)&&(tmp->ch!=0))        //cerca finche é uguale o é alla fine
	tmp=tmp->next_o;
      
      if(tmp->ch==0) return 0;                     
      printf("\nptr=>%u",tmp);                     //affigge il percorso
      printf("\nchar=>%c",tmp->ch);
      printf("\npos=>%d",tmp->pos);
      printf("\nptrdown=>%u\n",tmp->level_d);
      if(j==strlen(arr)-1) return tmp->pos;        //alla fine ritorna pos che dice se esiste o no 
      tmp=tmp->level_d;
    }
}


void main(int argc,char *argv[])
{
  FILE *fb;
  char arr[50];

 head=(struct elm*)malloc(sizeof(struct elm));  
 init(head); 

 if(argc!=2) exit();

 if((fb=fopen(argv[1],"r"))!=0)
  {
    while(!feof(fb))
      {
	fscanf(fb,"%s",arr);
	insert(arr);
      }
  }

 fclose(fb);

 while(1)
   {
     printf("\nCaratteri presenti : %d\n",nchar);
     printf("Celle usate : %d\n",ncelle);
     printf("Grandezza struct : %d\n",sizeof(struct elm));
     printf("Memoria utilizzata : %d\n",ncelle*sizeof(struct elm));
     printf("\ndammi parola: "); scanf("%s",arr);

     if(cerca(arr))
      printf("\nesiste!\n");
    
     else printf("\nnon esiste!\n");
   }
}











