function crbrain=cba_sig2avg(rbrain, z,isbrain)
%transform voxel time series from raw signal to avg. cluster signal.
%input:
%rbrain: nxnxnumslicesxtc 4d data. 
%z: nxnxnumslices clusters. 
crbrain = zeros(size(rbrain));

ind = zeros(sum(sum(sum(isbrain))),4);
k=1;
for h=1:size(z,3)
    for i=1:size(z,1)
        for j=1:size(z,2)
            if isbrain(i,j,h)>0
                ind(k,:) =[z(i,j,h) h i j];
                k=k+1;
            end
        end
    end
end

for k=1:max(max(max(z)))
    cind = ind(ind(:,1)==k,:);
    if  isempty(cind) 
        continue;
    end;
    tc = zeros(size(rbrain,4),1);
    for i=1:size(cind,1)
        tc = tc + squeeze(rbrain(cind(i,3), cind(i,4),cind(i,2),:));
    end
    tc = tc/size(cind,1);
    for i=1:size(cind,1)
        crbrain(cind(i,3), cind(i,4),cind(i,2),:) = tc;
    end
end
        

