function [Cond, Vf, RT] = kc_get_design(varargin);

% Algorithm to extract design info from an SPMcfg file 
% so that it can later be used for plots and PST averaging.
%
% FORMAT [Cond, Vf, RT] = kc_get_design('Load');
% Asks for pre-specified SPMcfg.mat or kcSPMcfg.mat file and
% loads it.
%
% FORMAT [Cond, Vf, RT] = kc_get_design('Load',full_load_path);
% Where full_load_path is a string containing the full path to
% an SPMcfg.mat or a kcSPMcfg.mat file, loads without asking.
%
% FORMAT [Cond, Vf, RT] = kc_get_design('Specify');
% Asks for design parameter specification and saves them for
% later use in a kcSPMcfg.mat file.
%
% Cond    - structure containing information for each condition
% .name   - name of condition
% .iC     - indeces for this conditions in the columns of xX.X
% .iS     - corresponding condition indeces in each Sess
% .iSC    - session specific indeces for this condition
% .onsec  - the onsets for this condition (in sec)
% .onidx  - the onsets for this condition (in scans)
% .num_scans  - (a guess about the) duration of the PST in scans
%
% Vf		- structure containing information about the V-files
% .iS		- V-files indexed according to session
% .G		- global intensity for each V-file
% .VY		- memory-mapped V-files structure
%
% RT     - repetition time for the study
%
% ---------------------------------------------------------------
% Compatible with SPM99 files. 
% Uses SPMcfg.mat to load parameters or otherwise asks for input.
% 
% Condition names across different sessions are matched ignoring 
% letter case. The order in which conditions have been entered in 
% each session is not important.
% ---------------------------------------------------------------
% @(#) kc_get_design.m 1.2      Kalina Christoff       2000-06-15 


if nargin == 0 
  fprintf('\n\nWould you like to load the design parameters from');
  fprintf('\na prespecified SPMcfg.mat (SPM99) or kcSPMcfg.mat file?');
  fprintf('\n\nType [y] to ');
  tmp=input('load or [s] to specify design parameters now : ','s');
    if     strcmpi(tmp,'y'), Option='Load';
    elseif strcmpi(tmp,'s'), Option='Specify';
    
    else  
      error('\n\nEither ''y'' or ''s'' is expected. Please try again.\n\n');
    end
  clear tmp;
end


if nargin > 0 
   if     strcmpi(varargin{1},'Specify'), Option='Specify';
   elseif strcmpi(varargin{1},'Load'),    Option='Load';
   end
end

if nargin > 1
   if     strcmpi(varargin{1},'Load'), Option='Load'; 
   else   error('varargin1 illigal');
   end
   Input_SPMcfg_path=varargin{2};
end       

  
if nargin > 2
   error('\n\nToo many input arguments. Please try again.\n\n')
end


%================================================================
switch lower(Option), case 'load'        % load from a SPMcfg.mat
%================================================================

  if exist('Input_SPMcfg_path','var')
    SPMcfg_path = Input_SPMcfg_path;

  else
    % ask where file is and get it
    % ==========================================================
    SPMcfg_path = spm_get(1,'SPMcfg.mat',...
			 'Please select design specification file.');

  end


    if length(SPMcfg_path)>10 & strcmp(SPMcfg_path(end-11:end-10),'kc'),
         SPMcfg_file = SPMcfg_path(end-11:end);
    else SPMcfg_file = SPMcfg_path(end-9:end);
    end
    
    switch SPMcfg_file    % either 'kcSPMcfg.mat' or 'SPMcfg.mat'
    
    % ------------------------
    case 'kcSPMcfg.mat'
    % ------------------------
    load(SPMcfg_path); 
    

    % ------------------------
    case 'SPMcfg.mat'
    % ------------------------
    
	load(SPMcfg_path);
	
	% build Cond structure
	% --------------------
	
	% get # sessions
	n_sess         = length(Sess);

	% find the correct condition index corresponding to the same name
	% in each session, so that even conditions entered in different order
	% for the different sessions would be averaged correctly
	% ---------------------------------------------------------------------

	% get the names of all conditions in the entire experiment
	% ----------------
	  cond_names = [];
	  xX.iC         = [];    % the indeces in xX.X for hrf only

	  for s=1:n_sess
	    cond_names = [cond_names, Sess{s}.name];
	    tmp=[];
	    for i=1:length(Sess{s}.ind)
	       tmp    = [tmp, Sess{s}.ind{i}(1)]; 
	    end
	    xX.iC = [xX.iC, Sess{s}.col(tmp)];
	    clear tmp;
	  end

	  
	% make a best guess to figure out the number of conditions
	% ---------------------------------------------------------
	name_idx = 1:length(xX.iC);

	c=1; % start from condition one

	while ~isempty(find(name_idx))
	   Cond(c).name = cond_names(min(find(name_idx)));

	   % match the condition names, ignoring case
	   % ----------------------------------------
	   Cond(c).iC   = xX.iC(find(strcmpi(Cond(c).name,cond_names)))';
		
		  %-----------------------------------------------------------
	     if length(Cond(c).iC) < n_sess  % if this condition does not
                                        % appear in every session
		       s=1;
				 while s <= length(Cond(c).iC)
			
					i = s;
					while  Cond(c).iC(i) > max(Sess{i}.col)		
								Cond(c).iC(i+1:end+1,1)...
							   =Cond(c).iC(i  :end  ,1);
				  
	 						   Cond(c).iC(i)=0;
					  i = i+1;
					end
				   s = s+1;

				 end
			 
 		       Cond(c).iC(end+1:n_sess,1)=zeros;

		  end
		  % --------------------------------------------------------------

		  

		  
		Cond(c).iS  = zeros(n_sess,1);
	   Cond(c).iSC = zeros(n_sess,1);
	   cnt = 0; 

	   for s = 1:n_sess
		  idx = find(xX.iC==Cond(c).iC(s));
		  
		  if ~isempty(idx)
	      % Cond.iS is the indeces for this condition in each sessions
	      % ----------------------------------------------------------
	      Cond(c).iS(s) = name_idx(idx);

	      % Zero out the condition indeces that have been used
	      % --------------------------------------------------
	      name_idx(idx) = 0;    

	      % Cond.iSC is the session specific condition index
	      % ------------------------------------------------
		  Cond(c).iSC(s) = Cond(c).iS(s) - cnt;
		  end
	     cnt = cnt+length(Sess{s}.name);
	   end

	   c=c+1;                                   % update to next condition
	end

	clear cond_names s c name_idx idx cnt;

	% compose the G matrix by collapsing xX.X across session
	% ------------------------------------------------------
	n_cond=length(Cond);

	for c = 1:n_cond
	      Cond(c).X = sum(xX.X(:,Cond(c).iC(find(Cond(c).iC))),2);  
	end


	  % START LOOPING THROUGH CONDITIONS
	  % ================================
	  for c=1:n_cond

	    % convert all Sess{i}.ons into secs from the beginning of the experiment
	    % ----------------------------------------------------------------------
	    pst_ons=[];        % the onsets in sec

	    for s = 1:n_sess
	       if Cond(c).iSC(s)~=0          % skip this session if empty
				pst_ons = [pst_ons; ...
			   Sess{s}.ons{Cond(c).iSC(s)} + ...
			   + (min(Sess{s}.row)-1)*xX.RT ...
			 ];
	       end
	    end
		 
		 %
		 
       % get onset and offset indeces in V-files, first is 1
		 % rounding down would effectively subtract the fMRI_T0
		 pst_ons_idx = floor(pst_ons/xX.RT)+1;  
		 pst_offs_idx = [(pst_ons_idx(2:end)-1);max(Sess{n_sess}.row)];	
 

       RT = xX.RT;
       
        num_scans = round(32/RT);  % PST span in scans, default in sec=32s
      

	    Cond(c).onsec      = pst_ons;       % onsets in sec
	    Cond(c).onidx      = pst_ons_idx;   % onsets in scans
	    Cond(c).num_scans  = num_scans;    

	  % END LOOPING THROUGH CONDITIONS
	  % ==============================
	  end
      
       	
       % these mods currently under review - Jeff 10/3.    
           
       % modification made by Jeff Cooper, 10/1/2002 to replace the following
       % hack in Kalina's code:
       
      % fake mods - draft code
       
        % figuring out num_scans is actually kind of tricky.
        % The simplest way to do it I could figure is to loop through 
        % all the conditions except this one and find the one who has
        % an onset time  after this condition's first onset
        % but as close as possible to it - that should give us
        % the true condition length.
        
        % A note on this: we 
        % assume that each session contains more than one running
        % of a given condition.  Pretty safe in most cases.
        

%       for c = 1:n_cond
%            next_onsec_diff = (length(VY) * RT) + 1;
%            %initialize as being past the possible end
%            curr_onsec = Cond(c).onsec(1);
%            for i = 1:n_cond
%                if ~(c==i)
%                   test_onsec = Cond(i).onsec;
%                    test_onsec_greater = test_onsec(find(test_onsec > curr_onsec));
%                    if ~(isempty(test_onsec_greater))  %i.e., there is some later onset
%                        test_onsec_diff = test_onsec_greater - curr_onsec;
%                        closer_onsec = test_onsec_diff(find(test_onsec_diff < next_onsec_diff));
%                       if ~(isempty(closer_onsec))
%                          next_onsec_diff = min(closer_onsec);
%                        end
%                    end
%                end
%            end
%            % next_onsec should now be the onset of the next 
%            % condition to go on, meaning our current condition
%            % lasts until then.
%            Cond(c).num_scans = ceil(next_onsec_diff / RT);
%        end
        

	  
	  
	  % ------------------
	  % build Vf structure
	  % ------------------
	  
	  % .iS (V-files intexed according to sess)
	  % ----------------------------------------
	  Vf.iS = (xX.X(:,xX.iB))*(1:length(xX.iB))';
	  
	  % check if all's fine
	  tmp = xX.Xnames(xX.iB);
	  if length(xX.iB) ~= n_sess | ...
			  length(findstr([tmp{:}],'constant')) ~= n_sess
		 error ('Could not successfully determine session length.\n\n');
	  end
	  
	  % .G (global intensity for each V-files)
	  % --------------------------------------
	  Vf.G = xGX.rg;
	  
	  % .VY 
	  % ----
	  Vf.VY = VY;


   % END switch SPMcfg_file
   % ----------------------
   end


%=====================================================================
case 'specify'                 % enter params and save in kcSPMcfg.mat
%=====================================================================


   n_cond = input('\n\nEnter the number of conditions : ');

   fprintf('\n\nEnter the number of scans (V-files) in the entire\n');
   scans  = input('experiment : ');
   
   TR     = input('\n\nEnter the TR in seconds : ');


   % START LOOPTING THROUGH CONDITIONS
   % ---------------------------------
   for c = 1:n_cond

    fprintf('\n\n=============== Condition  %d =============\n\n',c);
    Cond(c).name = cellstr(input('Enter name for this condition : ','s'));

    fprintf('\n\nEnter a vector representing the onsets for this ');
    fprintf('condition in scans.\nThe first scan is 1. Your last ');
    fprintf('scan is %d.\nEnter as many numbers as the number of times ',...
                     scans);
    fprintf('this condition was \nrepeated in the experiment.');

    tmp = input('\n\nOnsets vector : ','s');
    Cond(c).onidx = str2num(tmp)'; 
    clear tmp;
 
    Cond(c).num_scans = input(...
         '\nEnter the number of scans in the peri-stimulus period : ');

    Cond(c).min_elapse = Cond(c).num_scans*TR;



    % pst_idx for this condition, to be used to averaging later
    % ---------------------------------------------------------
    Cond(c).pst_idx = zeros(scans,1);

    for i=1:Cond(c).num_scans
     
      % if the last trials pst does not exceed the session limit
      % --------------------------------------------------------
      if     Cond(c).onidx(end)+i-1 <= scans,
             Cond(c).pst_idx(Cond(c).onidx+i-1)=i;         

      else   Cond(c).pst_idx(Cond(c).onidx(1:end-1)+i-1)=i; 

      end
    end     
  
   % END LOOPING THROUGH CONDITIONS
   % ------------------------------
   end
	
	
	% -------------------------
	% build Vf structure
	% -------------------------
	
	% .iS (V-files indexed according to sess)
	% ----------------------------------------
	for i = 1:n_sess
	  fprintf('\n\nEnter the nmber of scans for session %g',i);
	  numVf(i)=input(' : ');
	end
	
	Vf.iS = ones(numVf(1),1);
	
	for i=2:n_sess
	  Vf.iS = [Vf.iS; i*ones(numVf(i),1)];
	end
	
	% .G (global intensity for each V-files
	% --------------------------------------
	Vfiles = spm_vol(spm_get(sum(numVf), ...
				 '*.img','Select all V-files for this subject'));
	for i = 1:sum(numVf)
	  Vf.G(i) = spm_global(Vfiles(i));
	end
	
	% .VY
	% ----
	Vf.YV = Vfiles;
	
   
	% ask whether to save the specifications as 'kcSPMcfg.mat' 
   % --------------------------------------------------------
   fprintf('\n\n-----------------------------------------------');
   fprintf('\nDone.');
   fprintf('\n\nWould you like to save this design ');
   tmp=input('specification? \nType [y] to save : ','s');

   if strcmpi(tmp,'y'), 
         save kcSPMcfg Cond Vf;
         fprintf('\n\nA new kcSPMcfg.mat file was created in');             
         fprintf('\n%s\n\n',pwd);
   end

   clear tmp;

% END switch Option
% -----------------
end













