function rp_intersection_mask_run(InputDir,MaskFile,OutputDir,Prefix,idx)
%-----------------------------------------------------------
%   Copyright(c) 2021
%	Written by Li Zi-qi 210623
%	http://www.restfmri.net/
[MaskData,VoxDimMask,HeaderMask]=rp_readfile(MaskFile);
MaskDataOneDim=reshape(MaskData,1,[]);
ImgList=dir_NameList(InputDir);
ResultsSum=ones([size(MaskData,1),size(MaskData,2),size(MaskData,3)]);
for i=1:length(ImgList)
    fprintf('.');
    tmp_img_path=[InputDir filesep ImgList{i}];
    [ResultsBrain,Header]=get_Volume_mean(tmp_img_path,MaskDataOneDim);
    RData=ResultsBrain~=0;
    ResultsSum=ResultsSum.*RData;
end

rp_WriteNiftiImage(ResultsSum,Header,[OutputDir filesep Prefix '_' num2str(idx) '.nii']);
fprintf('Get Intersection Mask is done!\n');
end

function [ResultsBrain,Header]=get_Volume_mean(tmp_img_path,MaskDataOneDim)
    [Outdata,VoxDim,Header]=rp_readfile(tmp_img_path);
    [~,~,~,nVolume]=size(Outdata);
    if nVolume>1
        AllVolume=reshape(Outdata,[],nVolume)';
        ResultsVolume=mean(AllVolume);
    elseif nVolume==1
        ResultsVolume=reshape(Outdata,[],1)';
    else
        error('InputImage Volume must be 3d or 4d Image!');
    end
    ResultsVolume=ResultsVolume(:,find(MaskDataOneDim));
    ResultsBrain=zeros(size(MaskDataOneDim));
    ResultsBrain(1,find(MaskDataOneDim))=ResultsVolume;
    ResultsBrain=reshape(ResultsBrain,size(Outdata,1),size(Outdata,2),size(Outdata,3));
end