
from struct import unpack,calcsize


class AnalyzeReader:
    "Reads dimensions and field of view data from an ANALYZE .hdr file"
    
    def __init__(self, fname):
        if (fname[-4:] == '.img') or (fname[-4:] == '.hdr'):
            self.filename = fname[:-4]
        else :
            self.filename = fname
        try:
            fid = open(self.filename + '.hdr')
        except IOError:
            print 'Cannot open file ' + self.filename + '.hdr'
            raise
        
        self._EndianChar = '>'
        #self._EndianChar = '<'
        
        # skip past header_key
        fid.read(40)
        
        # skip past extra 2 bytes (number of dimensions)
        fid.read(2)
        
        # get the dimensions of the image
        self.dim = unpack(self._EndianChar+'hhhh', fid.read(calcsize('hhhh')))
        
        if self.dim[3] != 1:
            print 'Error: found 4th dimension > 1 in file %s.hdr' % self.filename 
            raise ValueError

        self.dim = self.dim[0:3]
        
        # skip past some more stuff
        fid.read(20)
        
        # get the data type
        self.dtype = unpack(self._EndianChar+'H', fid.read(calcsize('H')))
        
        fid.read(8)
        
        # get the voxel dimensions
        self.pixdim = unpack(self._EndianChar+'fff',fid.read(calcsize('fff')))
        
        # calculate the field of view size
        self.fov = []
        for i in range(3):
            self.fov.append(round(self.pixdim[i] * self.dim[i]))
        
        fid.read(161)
        
        # get the image origin
        self.orig = unpack(self._EndianChar+'hhh', fid.read(calcsize('hhh')))

            
    def GetDim(self):
        return self.dim[:3]
    
    def GetFOV(self):
        return self.fov
    
    def GetOrigin(self):
        return self.orig

