/*	prime number generator from Aminet
	modified for my own purposes
*/

#include <exec/types.h>
#include <stdio.h>
#include <math.h>
#include <dos/dos.h>
#include <dos/rdargs.h>
#include <proto/dos.h>

#define template "N=Number/K/N,S=Start/K/N,E=End/K/N,P=Print/S"
#define OPT_NUM   0
#define OPT_START 1
#define OPT_END   2
#define OPT_PRINT 3
#define OPT_COUNT 4

static UBYTE *VersTag = "$VER: primes 1.0 (17.8.96)";

/* prototype */
long findprimes(long,long,long,long);

long		numberof,maximum,number,startnumber,numprimes;
BOOL		Print;
long		antal = 2;
long		time();
long		code,starttime, endtime, benchtime,result[OPT_COUNT];

main(int argc,char *argv[])
{
	struct RDArgs *args=NULL;
	if (!(args = (struct RDArgs *)ReadArgs(template,result,NULL)))
		{
			code = IoErr();
			PrintFault(code,NULL);
			exit(5);
		}
	if (result[OPT_NUM]) numberof = *((LONG *)result[OPT_NUM]);
	else numberof = 0;
	if (result[OPT_START]) number = *((LONG *)result[OPT_START]);
	else number=0;
	if (result[OPT_END]) maximum = *((LONG *)result[OPT_END]);
	else maximum = number+100000;
	printf("\n");
	if (number+2 > maximum)
		{
		maximum = number+2;
		}
	if (result[OPT_PRINT])
		Print=TRUE;
	else
		Print=FALSE;
	if (result[OPT_NUM])
		printf("Now computing %ld primes\n",numberof);
	else
		printf("Now computing primes between %ld and %ld\n",number,maximum);
	printf("You can interrupt at any time with ctrl-c\n");
	starttime = time(0);
	numprimes = findprimes(number,maximum,Print,numberof);
	endtime = time(0);
	printf("\nThats it!\n");
	benchtime = endtime - starttime;
	if (result[OPT_NUM])
		printf("Found %d prime numbers between %d and %d in approximately %d seconds\n",antal,number,numprimes,benchtime);
	else
		printf("Found %d prime numbers between %d and %d in approximately %d seconds\n",antal,number,maximum,benchtime);
	FreeArgs(args);
}

isprime(long thenumber)
{
	int isitprime=1,loop;
	for(loop=3 ; (isitprime) && (loop<(sqrt(thenumber)+1)) ; loop+=2)
		isitprime = (thenumber % loop);
	return(isitprime);
}

long findprimes(long num,long end,long p,long nums)
{
	if (num<1) num=1;
	if ((num==1)&&(p)) printf("1\n");
	if ((num<=2)&&(p)) printf("2\n");
	if (!(num % 2)) num++;
	if (num==1) num=3;
	if (!nums)			/* regular computation of prime numbers between num and end */
		do              /* nums tells it if there was an n argument or not */
		{
			if (isprime(num))
			{
				++antal;
				if (p) printf("%ld\n",num);
			}
			num+=2;
		}while (num <= end);
	else
		do				/* computation of a antal number of primes */
		{
			if (isprime(num))
			{
				++antal;
				if (p) printf("%ld\n",num);
			}
			num+=2;
		}while (antal <= nums-1);
	return(num);
}
