# include <stdio.h>
/** Auto to programma bazei protous arithmous se ena 
   arxeio. O xristis epilegei mia epilogi apo ena 
   menu. Analoga me tin epilogi eite bazei arithmous
   sto arxeio eite emfanizei to arxeio **/


/**πχ 2,3,5, 6=2 * 3, 7, 8 = 4 * 2 = 2 * 2 *2 , 9 = 3 *3, 24=2 * 12 = 2 * 3 * 4= 2 * 3 * 2 * 2 **/
/**πχ 2,3,5, 6=2 * 3, 7, 8 = 4 * 2 = 2 * 2 *2 , 9 = 3 *3, 24=2 * 12 = 2 * 3 * 4= 2 * 3 * 2 * 2 **/
int menu()
{
	int option;
	printf("1- Store a prime integer \n");
    printf("2- Display the file \n");
	printf("3- Quit\n");
	scanf("%d",&option);
	return option;
}


/** 20 
 * 2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19 
 * **/
int isPrime(int x)
{
	int i;
	int count=0;
	if(x<=0) return 0;
	for(i=2;i<=x/2;i++) 
		if(x%i==0) count++;
	if(count==0) return 1;	
	return 0;
}

int main()
{
	int option,x;
	FILE *fp;
	do
	{
		option=menu();
		if(option==1)
		{
			printf("Please give an integer \n");
			scanf("%d",&x);	
			if(isPrime(x))
			{
				/** found=0, to x den yparxei sto arxeio kai found=1 to x yparxei sto **/
				int found=0;
				
				fp=fopen("primes.txt","r");
				if(fp==NULL) found=0;
				else
				{
					int value;
					while(fscanf(fp,"%d",&value)>0)
					{
						if(x==value) found=1;
					}
					fclose(fp);
				}
				
				if(found==0)
				{
				
					fp=fopen("primes.txt","a");
					fprintf(fp,"%d\n",x);
					fclose(fp);
				}
				else
				{
					printf("O %d protos yparxei \n",x);
				}
			}
			else printf("%d is not a prime\n",x);
		}
		else
		if(option==2)
		{
			fp=fopen("primes.txt","r");
			if(fp!=NULL)
			{
			while(fscanf(fp,"%d",&x)>0)
				printf("Prime: %d\n",x);
			fclose(fp);
		}
		}
	}while(option!=3);
	return 0;
}
