% function [Im, head] = openINR(filename)
%--------------------------------------------------
% by P. DERIAN, january 2011
%--------------------------------------------------
%
% This function reads a *SCALAR* pixel-valued Inrimage-4 (.inr).
% Currently only *float32* and *double* precisions are supported,
% this can be easily extended. A matrix of double is returned in any case.
% The given image might be volumic.
%
% Parameter:    filename, name of the image.
% Returns :     Img, the matrix
%               head, the file header (optionnal !)
%
% Rem: for a simpler usage, don't forget to put this file 
% in Matlab's path !
%---------------------------------------------------

function [Im,head] = openINR(filename)

    if ~exist(filename,'file')

        fprintf('Unknown file %s !\n',filename);
        Z = [];
    else
        f = fopen(filename);
        %--read header (of size multiple of 256 bytes)
        head = fread(f,256,'*char')';
        while (~strfind(head,'}'))
            head = [head,fread(f,256,'*char')'];
        end;
        %--process header to get dimensions and data type
        info = textscan(head,'%s');
        Dx = getPropertyValue(info{1},'XDIM');
        Dy = getPropertyValue(info{1},'YDIM');
        Dz = getPropertyValue(info{1},'ZDIM');
        precision = getPropertyValue(info{1},'PIXSIZE');
        switch precision
            case 32
                format = 'float32=>double';
            case 64
                format = '*double';
            otherwise
                fprintf('ALAAAAARM !!\n\tUnrecognized precision\n\t=>we''re crashing happily, sorry ''bout that :P\nYour file''s header:');
                disp(info)
        end;
        %--read data plane by plane
        Im = zeros(Dy,Dx,Dz);
        for z = 1:Dz
            temp = fread(f,[Dx,Dy],format);
            %-matlab reads columnwise, so we need to transpose it
            Im(:,:,z) = temp';
        end;
        fclose(f);
    end;
end


%------------------------
% function [v] = getPropertyValue(strCell,propertyName)
%------------------------
%
% This is a very basic parser for Inrimage headers.
%------------------------

function [v] = getPropertyValue(strCell,propertyName)
    
    pattern = [propertyName,'='];
    index = strfind(strCell,pattern);
    p = 1;
    while isempty(index{p})
        p = p+1;  
    end;
    if (p>length(strCell))
        fprintf('Property %s not found ...\n',propertyName);
        v = 0;
    else
        c = textscan(strCell{p}(length(pattern)+1:end),'%n');
        v = c{1};
    end;
end