/****************************************************************************
 Program: Phone Directory
 

  Reminder:
     Input file:
     It is best created by "edit" command inside Command Prompt or there might
     be error(s)      
     phone number has to be in 8 digits    
           
     AddEntry:
     While Rentering data for name or phone then leaving it blank
     it will not exit but instead storing/displaying your input
     as being ZERO.

TESTED/COMPILED - Windows XP / Dev C++ 4.9.9.2
*****************************************************************************/
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <windows.h>
#define MAXDB 500 /* Maximum number of Entries */


/* Globe variables */
int i; /*globe index*/
long int phone[MAXDB+1];
char name[MAXDB+1][21]; /* define array of string with maximum of 20 characters long in name, 
not including '\0' at the end of the string */
/* phone_tmp & name_tmp array's are temp storage used for delete recovery */
long int phone_tmp[MAXDB+1];
char name_tmp[MAXDB+1][21];
void AddEntry(char [], long int);
int add_count=0; /* master counter for entries added */
int current_e_add; /* counter for current entries added within a giventime.*/
int DeleteEntry(char*, long int);
int FindPhone(long int);
int FindName(char*);
int phone_found,name_found;
int del_entry; /* counts del entry at a given time */
int tot_del_entry=0; /* master del counter */
int ListAll(void);
int SortAllEntries(char);
int GeTotalEntries(void);
int chkstrdig1 (char str[], int range);
int chkstrdig2 (char str[], int range);
char menu(void);
void LoadDB(void); /* load database from file function */
void exitmenu(void);
void drawscreen(void);

char dbload[80]; /* loaded database */

