function [matOUT flag]=nic_Mask2Signal(Path,MaskIN,matOUT)
% Extract the signals from the images which are put into the directory using
% the mask (MaskIN) and output the extracted signals to the file (matOUT). 
% For caution's sake, the directory (Path) is only required
% to store the post-processed images (e.g., the normalised images).
%
% FORMAT [flag]=nic_Mask2Signal(Path,MaskIN,matOUT)
%
% Input:
% 1. Path - full file path for storing the images
% 2. MaskIN - the mask image [path\*.img]
% 3. matOUT - the output file name for storing the extracted signals,
%             each cell corresponds to each mask index. The order each cell
%             was determined according to the increased order of the index
%             contained in the mask. For 4-D functional images, the row of any cell denotes
%             scan time and column denotes voxel point which was ordered
%             based on the default index of matlab bulit-in procedure.
% Output:
% 1. matOUT - full file name for storing the extracted signals
% 2. flag - a flag for all done, 1: successful, 0: fail
%
%_______________________________________________________________________
% Copyright (C) 2007 Neuroimage Computing Group, State Key Laboratory of
% Cognitive Neuroscience and Learning
%
% Liang Wang, wanglbit@gmail.com
% @(#)nic_Mask2Signal.m  ver 2.0, 07/11/28

%help nic_Mask2Signal
oldpath=pwd;
if nargin < 3
    error('Providing sufficient parameters again');
end
cd(Path);
% Read the mask file
[Ymask,Head] = nic_ReadNiftiImage(MaskIN);

% Read the template file
files=nic_spm_select('List',Path, '^*\.img$');
V=nic_spm_vol(files);
maskId=unique(Ymask(:));
maskId(~maskId)=[];
maskNum=length(maskId);
tc=cell(maskNum,1);
for nID=1:maskNum
    index=find(maskId(nID)==Ymask(:));
    [I,J,K] = ind2sub(size(Ymask),index);
    XYZ=[I J K]';
    XYZ(4,:)=1;
    VY = nic_spm_get_data(V,XYZ);
    tc{nID}=VY;
end

% Output mask brain
cd(oldpath);
save(matOUT,'tc');
if exist([matOUT])
    flag = 1;
   disp('Congratulations,all done');
else
    error('Please carefully check the whole processing step, do again')
end