/******** Programma Agenda ********/

#include <exec/types.h>
#include <exec/nodes.h>
#include <exec/lists.h>
#include <exec/memory.h>
#include <stdio.h>

#ifdef AZTEC_C /* Inclusione per Aztec C */
#include <functions.h>
#else /* Inclusioni per Lattice C */
#include <stdlib.h>
#include <string.h>
#include <proto/exec.h>
#endif

#define TELEL 10
#define NOMEL 20

struct List Plist;
struct Elem {
 struct Node Pnode;
 char nome[ NOMEL+1 ];
 char tele[ TELEL+1 ];
};

struct Elem *ealloc()
{
 return ( (struct Elem *) AllocMem( sizeof( struct Elem ),\
        MEMF_CLEAR ) );
}
void cleanup()
{
struct Elem *p;
while ( ( p = (struct Elem *) RemHead ( &Plist ) ) != NULL )
 FreeMem ( (char *) p, sizeof( struct Elem ) );
}

void gerror( s )
char *s;
{
cleanup();
printf ( "%s\n", s );
exit ( 0L );
}

struct Elem *eseek( init, s )
struct Elem *init;
char *s;
{
struct Elem *pe = init;
for ( ; pe -> Pnode.ln_Succ != NULL ;\
    pe = (struct Elem *) pe->Pnode.ln_Succ )
 if ( strcmp ( &pe->nome[ 0 ], s ) == 0 )
  return ( pe );
return ( NULL );
}

void main()
{
struct Elem *pe;
char c, nome[ NOMEL+1 ], tele[ TELEL+1 ];

NewList (&Plist);

for ( ;; ) {
 printf ( "\n\n\033[1m *** EXEC-Agenda ***\033[0m\nOpzioni:\n" );
 printf ( "1 --> Inserisci elemento\n" );
 printf ( "2 --> Cancella elemento\n" );
 printf ( "3 --> Ricerca elemento\n" );
 printf ( "4 --> Visione elenco\n" );
 printf ( "0 --> Fine lavoro\n" );
 scanf ( "%s", &c );
 switch (c) {
  case '0':
   cleanup();
   exit( 0 );
  case '1':
   printf ( "Aggiunta: Nome ? " );
   scanf ( "%s", &nome );
   printf ( "      Telefono ? " );
   scanf ( "%s", &tele );
   if ( strlen ( nome ) == 0 || strlen ( tele ) == 0 )
    break;
   if ( ( pe = ealloc() ) == NULL )
    gerror ( "Non s'alloca memoria!" );
   strncpy ( &pe->nome[ 0 ], nome, NOMEL );
   strncpy ( &pe->tele[ 0 ], tele, TELEL );
   AddTail ( (struct List *) &Plist, (struct Node *) pe );
   printf ( "Inserito!\n" );
   break;
  case '2':
   printf( "Cancello nome ? " );
   scanf ( "%20s", &nome );
   if ( ( pe = eseek( Plist.lh_Head, nome ) ) == NULL )
    printf( "Non trovato\n" );
   else
    {
    Remove( (struct Node *) pe );
    FreeMem( (char *) pe, sizeof( struct Elem ) );
    }
   break;  
  case '3':
   printf( "Ricerca: Nome ? " );
   scanf( "%20s", &nome );
   if ( ( pe = eseek( Plist.lh_Head, nome ) ) == NULL )
    printf( "Non trovato\n" );
   else
    printf( ">->-> %s %s\n", &pe->nome[ 0 ], &pe->tele[ 0 ] );
   break;
  case '4':
   pe = (struct Elem *) Plist.lh_Head;
   while ( pe->Pnode.ln_Succ != NULL )
    {
    printf( "> %s %s\n", &pe->nome[ 0 ], &pe->tele[ 0 ] );
    pe = (struct Elem *) pe->Pnode.ln_Succ;
    }
   break;
  default:
   break;
  } /* switch() */
 } /* for (;;) */
} /* main() */