int main(void)
{
char iname[80], sname_del[80], sname_search[80], iphone[80],add_quit;
char option,sortopt,exit_opt; /* menu,sort and exit option*/
int phone_check,name_check,delete_check,sort_check,list_check;
int int_iname,total_entries;
int error_iphone,error_iname; /* used to check inputs error's  */
long int longint_iphone;
long int iphone_search;
long int iphone_del;
void gotoxy(int, int);
void col(unsigned short);

/* Init while no valid database file is loaded program will work in RAM! */
strcpy(dbload, "No database file loaded (RAM MODE!).");

/* MAIN MENU */
do
 {
  do
   { option = menu();
     if (option == '1') /* AddEntry Option */
     {  current_e_add=0; /*init current entries added to zero.*/
	for (i=add_count; i < MAXDB; i++)
	{   system("cls");
	    drawscreen();
	    gotoxy(1,4);
	    printf(">> Add Entry <<");
	    gotoxy(1,25);
	    printf("Please Add Your Entry, leave blank to quit to Main Menu");
	    gotoxy(1,6);
	    printf("\nEnter Name[%3d]: ",i+1);
	    gets(iname);

	    if (iname[0] == '\0' ) /* user hits enter - quits */
	    {  gotoxy(1,25);
	       printf("You chose to quit: Entry %d was not added to the database.",i+1);
	       break;
	    }
	    printf("Enter Phone Number[%3d]: ",i+1);
	    gets(iphone);

	    if (iphone[0] == '\0') /* user hits enter - quits */
	    {  gotoxy(1,25);
	       printf("You chose to quit: Entry %d was not added to the database.",i+1);
	       getch();
	       break;
	    }
	    /* check the string for valid inputs */
	    error_iname = chkstrdig1(iname,21);
	    error_iphone = chkstrdig2(iphone,8);
	    /* loop's while name input error (out of range/character) */
	    while(error_iname != 0)
	    {	if (error_iname == -1)
		{  system("cls");
		   drawscreen();
		   gotoxy(1,4);
		   printf(">> Add Entry <<");
		   gotoxy(1,25);
		   printf("Error: Input Name - out of Range, Your entry was greater than 20 characters. ");
		   gotoxy(1,6);
		   printf("Renter Name[%3d]: ",i+1);
		   gets(iname);
		}
		if (error_iname == -2)
		{  system("cls");
		   drawscreen();
		   gotoxy(1,4);
		   printf("*** Add Entry ***");
		   gotoxy(1,25);
		   printf("Error: Input Name - Digit(s) detected, digit(s) are not allowed.");
		   gotoxy(1,6);
		   printf("Renter Name[%3d]: ",i+1);
		   gets(iname);
		}/* checks string name input if valid */
		error_iname = chkstrdig1(iname,21);
	    }/*loop's while phone input error (out of range/character) */
	    while(error_iphone !=0)
	    {	if (error_iphone == -1)
		{  system("cls");
		   drawscreen();
		   gotoxy(1,4);
		   printf(">> Add Entry <<");
		   gotoxy(1,25);
		   printf("Error: Phone Number - out of Range, Your entry was greater than 8 digits. ");
		   gotoxy(1,6);
		   printf("Name[%3d] Entry: %s",i+1,iname);
		   gotoxy(1,7);
		   printf("Renter Phone Number[%3d]: ",i+1);
		   gets(iphone);
		}
		if (error_iphone == -2)
		{  system("cls");
		   drawscreen();
		   gotoxy(1,4);
		   printf(">> Add Entry <<");
		   gotoxy(1,25);
		   printf("Error: Phone Number - Character(s) detected, character(s) are not allowed.");
		   gotoxy(1,6);
		   printf("Name[%3d] Entry: %s",i+1,iname);
		   gotoxy(1,7);
		   printf("Renter Phone Number[%3d]: ",i+1);
		   gets(iphone);
		}/* checks phone input valid */
		error_iphone = chkstrdig2(iphone,8);
	    }
	    /* no name or phone input error - addentry */
	    if (error_iname == 0 && error_iphone == 0)
	    {  /* int_iname = atoi(iname);  converts string to int */
	       longint_iphone = atol(iphone); /* converts string to long int */
	       current_e_add++;
	       AddEntry(iname,longint_iphone);
	    }
	}
	if (add_count == MAXDB) /* database full */
	{  gotoxy(1,25);
	   printf("\aDatabase is full!: %d entries were added, ",add_count);
	   printf("that is the Maximum No. of the database.");
	   getch();
	}
     }
     	    
     else
     if (option == '2') /* DeleteEntry option */
     {  del_entry = 0; /* Initialize del_entry counter zero */
	system("cls");
	drawscreen();
	gotoxy(1,4);
	printf(">> Delete Entry <<\n");
	printf("Enter name to delete: ");
	gets(sname_del);
	fflush(stdin);
  fflush (stdout);
  fflush (stderr);

	printf("Enter phone number to delete: ");
	scanf("%ld",&iphone_del);
 fflush (stdout);
  fflush (stderr);
  	fflush(stdin);
	delete_check = DeleteEntry(sname_del,iphone_del);

	if (delete_check == 0)/*successfully found or deleted entries display*/
	{  gotoxy(1,25);
	   printf("Successful: There are currently %d entries in the database, ",add_count);
	   printf("deleted %d.",del_entry);
	   getch();
	}
	if (delete_check == -1) /* error: does not delete if db not found */
	{  gotoxy(1,25);
	   printf("Error: The specific Name No. and Phone No. are NOT Found.                  ");
	   getch();
	}

     }
     else
     if (option == '3') /* FindPhone Option */
     {  phone_found = 0; /*initialize phone no. found to zero */
	system("cls");
	drawscreen();
	gotoxy(1,4);
	

	printf(">> Find Name <<");

	gotoxy(1,6);
	printf("Enter the phone number to search for: ");
	scanf("%ld",&iphone_search);
  fflush (stdout);
  fflush (stderr);
    	fflush(stdin);
	phone_check = FindPhone(iphone_search);

	if (phone_check == 0) /* return = 0 Phone found */
	{  gotoxy(1,25);
	   printf("Successful: There are currently %d entries in the database, ",add_count);
	   /* phone_found(globe), counts phone no. found(within FindPhone function) */
	   printf("found %d.",phone_found);
	   getch();
	}
	if (phone_check == -1) /* return = -1 Phone not found */
	{  gotoxy(1,25);
	   printf("Error: The Phone No. Your looking for was Not Found.");
	   getch();
	}
     }
     else
     if (option == '4') /* FindName Option */
     {  name_found = 0;  /* initialize name no. found to zero */
	system("cls");
	drawscreen();
	gotoxy(1,4);
	

	    
	printf(">> Find Phone Number <<");

	gotoxy(1,6);
	printf("Enter the name to search for: ");
	gets(sname_search);
fflush (stdout);
  fflush (stderr);
  	fflush(stdin);
	name_check = FindName(sname_search);

	if (name_check == 0) /* return = 0 Name found */
	{  gotoxy(1,25);
	   printf("Successful: There are currently %d entries in the database, ",add_count);
	   /* name_found is globe it counts name no. found in FindName function */
	   printf("found %d.",name_found);
	   getch();
	}
	if (name_check == -1) /* return = -1 Name was not found */
	{  gotoxy(1,25);
	   printf("Error: The Name No. Your looking for was Not Found.");
	   getch();
	}

     }
     else
     if (option == '5') /* ListAll option */
     {  
     system("cls");
	drawscreen();
	gotoxy(1,4);
	printf(">> ListAll <<\n\n");

	    

	list_check = ListAll();

	if (list_check == 0) /* return 0 if entries are in database */
	{  gotoxy(1,25);
	   printf("List Sucuessful");
	   getch();
	}
	if (list_check == -1) /* return -1 - emptylist */
	{
	   gotoxy(1,25);
	   printf("Empty List");
	   getch();
	}
     }
     else
     if (option == '6') /* Getotalentries option */
     {  total_entries = GeTotalEntries();
	gotoxy(1,25);
	printf("There are currently %d entries stored in the Database.",total_entries);
	getch();
     }
     else
     if (option == '7') /* Sort Option */
     {  system("cls");
	drawscreen();
	gotoxy(1,4);
	printf(">> Sort All Entries <<");
	gotoxy(1,6);
	printf("Press 'A' to sort database in [A]scending order");
	gotoxy(1,7);
	printf("Press 'D' to sort database in [D]escending order.");
	gotoxy(1,9);
	printf("Note: Database is sorted by phone no. entries.");
	sortopt = getch();
fflush (stdout);
  fflush (stderr);
	fflush(stdin);
	sort_check = SortAllEntries(sortopt);
	getch();
	if (sort_check == 0) /* return = 0 - entries, in db & was sorted */
	{  gotoxy(1,25);
	   printf("Database was successfully Sorted.                                      ");
	   getch();
	}
	if (sort_check == -1) /* return = -1 - if db is empty */
	{  gotoxy(1,25);
	   printf("Database was not sorted - Database is empty!");
	   getch();
	}
     }
     else
     if (option == '8') /* Load Database from file option */
     { 
                system("cls");
	drawscreen();
	gotoxy(1,4);
	printf(">> Load Database <<");
	LoadDB();
     }
     else
     if (option == '9') /* exit option */
     {  gotoxy(1,25);
	printf("Do you really want to exit?, Press 'Y' to confirm, anykey to cancel");
	exit_opt = getch();
 fflush (stdout);
  fflush (stderr);
    	fflush(stdin);
	if (exit_opt == 'y' || exit_opt == 'Y')
	{  system("cls");
	   drawscreen();
	   gotoxy(1,4);
	   printf(">> Exit To system <<\n\n");
	   exitmenu();
	}
     }
     else /* user presses an invalid key display msg error */
     {  gotoxy(1,25);
	printf("Error: Invalid option! Select an option between 1 and 9");
	getch();
fflush (stdout);
  fflush (stderr);
	fflush(stdin);
     }
   }while  (option > '9' || option < '1' );
 }while (option != '`'); /* unlimated loop */
}
/****************************************************************************
	Main Functions
	--------------
	AddEntry, DeleteEntry, FindPhone, FindName,
	ListAll, GeTotalEntries, SortallEntries, col, gotoxy
*****************************************************************************/
/*---------------------------------------------------------------------------
	AddEntry Function
	-----------------
	Does not return any values it is used to added valid inputs(only) into
	the database and display the entries which was added.
	* A valid inputs are positive numbers only.
	1. Name no. input with less than or equal to 4 digits only.
	2. Phone no. input with less than or equal to 8 digits only.
	3. Input of Zero for name no. or phone no. inputs is an valid.
----------------------------------------------------------------------------*/
void AddEntry(char *r, long int p)
{
     strcpy(name[i],r);  /* store r(name) input into db */
     phone[i] = p; /* store p(phone) input into db */
     add_count++;  /* keeps track of total entries added. */
     printf("\nName No. [%-21s]\nPhone No. [%-8ld]\n%d entries added.",name[i],p,current_e_add);
     getch();
}

