"""
Created on Tue Oct 13 2020

@author: Anders Bjorholm Dahl
abda@dtu.dk
"""
import numpy as np
import io

def readvol(file_name):
    """
    Todo: Test this function on images of uint8, uint16, and when dimensions are 
    not all the same.
    
    Parameters
    ----------
    file_name : Sting
        name of .vol and .vgi files without extension

    Returns
    -------
    V : numpy array (float32, uint8, or uint16)
        3D volume.

    """
    vgi_name = file_name + '.vgi'
    f = io.open(vgi_name, 'r')
    t = f.read()
    f.close()
    elem = []
    dt = ''
    for l in t.splitlines():
        if(l.startswith('Size = ')):
            elem = [int(n) for n in l.split() if n.isdigit()]
        if(l.startswith('Datatype = float')):
            dt = np.float32
        elif(l.startswith('Datatype = uint8')):
            dt = np.uint8
        elif(l.startswith('Datatype = uint16')):
            dt = np.uint16

    vol_name = file_name + '.vol'
    V = np.fromfile(vol_name, dtype = dt, count = elem[0]*elem[1]*elem[2])
    V = np.reshape(V, (elem[2], elem[0], elem[1]))
    V = V.transpose((0,2,1))

    return V