function dtiMakeBrainMaskSafe(dtiDir,  dtiAlignedAvgFile)

%E.g., dtiMakeBrainSafeMask('dti06rt', 'dti_g712_b2000_aligned_trilin_avg.nii.gz')
%Take brainMask.nii.gz and remove the voxels that have a zero in the raw data (at
%least in one gradient directions)
%Input: directory with raw dti data
%Will overwrite your brainMask.nii.gz with a new safer one.

%ER 02/23/2009 pulled code out of mtrNotes to perform this operation
%ER 09/09 removed redundant code and changed input (dtiRawDir->dtiAlignedAvgFile)

dirPrev = pwd;
ni=niftiRead(dtiAlignedAvgFile);

% Update brain mask so that bad voxels are removed
cd([dtiDir filesep 'bin']);
bm = niftiRead('brainMask.nii.gz');
rawm = min(ni.data,[],4);
bm.data(rawm<1) = 0;

%bm.fname='brainMaskRawSafe.nii.gz';
writeFileNifti(bm);

cd(dirPrev);

return;