/****************************************************************************/

void col(unsigned short color)
{
    HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hcon,color);
}

void gotoxy(int x, int y)
{
  COORD point;
  point.X = x; point.Y = y;
  SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),point);
}


/*---------------------------------------------------------------------------
	DeleteEntry function
	--------------------
	Used to delete entrys in the database.
	Returns 0 if name no. & phone no. was found in the database.
	Returns -1 if name no. & phone no. is not found in the database.

	Note: Auto-Recovery was implemented into this function but was never
	used. name_tmp and phone_tmp arrays contain the deleted data
	which maybe used for recovery.
---------------------------------------------------------------------------*/
int DeleteEntry(char *r, long int p)
{
int k,x,del_found_flag=-1,loop_mov_stop,loop_mov,count_del=0;
char del_me; /* Variable to confirm delete */
char tmp_name[1][21];



         for(k=0; k < add_count; k++)
         {   
             if (add_count != 0) /* checks if database is not empty */
             {  if (strcmp(r,name[k])==0 && p == phone[k])
	         {  
         gotoxy(1,8); 
	     printf("Match Found: \n");
	     printf("Name No. [%-21s]\tPhone No. [%-8ld] was found in record No. [%3d  ]\n",name[k],phone[k],k+1);
	     del_found_flag = 0; /* when found, set's del_found_flag=0 */
	     gotoxy(1,25);
	     printf("Delete record [%3d  ]?, Press 'Y' to confirm, anykey to cancel.",k+1);
	     del_me = getch();
    fflush (stdout);
  fflush (stderr);
    	 	fflush(stdin);
	     if (del_me == 'y' || del_me == 'Y')
	     {  
        strcpy(name_tmp[tot_del_entry],name[k]); /* tmp array storage for name found */
		strcpy(name[k],"!"); /* marks '!' for name deleted */
		phone_tmp[tot_del_entry] = phone[k];
		phone[k] = -1;  /* marks -1 for phone number deleted */
		del_entry++; /* counter for deleted entry */
		tot_del_entry++; /* counter for temp storage */
	     }
	  }
       }
    }

    
    if (add_count !=0) /* if database is not empty process with delete */
    {/* keeps looping while move up position is not = to deleted entry */
       for (x=0; x < del_entry; x++)
       {   for (k=0; k < add_count; k++)
	   {/* When -1 is found it moves everything by one */
	      if (strcmp(name[k],"!")==0 && phone[k] == -1)
	      {  loop_mov_stop=0;
		 loop_mov =0;
		 count_del++;
		 /* loop_mov_stop calculates moves needed */
		 loop_mov_stop = add_count-(k+1);
		 while (loop_mov_stop != loop_mov)
		 {     strcpy(name[k+loop_mov],name[(k+1)+loop_mov]);
		       phone[k+loop_mov] = phone[(k+1)+loop_mov];
		       loop_mov++; /* counter for move */
		 }
	      }
	   }
       }
    }
    /* Calcalates total entry */
    add_count = add_count - del_entry;

    if (del_found_flag == 0) /* flag is 0 when delete entry input was found */
    { return(0);  } /* return sucessful */
    else
    { return(-1); } /* return not found */
}
/*---------------------------------------------------------------------------
	FindPhone function
	------------------
	Used to search for a phone number in the database.

	Returns 0 if phone no. was found.
	Returns -1 if phone no. is not found.
---------------------------------------------------------------------------*/
int FindPhone(long int p)
{
int k, phone_found_flag= -1;
    gotoxy(1,8);
    for(k=0; k < add_count; k++)
    {  if (add_count != 0) /* if database is not empty then run a search */
       {  if (k != 0 && (k%15) == 0)
	  {  gotoxy(1,8); /* moves cursor to beginning when screen filled */
	     getch();
	  }
	  if (p == phone[k])
	  {  printf("Phone No. [%-8ld] was found in record No. [%3d  ]\tName No. [%-21s]\n",phone[k],k+1,name[k]);
	     phone_found++;
	     phone_found_flag = 0;
	  }
       }
    }
    if (phone_found_flag == 0) /* flag is 0 if record was found */
    { return(0);  } /* return sucessful */
    else
    { return(-1); } /* return not found */
}
/*---------------------------------------------------------------------------
	FindName function
	------------------
	Used to search for a Name number in the database.

	Returns 0 if name no. was found.
	Returns -1 if name no. is not found.
----------------------------------------------------------------------------*/
int FindName(char *r)
{
int k, name_found_flag=-1;

    gotoxy(1,8);
    for(k=0; k < add_count+1; k++)
    {  if (add_count != 0) /* if database is not empty then run a search */
       {  if (k != 0 && (k%15) == 0)
	  {  gotoxy(1,8); /* moves cursor to beginning when screen filled */
	     getch();
	  }
	  if (strcmp(r,name[k])==0)
	  {  printf("Name No. (%-21s) was found in record No. [%3d  ]\tPhone No. (%-8ld)\n",name[k],k+1,phone[k]);
	     name_found++;
	     name_found_flag = 0;
	  }
       }
    }

    if (name_found_flag == 0)
    { return(0);  } /* return sucessful */
    else
    { return(-1); } /* return not found */
}

