% batch_tstd
% Dec 15 2011. We will only calculate temporal std using the realigned
% data. 
org_pwd=pwd;
for groupnum=1
    par;

for sb = 1:length(PAR.subjects)
    pair1=[];pair2=[];
    for b=1:PAR.nsess(sb) 
        for c=1:PAR.ncond
            if ~isempty(PAR.condirs{sb,b,c})
            tsnrdir=PAR.condirs{sb,b,c};
            maskimg = spm_select('FPList', tsnrdir,'^mask_bet.nii$');
            maskimg=maskimg(1,:);
            vm=spm_vol(maskimg);
            mask=spm_read_vols(vm);
            mask=mask(:)>0;
            tmp=spm_select('FPList',tsnrdir, ['^ra' PAR.fmriprefix{c} '\w*\.nii$'] );
            if isempty(tmp)
                tmp=spm_select('FPList',tsnrdir, ['^ra' PAR.fmriprefix{c} '\w*\.img$'] );
            end
            
            v=spm_vol(tmp);
            dat=spm_read_vols(v);
            vo=vm;
            tsnr=zeros(vo.dim(1),vo.dim(2),vo.dim(3));
            dat=reshape(dat,vo.dim(1)*vo.dim(2)*vo.dim(3),size(dat,4));
            dat=dat(mask,:);
    %             tsnr(mask)=mean(dat,2)./std(dat,0,2);
            tsnr(mask)=std(dat,0,2);
            vo.dt(1)=16;
            vo.fname=fullfile(tsnrdir,['tSTD_epi_' num2str(b) '.nii']);
            vo=spm_write_vol(vo,tsnr);
            end
        end
    end
        
end
end


