function perm_order = rri_perm_order(num_subj_lst, num_cond, num_perm)
%
%  USAGE:  perm_order = rri_perm_order(num_subj_lst, num_cond, num_perm)
%   
%  Method:  
%     There are 2 steps to generate the permutation orders.  First permute 
%     tasks within each subject, then apply permutation for subjects across
%     groups.  
%
%  Input:
%         num_subj_lst: a N elements vector, each element specifies
%			the number of subjects of one of the groups.
%         num_cond:	number of conditions in the experiment
%         num_perm:	number of permutation to be performed
%
%  Output: 
%        perm_order:	an MxN matrix that stores the new order for 
%			the N permutations, where M is the total number
%			of rows of the st_datamat.
%			(i.e M = num_subj_grp * num_cond)
%

  num_subj_grp = sum(num_subj_lst);
  total_rows = num_subj_grp * num_cond;
  row_idx = 1:total_rows;

  perm_order = zeros(total_rows,num_perm);

  for p=1:num_perm,

     cnt = 0;
     duplicated = 1;
     while (duplicated)
        cnt = cnt+1;

        first = 1;
        last = 0;
        task_group = [];
        for g=1:length(num_subj_lst)
           last = last + num_cond*num_subj_lst(g);
           tmp = reshape([first:last],num_subj_lst(g),num_cond);
           task_group = [task_group, tmp'];
           first = last + 1;
        end

        %  permute tasks within each group.
        %
        for i = 1:num_subj_grp,
            task_perm = randperm(num_cond);
            task_group(:,i) = task_group(task_perm,i);
        end;

        %  permute tasks across groups
        %
        group_perm = randperm(num_subj_grp);
        task_group = task_group(:,group_perm);

        new_perm_order = [];
        for g=1:length(num_subj_lst)
           tmp = ...
              task_group(:,[sum(num_subj_lst(1:(g-1)))+1:sum(num_subj_lst(1:g))]);
           tmp = reshape(tmp', [num_cond*num_subj_lst(g),1]);

           new_perm_order = [new_perm_order; tmp];
        end

        %  make sure the permuation order is not a repeated one
        duplicated = 0;
        for i=1:p-1,
           if isequal(perm_order(:,i),new_perm_order)
               duplicated = 1;
               break;
           end;
        end;

        %  treat sequential order as duplicated one
        %
        if isequal([1:total_rows]', new_perm_order)
           duplicated = 1;
        end

        if (cnt > 500),
            duplicated = 0;
            disp('ERROR:  Duplicated permutation orders are used!');
        end;

     end;  % while (duplicated)

     perm_order(:,p) = new_perm_order;

  end;  % for num_perm

  return;

