
% Getting the number of contrasts and determining how many loops should be performed:
ncons = spm_input('Number of Contrasts',1, 'n');
[unit_max   tens_max   hund_max] = deal(0);
if ( ncons < 10 )
    unit_max = ncons;
elseif ( ncons >= 10  &  ncons < 100 )
    unit_max  = 9;
    tens_max  = ncons;
elseif ( ncons >= 100 & ncons <1000 )
    unit_max  = 9;
    tens_max  = 99;
    hund_max  = ncons;
else
    error('Too many Contrasts!');
end

% better to replace following line with spm_input('Enter Subjects', 2, 's+');
% but using s+ seems to make it inf loop???
subs     = spm_input('Enter subjects, separated by a ''\''', 2, 's');
subjlist = namelist(subs);
[ln,x]   = size(subjlist); % ln = number of subjects.
subdirs  = cellstr( spm_get(-ln,'.','Select subjects'' results dirs. containing Contrast images.') );
condir   = spm_get(-1,'.','Select directory to hold contrast directories.')

% Create the individual destination directories to hold the contrast images:
for i = 1 : ncons,
    if ( exist( [condir '/con' int2str(i)], 'dir') ~= 7 )
        mkdir(condir, ['/con' int2str(i)]);
    end
end
      

for j = 1:ln %to do the group; 
   		% this creates folders for group analysis
  
     	%this does the contrasts and moves them to the group folder
	 eval(['cd ' subdirs{j}]);
    %spm_bch_doCont
        %for k = 1 % F contrasts
        %copyfile ((['ess_000' int2str(k) '.hdr']), (['d:\fmri\kx\gsoK_group\con' int2str(k) '\' deblank(subjlist(j,:)) '_000' int2str(k) '.hdr']));
        %copyfile ((['ess_000' int2str(k) '.img']), (['d:\fmri\kx\gsoK_group\con' int2str(k) '\' deblank(subjlist(j,:)) '_000' int2str(k) '.img']));
        %end
    
    for p = 2 : unit_max % T contrasts
        if exist(['con_000' int2str(p) '.hdr'], 'file')
          k = p;%p-1;
          copyfile ((['con_000' int2str(p) '.hdr']), ([condir '/con' int2str(k) '/' deblank(subjlist(j,:)) '_0' int2str(k) '.hdr']));
          copyfile ((['con_000' int2str(p) '.img']), ([condir '/con' int2str(k) '/' deblank(subjlist(j,:)) '_0' int2str(k) '.img']));
        end
    end
    for p = 10 : tens_max
        if exist(['con_00' int2str(p) '.hdr'], 'file')
           k = p;%p-1;
           copyfile ((['con_00' int2str(p) '.hdr']), ([condir '/con' int2str(k) '/' deblank(subjlist(j,:)) '_0' int2str(k) '.hdr']));
           copyfile ((['con_00' int2str(p) '.img']), ([condir '/con' int2str(k) '/' deblank(subjlist(j,:)) '_0' int2str(k) '.img']));
        else
           break
        end
    end
    for p = 100 : hund_max
        if exist(['con_0' int2str(p) '.hdr'], 'file')
           k = p;%p-1;
           copyfile ((['con_0' int2str(p) '.hdr']), ([condir '/con' int2str(k) '/' deblank(subjlist(j,:)) '_0' int2str(k) '.hdr']));
           copyfile ((['con_0' int2str(p) '.img']), ([condir '/con' int2str(k) '/' deblank(subjlist(j,:)) '_0' int2str(k) '.img']));
        else
           break
        end
    end
    
end

