#include "carac.h"
#include <proto/dos.h>
#include <proto/exec.h>
#include <exec/execbase.h>
#include <exec/memory.h>
#include <proto/mathieeesingtrans.h>
#include <proto/mathieeesingbas.h>
#include <proto/timer.h>
#include <devices/timer.h>

#define MEM MEMF_PUBLIC|MEMF_CLEAR
#define TEMPLATE "MAXIMUM/N"
#define TXT GRAS"\n   Primes 1.0"NORM"\n\n   © Allenbrand Brice 1996\n\n   Ringard'Production\n\n   "ITALIK"Usage : Primes Maximum\n\n"NORM
#define VER "$VER: Primes 1.0 ** "__DATE__

__saveds int main(void)
{
 struct RDArgs *rdargs;
 int opts[]={0,0};
 static char pipo[]=VER;
 unsigned int i,j,k,a,b;
 char *s;
 struct DosLibrary *DOSBase;
 struct Library *MathIeeeSingTransBase;
 struct Library *MathIeeeSingBasBase;
 struct Library *TimerBase;
 long Err;
 struct timerequest *tr;
 struct timeval aa,bb;

 if(DOSBase=(struct DosLibrary *)OpenLibrary("dos.library",37))
 {
  if(MathIeeeSingTransBase=(struct Library *)OpenLibrary("mathieeesingtrans.library",0))
  {
   if(MathIeeeSingBasBase=(struct Library *)OpenLibrary("mathieeesingbas.library",0))
   {
    if(tr=(struct timerequest *)AllocVec(sizeof(struct timerequest),MEM))
    {
     if(!(Err=OpenDevice("timer.device",UNIT_MICROHZ,(struct IORequest *)tr,0)))
     {
      TimerBase=(struct Library *)tr->tr_node.io_Device;
      if(rdargs=ReadArgs(TEMPLATE,(long *)opts,NULL))
      {
       if(opts[0])
       {
        i=*((int *)(opts[0]));
        k=(IEEESPFix(IEEESPSqrt(IEEESPFlt(i)))+1)>>1;
        i++;
        i>>=1;
        if(s=AllocVec(i+1,MEM))
        {
         GetSysTime(&aa);
         j=2;
         while(j<=k)
         {
          if(!s[j])
          {
           b=j+j-1;
           a=b+j;
           while(a<=i)
           {
            s[a]=1;
            a+=b;
           }
          }
          j++;
         }
         GetSysTime(&bb);
         SubTime(&bb,&aa);
         k=1;
         Printf("%8ld%8ld",1,2);
         for(j=2;j<=i;j++)
          if(!s[j])
          {
           k++;
           if(!(k&7))
            Printf("\n");
           Printf("%8ld",(j<<1)-1);
          }
         Printf("\n(%ld)\n",k+1);
         Printf("(%ld.%05ld s)\n\n",bb.tv_secs,bb.tv_micro);
         FreeVec(s);
        }
       }
       else
        Printf(TXT);
       FreeArgs(rdargs);
      }
      CloseDevice((struct IORequest *)tr);
     }
     FreeVec(tr);
    }
    CloseLibrary(MathIeeeSingBasBase);
   }
   CloseLibrary(MathIeeeSingTransBase);
  }
  CloseLibrary((struct Library *)DOSBase);
 }
 return(0);
}