/*---------------------------------------------------------------------------
	ListAll Function
	----------------
	Used for displaying data entered into the database.
	returns -1 if list is empty.
	returns 0 if sucessful (database contains valid entries)
---------------------------------------------------------------------------*/
int ListAll(void)
{
int k;
    gotoxy(1,6);
    printf("\n");

    for (k=0; k < add_count; k++)
    {
	if (k != 0 && (k%17) == 0)
	{  gotoxy(1,6); /* moves cursor to beginning when screen filled */
	   getch();
	}
	/* double checks - it will not print out delete entries(-1) */
	if (strcmp(name[k],"!")!= 0 && phone[k] != -1)
	{      
       printf("Name [%3d  ]: %-20s\t",k+1,name[k]);
	   printf("Phone Number [%3d  ]: %-8ld\n",k+1,phone[k]);
	}  
    }
    if (add_count == 0)
    {  return(-1); } /* Empty List */
    else
    {  return(0);  } /* Successful */
}
/*---------------------------------------------------------------------------
	GeTotalEntries function
	-----------------------
	Used to return total entries added to database.
---------------------------------------------------------------------------*/
int GeTotalEntries(void)
{
/* This function is not required but was created to make things clear. As
   the add_count(globe varible) already keeps track of total entries added.*/
   return(add_count);
}
/*---------------------------------------------------------------------------
	SortAllEntries function
	-----------------------
	Sort is done with the use of bubble sort.
	returns 0 if sort was successful.
	returns -1 if database is empty.
---------------------------------------------------------------------------*/

