function v = load_tMCimg_2pt(filename, dims)

% USAGE:
%
%    v = load_tMCimg_2pt(filename, dims)
%     
%
% DESCRIPTION:
%     
%    Loads a fluence data file generated by the tMCimg application into matlab. 
%    the dims argument is optional. If it is not supplied this function tries 
%    to find the dimensions from the .inp file with the same prefix. 
%
% EXAMPLE:
%    
%    sample1_2pt = load_tMCimg_2pt('sample1');
%
%
% AUTHOR:
%
%    Jay Dubb,     (jdubb@nmr.mgh.harvard.edu)


    if(~exist('dims') | isempty(dims))
        i=strfind(filename, '.2pt');    
        if(isempty(i))
            filename = strcat(filename, '.2pt');
            i=strfind(filename, '.2pt');
        end
        filename_input = filename;
        filename_input = strcat(filename_input(1:i-1), '.inp');
        config = read_tMCimg_inp(filename_input);
        if(isempty(config))
            error('Input file doesn''t exist and dimensions not given');
        end
        dims(1)=config.Sx_max-config.Sx_min+1;
        dims(2)=config.Sy_max-config.Sy_min+1;
        dims(3)=config.Sz_max-config.Sz_min+1;
        t=config.temporal_gates;        
        dims(4)=uint8((t(3)-t(1))/t(2));
    end


    nx=dims(1);
    ny=dims(2); 
    nz=dims(3);
    if(length(dims)>3)
        nt=dims(4);
    else
        nt=1;
    end

    file_stats = dir(filename);
    data_size = file_stats.bytes/(nx*ny*nz*nt);

    fid = fopen(filename, 'rb');
    if(data_size==4)
        v = single(fread(fid, 'float32'));
    elseif(data_size==8)
        v = double(fread(fid, 'float64'));
    else
        error('Wrong volume dimensions given');
    end
    v = reshape(v, dims);

    fclose(fid);
