import random
import os
from ctypes import *
from ctypes.util import find_library

# If running on phylocluster
pp = os.getenv('PYTHONPATH')
if pp == '/home/ebo87/lib/python2.7/site-packages':
    lib = cdll.LoadLibrary('/home/ebo87/lib/librngstreams.so')
else:
    libname = find_library('rngstreams')
    lib = cdll.LoadLibrary(libname)

class RngStream_InfoState(Structure):
    _fields_ = [("Cg", c_double * 6),
                ("Bg", c_double * 6),
                ("Ig", c_double * 6),
                ("Anti", c_int),
                ("IncPrec", c_int),
                ("name", c_char_p)]

rngp = POINTER(RngStream_InfoState)
lib.RngStream_CreateStream.restype = rngp
lib.RngStream_CreateStream.argtypes = [c_char_p]
lib.RngStream_RandU01.restype = c_double
lib.RngStream_RandU01.argtypes = [rngp]
lib.RngStream_ResetNextSubstream.argtypes = [rngp]

class sprng(random.Random):
    def __init__(self):
        self.stream = lib.RngStream_CreateStream("a_stream")
    
    def random(self):
        return lib.RngStream_RandU01(self.stream)

    def getstate(self):
        return self.stream.contents

    def printstate(self):
        lib.RngStream_WriteStateFull(self.stream)

    def jumpasubstream(self, n):
        for i in range(n):
            lib.RngStream_ResetNextSubstream(self.stream)    
