#!/usr/bin/python3
import os,sys,math
import numpy as np

#Write double ndarray
def fwrite_dndarray(fp,array):

    array = np.array(array,dtype=np.float64,order='F')

    Ndim = np.int32(len(array.shape))
    shp = np.int32(array.shape)

    q = Ndim.tobytes()
    fp.write(q)
    if(Ndim>0):
        q = shp.tobytes()
        fp.write(q)

        q = array.tobytes()
        fp.write(q)

    return

#Read double ndarray
def fread_dndarray(fp):

    array = np.zeros((),dtype=np.float64,order='F')

    q = fp.read(4)
    Ndim = np.frombuffer(q,dtype=np.int32,count=1)[0]
    
    if(Ndim>0):
        q = fp.read(4*Ndim)
        shp = np.frombuffer(q,dtype=np.int32,count=Ndim)
        piprod = 1
        for i in range(0,len(shp)):
            piprod = piprod*shp[i]
        q = fp.read(8*piprod)
        array = np.frombuffer(q,dtype=np.float64,count=piprod)
        array = array.reshape(shp,order='F')
        
    return array

#Write float ndarray
def fwrite_fndarray(fp,array):

    array = np.array(array,dtype=np.float32,order='F')

    Ndim = np.int32(len(array.shape))
    shp = np.int32(array.shape)

    q = Ndim.tobytes()
    fp.write(q)
    if(Ndim>0):
        q = shp.tobytes()
        fp.write(q)

        q = array.tobytes()
        fp.write(q)

    return

#Read float ndarray
def fread_fndarray(fp):

    array = np.zeros((),dtype=np.float32,order='F')

    q = fp.read(4)
    Ndim = np.frombuffer(q,dtype=np.int32,count=1)[0]
    
    if(Ndim>0):
        q = fp.read(4*Ndim)
        shp = np.frombuffer(q,dtype=np.int32,count=Ndim)
        piprod = 1
        for i in range(0,len(shp)):
            piprod = piprod*shp[i]
        q = fp.read(4*piprod)
        array = np.frombuffer(q,dtype=np.float32,count=piprod)
        array = array.reshape(shp,order='F')
        
    return array