% list onsets in SPM.mat file
% input (from GUI): subject dirs, results dir, output dir
% output: tab-deliminated text file in specified output dir containing
%	  onsets organized by subject, session, and condition
% by Dara Ghahremani (dara@psych.stanford.edu) - 10/27/03

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % get subject dirs
    dirs = spm_get(-Inf, '.img', 'Select subject directories to add');
    dirs = cellstr(dirs);
    dirs = deblank(dirs);
    for i = 1:length(dirs)
        [dummy_dir, dummy_file, dummy_ext] = fileparts(dirs{i});
        if (strcmp(dummy_ext,'.') | strcmp(dummy_ext,'')) & isempty(dummy_file)
            % we've selected a directory from within it, and
            % hence subj_name ends in /.  So let's strip it
            dirs{i} = dummy_dir;
        end
    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % get results dir
    dir = spm_get(-1, '.img', 'Select results directory from one subject');
    dir = deblank(dir);

    [dummy_dir, display_dir, dummy_ext] = fileparts(dir);
    if strcmp(dummy_ext, '.') & isempty(display_dir)
        % dir ends in /., so strip those
        dir = dummy_dir;     
        display_dir = dummy_dir;
        [dummy_dir, display_dir] = fileparts(display_dir);
    end
    
    % initial guess at resdir
    [dummy_dir, resdir] = fileparts(dir);

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % output file
    outdir = spm_get(-1, '.img', 'Select directory for output file(s)');
    output_file = fullfile(outdir,'spm_onsets.txt')

    %outdir = deblank(outdir);
    %[dummy_dir, display_dir, dummy_ext] = fileparts(outdir);
    %if strcmp(dummy_ext, '.') & isempty(display_dir)
    %    % dir ends in /., so strip those
    %    outdir = dummy_dir;     
    %    display_dir = dummy_dir;
    %    [dummy_dir, display_dir] = fileparts(display_dir);
    %end
    % initial guess at resdir
    %[dummy_dir, outdir] = fileparts(outdir);

    

subjects=dirs;
cwd=pwd;

fid=fopen(output_file,'wa');

for subj=1:length(subjects),

   subjdir = fullfile(subjects{subj},resdir);

   fprintf('Onsets from: %s\n',subjdir);
   fprintf(fid,'Subject: %s\n',subjdir);

   
   cd(subjdir)
   load SPM.mat
   for sess=1:length(Sess),
    for cond=1:length(Sess{sess}.ons),
		fprintf('Sess. %d\tCond %d (%s):\t',sess,cond,Sess{1}.name{cond});
		fprintf(fid,'Sess. %d\tCond %d (%s):\t', sess,cond,Sess{1}.name{cond});
 	        fprintf('%0.3f\t',(Sess{sess}.ons{cond} - xX.dt) / xX.RT); 
 	        fprintf(fid,'%0.3f\t',(Sess{sess}.ons{cond} - xX.dt) / xX.RT); 

		fprintf('\n');
		fprintf(fid,'\n');
    end
   end
end    

fclose(fid);

fprintf('\n\nOutput file spm_onsets.txt written to: \n%s\n\n',output_file);

cd(cwd)