function [data, yes, data_name] = dataread_nifti(data_folder,atlas,voxelwise)
%% read nifti data
% Input
%   data_folder  -  data folder. e.g. F:/xxx/
%   atlas        -  atlas. e.g F:/xxx/AAL_90_2mm.nii
%   voxelwise    -  voxelwise or not. 1 - yes; 0 - no;
% Output
%   data         -  subjid x rois
%   yes          - 1 indicates read data successfully, 0 otherwise.
%%

if voxelwise % whole brain mask
    A = spm_read_vols(spm_vol(atlas));
    data_Ind = find(A~=0);
    clear A
else % atlas
    A = spm_read_vols(spm_vol(atlas));
    rois = unique(A);
    rois(rois == 0) = [];
    for i=1:length(rois)
        data_Ind{i} = find(A == rois(i));
    end
    clear A rois i
end

Imgs = dir([data_folder,filesep,'*.nii']);
if isempty(Imgs)
    Imgs = dir([data_folder,filesep,'*.img']);
end

data      = zeros(length(Imgs),length(data_Ind)); % subjid x rois
data_name = cell(length(Imgs),1);
for i=1:length(Imgs)
    Name = Imgs(i).name;
    data_name{i} = Name;
    fprintf('Reading subject : %s \n',Name(1:end-4));
    A = spm_read_vols(spm_vol([data_folder,filesep,Name]));
    if voxelwise
        data(i,:) = A(data_Ind);
    else
        for iroi = 1:length(data_Ind)
            data(i,iroi) = nanmean(A(data_Ind{iroi}));
        end
        clear iroi
    end
    clear A Name
end
yes = 1;
end