function V = nic_getVol(files, number)
% USE SPM2 functions to read the volume and if any warning message appears
% for ignoring hdr.hist.orient field then use spm5 function to get the
% volume

% number of files
countFiles = size(files, 1);

% first file
firstFile = deblank(files(1, :));

[pathstr, imFile, imExtn] = fileparts(firstFile);

% Turn off all warnings
warning off all;

[spmPath, spm2Path, spm5Path] = nic_getSPMPath(imExtn);

addpath(spmPath);

oldDir = pwd;

if strcmpi(imExtn, '.img')
    icatb_check_hdr_file(firstFile);
end

try

    if strcmp(spmPath, spm2Path)
        % Use orientation to determine whether it is nifti compatible
        % analyze image or regular analyze image
        V = nic_spm_vol_ana(firstFile, 1); % Get mat file info using spm2
        spm2Mat = V(1).mat;
        VN = nic_spm_vol_nifti(firstFile, 1); % Get mat file info using spm5
        spm5Mat = VN(1).mat;
        % Get the differenic_e
        diffV = VN(1).mat(:, 4) - V(1).mat(:, 4);
        if length(find(diffV == 0)) ~= 4
            warning('Ignoring hdr.hist.orient field');
        end

    else
        V = nic_spm_vol_nifti(firstFile, 1);
    end

    warnMsg = lastwarn;

    lastwarn('');

    warning on;

    % USE SPM5 functions to deal this
    if icatb_findstr(warnMsg, 'Ignoring hdr.hist.orient field')
        spmPath = spm5Path;
    end

    addpath(spmPath);
    
    if strcmpi(spmPath, spm5Path)

        clear V;
        try
            cd(spmPath);        
            V = nic_spm_vol(files);

            if exist('number', 'var')
                if max(number) > length(V)
                    error(['Image number requested exceeds the number of images']);
                end
                V = V(number);
            end
            cd(oldDir);
        catch

            cd(oldDir);
            nic_displayErrorMsg;

        end

    else


        % different time points
        diffTimePoints = zeros(1, size(files, 1));

        % loop over files
        for ii = 1:size(files, 1)
            diffTimePoints(ii) = nic_get_countTimePoints(deblank(files(ii, :)));
        end
        % end loop over files


        if ~exist('number', 'var')
            number = [1:sum(diffTimePoints)];
        end

        % replicate volume
        V = repmat(V, sum(diffTimePoints), 1);

        count = 0;
        % loop over files
        for ii = 1:size(files, 1)
            % loop over different time points
            for jj = 1:diffTimePoints(ii)
                count = count + 1;
                V(count) = nic_spm_vol_ana(deblank(files(ii, :)), jj);
            end
            % end loop over different time points
        end
        % end loop over files

        V = V(number);

    end

    % add pixdim field
    if ~isfield(V(1).private.hdr, 'pixdim')

        for nVol = 1:length(V)
            V(nVol).private.hdr.pixdim = V(nVol).private.hdr.dime.pixdim;
        end

    end

catch
    lastwarn('');
    warning on;
    icatb_displayErrorMsg;
end