function [Data, Head] = GIGICA_readNiftiImage(imageIN, volumeIndex)
% Read file(NIFTI, ...) for REST by CHEN Gui-Wen and YAN Chao-Gan
% %------------------------------------------------------------------------
% Read MRI image file (imageIN) with format of Nifti 1.1. It will return data
% of 3D matrix (Data) and infomation of the header (Head). Please set the volume
% index (1 for the first volume) you want to load into memory if the image file
% contains 4D data. The structure of header (Head) is the same with SPM5.
%
% Usage: [Data, Head] = rp_ReadNiftiImage(imageIN, volumeIndex)
%
% Input:
% 1. imageIN - the path and filename of image file, [path\*.img]
% 2. volumeIndex- the volume of 4D data to read, can be 1,2,..., not larger than
%             the number of total volumes, default: 'all' means read all
%             the time points.
% Output:
% 1. Data - 3D matrix of data
% 2. Head - a structure containing image volume information
% The elements in the structure are:
%       Head.fname - the filename of the image.
%       Head.dim   - the x, y and z dimensions of the volume
%       Head.dt    - A 1x2 array.  First element is datatype (see spm_type).
%                 The second is 1 or 0 depending on the endian-ness.
%       Head.mat   - a 4x4 affine transformation matrix mapping from
%                 voxel coordinates to real world coordinates.
%       Head.pinfo - plane info for each plane of the volume.
%              Head.pinfo(1,:) - scale for each plane
%              Head.pinfo(2,:) - offset for each plane
%                 The true voxel intensities of the jth image are given
%                 by: val*Head.pinfo(1,j) + Head.pinfo(2,j)
%              Head.pinfo(3,:) - offset into image (in bytes).
%                 If the size of pinfo is 3x1, then the volume is assumed
%                 to be contiguous and each plane has the same scalefactor
%                 and offset.
%        Head.private - a structure containing complete information in the header
% %------------------------------------------------------------------------
% Copyright (C) 2007 Neuroimage Computing Group, State Key Laboratory of
% Cognitive Neuroscience and Learning
% Guiwen Chen, gwenchill@gmail.com
% @(#)rp_ReadNiftiImage.m  ver 2.0, 07/11/24
% %------------------------------------------------------------------------
if ~exist('volumeIndex', 'var')
    volumeIndex='all';
end

    [pth,nam,ext] = fileparts(imageIN);
     filename = fullfile(pth,[nam '.nii']);
     [pathstr, fName, extn] = fileparts(deblank(filename));

    % Get info of header
    V = spm_vol(filename);
    if(~strcmpi(volumeIndex,'all'))  
        Data(:, :, :,1) = spm_read_vols(V(volumeIndex));
        Head=V(volumeIndex); % save Header info in structure
    else
        Data = spm_read_vols(V);
        Head=V(1); % save Header info in structure (just the first volume)
    end
    Data(isnan(Data)) = 0;

    clear V;
   
