DECLARE FUNCTION RAMValue% ()
DECLARE FUNCTION TestRnd% ()
DEFINT A-Z
'$INCLUDE: '\Prog\Forward\LIB\MTimer\MTimerA.bi'
'   Filename: MRand.bas
'      Title: MRand
'Description: Micro-Second Random Number Generator for DOS.
'     Author: Peter Fedorow
'    Contact: PF - fedorowp AT yahoo.com / fedorowp AT earthlink.net
'  Copyright: 2003 Peter Fedorow
'    Started: 2002 Jun 02 Mon
'Last Change: 2003 Jun 02 Mon
'    History: 2002 Jun 02 Mon  Started.


  CONST False = 0
  CONST True = NOT False


  'Discard = TestRnd
  'FOR A = 1 TO 30
  '  PRINT TestRnd;
  'NEXT A

  
  OPEN "Bytes.rnd" FOR BINARY AS #1
  FOR ByteCount& = 1 TO 32768
  'FOR ByteCount& = 1 TO 1048576
    Bytes = TestRnd
    Byte$ = CHR$(Bytes)
    PUT #1, , Byte$
  NEXT ByteCount&
  CLOSE #1

FUNCTION RAMValue ()

  STATIC RAMIndex, Segment&


  DEF SEG = Segment&
  RAMValue = PEEK(RAMIndex)
  DEF SEG

  RAMIndex = RAMIndex + 1

  IF RAMIndex = 256 THEN
    RAMIndex = 0
    Segment& = Segment& + 1
    IF Segment& = 65536 THEN
      Segment& = 0
    END IF
  END IF

END FUNCTION

FUNCTION TestRnd ()
'Timer entropy based random number generator.

  STATIC SampleTime&
  STATIC PrevElapsed&


  PowerTwo = 1


  FOR BitIndex = 1 TO 8

    FOR Sample = 1 TO 41
      PITReadTicks TicksHi, TicksLo
      Entropy = Entropy XOR TicksHi XOR TicksLo XOR RAMValue
    NEXT Sample

    Byte = (Byte XOR (Entropy * PowerTwo)) MOD 256
    PowerTwo = PowerTwo + PowerTwo

  NEXT BitIndex
  
  
  TestRnd = Byte

END FUNCTION

