function [flag]=nic_Template2Mask(imageREF,templateIN,AreaID,imageOUT)
% Convert the selected areas (AreaID) in the template (templateIN) to a mask
% image containing the index of the masking areas. The mask image is rearranged
% and output (imageOUT) with the same format as the reference image (imageREF). 
%
% FORMAT [flag]=nic_Template2Mask(imageREF,templateIN,AreaID,imageOUT)
%
% Input:
% 1. imageREF - full file path and name for the reference image
%               [path\*.img], i.e., the post-processed image
% 2. templateIN - full file path and name for the template [path\*.img]]
% 3. AreaID - a vector containing the ID(s) of selected brain area(s), e.g.,
%            [1] or [1 12 ...]
% 4. imageOUT - full file path and name for the output mask [path\*.img]
% Output:
% 1. 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_Template2Mask.m  ver 2.0, 07/11/27

%help nic_Template2Mask
if nargin < 4
    error('Providing sufficient parameters again');
end
% Resample the template file
outputNAME = nic_ImageResample(templateIN,imageOUT,imageREF,1);

% Read the template file
[Ymask,Head] = nic_ReadNiftiImage(outputNAME);
index = [];
Data = zeros(size(Ymask));

% Generate mask data
if length(AreaID) == 1
    index = find(AreaID==Ymask(:));
    Data(index) = AreaID;
else
    for nID = 1:length(AreaID)
        index = find(AreaID(nID) == Ymask(:));
        Data(index) = AreaID(nID);
    end
end

% Output mask brain
[flag] = nic_WriteMaskImage(Data,Head,imageOUT);
if flag == 1
    disp('Congratulations,all done')
else
    error('Please carefully check the whole processing step, do again')
end