int SortAllEntries(char sel)
{
int k,sortalldone;
char* name_str_tmp;
long int phone_str_tmp;
    if (add_count !=0) /* if list not empty continue with sort */
    {  do
       { sortalldone=0;
	 for (k = 0; k < add_count; k++)
	 {   /* sort in ascending order */
	     if ((phone[k] > phone[k + 1])&&(sel == 'a' || sel == 'A')&&(k != add_count -1))
	     {   phone_str_tmp = phone[k]; /* stores previous array to phone_str_tmp */
		 phone[k] = phone[k + 1]; /* copys next array to the previous array before it */
		 phone[k + 1] = phone_str_tmp; /* Previous array is copyed to next array */
		 /* same process is done here but with name no. */
		 strcpy(name_str_tmp,name[k]);
		 strcpy(name[k],name[k + 1]);
		 strcpy(name[k + 1],name_str_tmp);
		 sortalldone =1; /* sets to 1 if sort is done */
	     }
	     /* same method used here but sorts in decending order */
	     if ((phone[k] < phone[k + 1])&&(sel == 'd' || sel == 'D')&&(k != add_count -1))
	     {   phone_str_tmp = phone[k];
		 phone[k] = phone[k + 1];
		 phone[k + 1] = phone_str_tmp;
		 strcpy(name_str_tmp,name[k]);
		 strcpy(name[k],name[k + 1]);
		 strcpy(name[k + 1],name_str_tmp);
		 sortalldone =1;
	     }
	 }
       }while (sortalldone);
    }

    if ((sel == 'a' || sel == 'A')&&add_count !=0)
    {   gotoxy(1,25);
	printf("You have chosen to sort the database in [A]scending order. ");
	return(0);   /* sucessfully sorted */
    }
    else
    if ((sel == 'd' || sel == 'D')&&add_count !=0)
    {  gotoxy(1,25);
       printf("You have chosen to sort the database in [D]ecending order. ");
       return(0);    /* sucessfully sorted */
    }
    else
    if ((sel != 'a' || sel != 'A' || sel != 'd' || sel != 'D')&&add_count !=0)
    {  gotoxy(1,12);
       printf("Invalid option - database was not sorted!");
    }
    else
    { return(-1); } /* list empty */
}
/****************************************************************************
	Special functions
	-----------------
	Chkstrdig1, LoadDB.
****************************************************************************/
/*---------------------------------------------------------------------------
	Chkstrdig1(Check string for digits)
	----------------------------------
	Used to check string inputs, and lenght.
	returning:
	-1 = if string lenght is out of range.
	-2 = if a digit is found within the string.
	0 = if successful

	NOTE:
	Addentry specifed that Name allows for 4 digits or less.
	Phone allowing 8 digits or less.
---------------------------------------------------------------------------*/
int chkstrdig1 (char str[], int range)
{
int lenght=0,k;
    lenght = strlen(str); /* get lenght of string */

    if (lenght > range)
    { 	return(-1);} /* out of range */
    if (lenght <= range) /* string is in range */
    {  for (k=0; k < lenght; k++)
       {   if (isdigit(str[k]) != 0)
	   { return(-2); } /* char detected return error msg */
       }
    return(0); /* successful - input string was in range and was digits */
    }
}
/****************************************************************************
	Special functions
	-----------------
	Chkstrdig2, LoadDB.
****************************************************************************/
/*---------------------------------------------------------------------------
	Chkstrdig2(Check string for digits)
	----------------------------------
	Used to check string inputs, and lenght.
	returning:
	-1 = if string lenght is out of range.
	-2 = if a char is found within the string.
	0 = if successful

	NOTE:
	Addentry specifed that Name allows for 4 digits or less.
	Phone allowing 8 digits or less.
---------------------------------------------------------------------------*/
int chkstrdig2 (char str[], int range)
{
int lenght=0,k;
    lenght = strlen(str); /* get lenght of string */

    if (lenght > range)
    { 	return(-1);} /* out of range */
    if (lenght <= range) /* string is in range */
    {  for (k=0; k < lenght; k++)
       {   if (isdigit(str[k]) == 0)
	   { return(-2); } /* char detected return error msg */
       }
    return(0); /* successful - input string was in range and was digits */
    }
}
/*---------------------------------------------------------------------------
	Load up database from file function
	-----------------------------------
	Used to load a file into the database.
---------------------------------------------------------------------------*/
void LoadDB(void)
{
int count,nofilen,dbfilecount=0;
char finphone[8];
char finname[20];
int error_junk;
char* dummy;
long int l_finphone;
int y;


FILE *f1;
     gotoxy(1,6);
     printf("Enter the filename of the database: ");
     gotoxy(1,7);
     printf("Example: c:\\mydbfile.txt");
     gotoxy(37,6);
     gets(dbload);
fflush(stdout);
  fflush(stderr);
  	fflush(stdin);
       f1 = fopen (dbload,"r"); /* open file for reading */
     if (f1==NULL)
     {  gotoxy(1,25);
	fprintf(stderr,"There was an error reading your database file!");
	strcpy(dbload, "No database file loaded (RAM MODE!).");
	getch();
	exit(0);
     }
     else
     {	for (count=0; count < MAXDB; count++)
	{
         if ( fgets(finname, 21, f1) !=NULL && fgets(finphone, 9, f1)!= NULL
         && fgets(dummy, 2, f1)!=NULL){

		/* saves info to name, phone array */
		error_junk = chkstrdig1(finname,21);
	    error_junk = chkstrdig2(finphone,8);
         if (error_junk == -1 || error_junk == -2)
         {  printf("Sorry that was an invalid database\n");
            printf("Now working in RAM MODE!");
            getch();
            strcpy(dbload, "No database file loaded (RAM MODE!).");
	    break;
	 }
	 
	/*	trim the space at the end of each name from input file */  
	    for (y=0; y<20; y++){
		    if (finname[y] == ' ' && finname[y+1] == ' '){
		       strncpy(name[count],finname, y);
		       break;
               }
            if (y == 19){
               strcpy(name[count],finname);
               break;
               }
         }
		
         l_finphone = atol(finphone); /* converts string to long int */
		phone[count] = l_finphone;
		dbfilecount++; /* counts no. of records stored in file */
		   fflush(stdout);
   fflush(stderr);
   fflush(stdin);
	    }
	}
       if (error_junk ==0)
       {
	  gotoxy(1,25);
	  printf("Database %s, was successfully loaded!",dbload);
	  getch();
	  /* copys no. of records in file into master counter*/
	  add_count = dbfilecount;
       }
     }
     fclose(f1);
}
/****************************************************************************
	MAIN function
	-------------
	Menu, ExitMenu, drawscreen and refreshscreen.
****************************************************************************/
/*---------------------------------------------------------------------------
	Menu function
	-------------
	Display valid options on the screen
---------------------------------------------------------------------------*/
char menu(void)
{
char optrtn;
     system("cls");
     drawscreen();
     gotoxy(1,4);
     col(15);
     printf("\n"); 
     printf("[1] - Add entry\n");
     printf("[2] - Delete entry\n");
     printf("[3] - Find name\n");
     printf("[4] - Find phone number\n");
     printf("[5] - List all entries\n");
     printf("[6] - Display total entries in database\n");
     printf("[7] - Sort entries\n");
     printf("[8] - Load database from file\n");
     printf("[9] - Exit");
     col(7);
     gotoxy(1,25);
     col(18);
     printf("Please select an option between 1 and 9.");
     col(7);
     gotoxy(1,15);
     printf("\nDatabase loaded: %s",dbload);
     gotoxy(1,14);
     printf("\nSelect an option: ");
     optrtn = getch();
     return optrtn;
}
/*---------------------------------------------------------------------------
	ExitMenu function
	-----------------
	While exiting to system, askes user if he/she wants to save
	database into a file.
---------------------------------------------------------------------------*/
void exitmenu(void)
{    char filename[20],save_opt;
     int k;
     FILE *f1;
     gotoxy(1,6);
     printf("Do You want to Save database before exiting? ");
     gotoxy(1,25);
     printf("Press 'Y' to confirm, anykey to cancel.");
     save_opt = getch();
fflush (stdout);
  fflush (stderr);
  	fflush(stdin);
       if (save_opt == 'y' || save_opt == 'Y')
     {  gotoxy(1,8);
	printf("Please Enter the path and filename to save to:");
	gotoxy(1,10);
	printf("Example: c:\\mydbfile.txt");
	gotoxy(48,8); /* move cursor back to line 8 */
	gets(filename);
fflush (stdout);
  fflush (stderr);
  	fflush(stdin);
  	f1 = fopen (filename,"a"); /*open file for appending mode */
	if (f1== NULL)
	{  gotoxy(1,12);
	   fprintf(stderr, "Error opening file %s.",filename);
	   gotoxy(1,25);
	   printf("Database was not saved!                                                   ");
	   getch();
	   exit(0);
	}
	else
	{   for (k=0; k < add_count; k++)
	    {   fprintf(f1, "%s\t%ld\n",name[k],phone[k]);}
		fclose(f1);
		gotoxy(1,25);
		printf("Database was successfully saved in %s",filename);
		getch();
	    }
     }
     else
     {   gotoxy(1,25);
	 printf("Database was not saved!                                                   ");
	 getch();
     }
     system("cls");
     gotoxy(23,10);
     col(14);
     printf("Thank you for using this program");
     gotoxy(23,11);
     printf("by Morpheust");
     gotoxy(23,13);
     printf("Email: hello@helloworld.com");
     getch();
     exit(0);
}
/*---------------------------------------------------------------------------
	Drawscreen function
	-------------------
	Draws program header.
---------------------------------------------------------------------------*/
void drawscreen(void)
{
     gotoxy(1,1);
     col(20);
     printf("-------------------------------------------------------------------------------");
     gotoxy(1,2);
     printf("                            *** PHONE DIRECTORY ***                            ");
     gotoxy(1,3);
     printf("-------------------------------------------------------------------------------");
     col(7);
}

/* EOF */


