#!c:\perl\bin\perl.exe
#
# Fast Contact Manager v0.1
# Copyright (C) 2006  Plinio Gatto - pli@autistici.org
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

print "\nFast Contact Manager in Perl !\n\n";
$c = 's';

while ($c eq 's'){

	#Lettura dei dati del nuovo contatto
	print "\n\n| Nuovo contatto |\n------------------------------\n\n";
	print 'Nome: ';
	$nome=<STDIN>;
	chop($nome);

	print 'Cognome: ';
	$cognome=<STDIN>;
	chop($cognome);

	print 'Tel.: ';
	$tel=<STDIN>;
	chop($tel);

	print 'e-mail.: ';
	$email=<STDIN>;
	chop($email);
	
	print "------------------------------";
	
	$r='0';	#Elimina la risposta precedente
	while(($r ne 's') && ($r ne 'n')){
		print "\n\nI dati sono corretti (s/n) ?";
		$r=<STDIN>;
		chop($r);
	}

	#Il contatto viene inserito
	if ($r eq 's'){
		open(FILE,">>agenda.txt")|| die "\nErrore: impossibile aprire il file.\n\n"; 
		print FILE "$nome \t $cognome \t $tel \t $email\n";
		#printf FILE ("%s%20s%20s%20s",$nome,$cognome,$tel,$email);
		close(FILE);
		print "\nLe informazioni sono state inserite.\n\n";
		
		#******************************* Ordimanento del file *******************************
	
		#Lettura  del file per l'ordinamento
		open(RFILE,"<agenda.txt")|| die "\nErrore: impossibile aprire il file.\n\n"; 
		@readed=<RFILE>;
		chop(@readed);
		close(RFILE);

		@sorted=sort(@readed);

		#Cancella fil file esistente
		open(WFILE,">agenda.txt")|| die "\nErrore: impossibile aprire il file.\n\n"; 
		close(WFILE);

		#Scrive il file ordinato
		open(WFILE,">>agenda.txt")|| die "\nErrore: impossibile aprire il file.\n\n"; 
		foreach $riga (@sorted) {
			print WFILE "$riga\n" ;
		}
		close(WFILE);

		#************************************************************************************
	}
	
	
	#Chiede solo se i dati inseriti in precedenza sono corretti altrimenti ripete l'inserimento
	if ($r eq 's'){
		$c='0';	#Elimina la risposta precedente
		while(($c ne 's') && ($c ne 'n')){
			print "\n\nAggiungere un nuovo contatto (s/n) ?";	 
			$c=<STDIN>;
			chop($c);
		}
	}
	
}