function isbrain = brain_thresh(mask_files,numslices);
%BRAIN_TRHESH segments the data into brain and background. The area segmented as brain is the one that
%was segmented as brain by ALL  mask files. 
%
%ISBRAIN = BRAIN_THRESH(MASK_FILES,NUMSLICES);
%
%MASK_FILES: is a cell array of names of 4D fMRI image files with multiple  frames
%in ANALYZE (.img)  format.  
%
%NUMSLICES: the number of slices. 
%
%ISBRAIN: a 3D matrix with entry 1 for brain and 0 for background. 


minthresh = 400; % all voxels with signal below minthresh are considered background

mask_file=char(mask_files(1));
 mask_thresh=fmri_mask_thresh(mask_file);

 dm = fmris_read_image(mask_file,1:numslices,1);
isbrain = dm.data>max(mask_thresh,minthresh);

%first and last slice are ignored 
isbrain(:,:,1) = zeros(size(isbrain,1),size(isbrain,2));
isbrain(:,:,numslices) = zeros(size(isbrain,1),size(isbrain,2));

if length(mask_files)>1
    for i=2:length(mask_files) 
        mask_file=char(mask_files(i));
        mask_thresh=fmri_mask_thresh(mask_file)
        dm = fmris_read_image(mask_file,1:numslices,1);
        isbraintemp =  dm.data>max(mask_thresh,minthresh);
        isbrain(isbraintemp==0)=0; %include only voxels that were considered brain by all files. 
    end
end
     

