% Batch script (linear pipeline) for MEG analysis in SPM5   
% Rik Henson MRC CBU Sep 08
%
% Note that would benefit from modularisation (eg for stop/start
% running), but wanted all steps in one file to ease exposition
%
% First start SPM with (at the CBU) "spm 5 eeg" from Linux prompt

clear

wd = '/imaging/ms02/MasterclassDemo/Again/';   % !!!REPLACE WITH YOUR DIRECTORY!!!
cd(wd)

% Extra bit for MEG masterclass as maxfiltered files not stored in own
% working directory.   
fifd = '/imaging/ms02/MasterclassDemo/';    % Location of the maxfiltered files

addpath /imaging/local/spm/spm5/cbu_updates/    
% Or update direct from SVN http://imaging.mrc-cbu.cam.ac.uk/svn/spm5_cbu_updates/devel/
addpath /imaging/local/meg_misc/    
% Or update direct from SVN http://imaging.mrc-cbu.cam.ac.uk/svn/meg_misc/devel/

%%%%%%%%%% Different types of sensor
typ{1}   = 'mags'; typ{2} = 'grds'; typ{3} = 'eeg';
typ{4}   = 'grms';  % RMS of grads; just for sensor-level analyses 
Ntyp     = length(typ);
eegflag  = [0 0 1 0];         % Binary flag for which typ is EEG

% Num channels per type (if differs across subjects, can re-specify below)
Nchan(1) = 102;    Nchan(2) = 204;   Nchan(3) = 70;
Nchan(4) = 102;

% Any user-thresholds for rejection for each of above (Inf=none)
thr(1)   = Inf;    thr(2)   = Inf;   thr(3)   = 120;
thr(4)   = Inf;
EOGthr   = 120;   % EOG threshold (EOG is duplicated in each file)

%%%%%%%%%% Experiment-specific parameters
expwin      = [-100 400];                    % Epoch window (in ms)
expcodes    = [1:8];                         % Codes in FIF file to extract
offset      = [ones(1,length(expcodes))*34]; % t=0 offset (eg visual delay)
newcodes    = [1 1 1 1 2 2 2 2];             % Any new (recoding) of above
expcons     = [1 0; 0 1; 1 -1; 1/2 1/2];     % Contrasts (on NEW codes)
Ncons       = size(expcons,1); 
		 
%%%%%%%%%% Raw FIF files on network 
% (cell of cells for each session of each sub (only one session here))
% Eg if instead two sessions per subject:
%    Fifdata = { { '/megdata/cbu/lfp/meg08_0014/080117/block1_raw.fif';
%                  '/megdata/cbu/lfp/meg08_0014/080117/block2_raw.fif'} };
fifdata = {
           {'/megdata/cbu/lfp/meg08_0014/080117/block4_raw.fif'};
           {'/megdata/cbu/lfp/meg08_0015/080118/block4_raw.fif'};
           {'/megdata/cbu/lfp/meg08_0016/080118/block4_raw.fif'};
           {'/megdata/cbu/lfp/meg08_0038/080131/block4_raw.fif'};
           {'/megdata/cbu/lfp/meg08_0064/080212/block4_raw.fif'};
           {'/megdata/cbu/lfp/meg08_0111/080303/block4_raw.fif'};
           {'/megdata/cbu/lfp/meg08_0112/080303/block4_raw.fif'};
           {'/megdata/cbu/lfp/meg08_0113/080303/block4_raw.fif'};
           {'/megdata/cbu/lfp/meg08_0127/080310/block4_raw.fif'};
	     }


%%%%%%%%%% Raw DICOM files on network (one per subject)
mridata = {
           '/mridata/cbu/CBU080769_CBU080769/20080916_095501/Series_002_CBU_MPRAGE';
           '/mridata/cbu/CBU071255_CBU071255/20071218_150851/Series_002_CBU_MPRAGE';
           '/mridata/cbu/CBU071151_CBU071151/20071116_140044/Series_002_CBU_MPRAGE';
           '/mridata/cbu/CBU071229_CBU071229/20071211_112249/Series_002_CBU_MPRAGE';
           '/mridata/cbu/CBU080034_RIS13667/20080111_102845/Series_002_CBU_MPRAGE';
           '/mridata/cbu/CBU080292_CBU080292/20080418_161843/Series_002_CBU_MPRAGE';
           '/mridata/cbu/CBU080358_CBU080358/20080506_151233/Series_003_CBU_MPRAGE';
           '/mridata/cbu/CBU080413_CBU080413/20080522_124313/Series_002_CBU_MPRAGE';
           '/mridata/cbu/CBU080802_CBU080802/20080930_090538/Series_002_CBU_MPRAGE';
	  };


%%%%%%%%%% Bad channel names noticed by Operator or post hoc (eeg/meg,sub,ses)
badchans{1,1,1} = [1143];
badchans{1,2,1} = [1143 0913 1013 0313 0933 2222 0642 1232 1913];
badchans{1,3,1} = [1143];
badchans{1,4,1} = [1143 2223 0432];
badchans{1,5,1} = [1143];
badchans{1,6,1} = [1143];
badchans{1,7,1} = [1143 2223];
badchans{1,8,1} = [1143 1412];
badchans{1,9,1} = [1143 2223];

%%%%%%%%%% Bad EEG channels noticed by Operator or post hoc (in terms of NAME)
badchans{2,1,1} = [48 50 73];                 % Poor contact
badchans{2,2,1} = [7 13 16 24 46 48 57];      % Drifting
badchans{2,3,1} = [48];                       % Drifting
badchans{2,4,1} = [48];                       % Drifting
badchans{2,5,1} = [15 40 49];                 % Poor contact
badchans{2,6,1} = [48];                       % Drifting
badchans{2,7,1} = [48 72];                    % No deflection (odd N170 topo)?
badchans{2,8,1} = [65 48];                    % odd in final topo of N170?
badchans{2,9,1} = [20 31 45];                 % 45 poor contact; 20+31 highfreq noise

% (Just happens that any EEG Channels 61 onwards are numbered 65 onwards in our lab!)
for sub=1:size(badchans,2)
  for ses=1:size(badchans,3)
   f = find(badchans{2,sub,ses}>60);
   badchans{2,sub,ses}(f) = badchans{2,sub,ses}(f)-4;
  end
end

%%%%%%%%%%% subject-specific parameters
%dosubs   = [1:9];      % Subjects to run, eg for subset: dosubs = [5:8]; 
dosubs   = [1:8];       % Exclude sub9 because MRI segmentation requires manual re-
                        % positioning first (can try yourself; see MRI section below!)
                        % (in fact for many, eg sub5 too, normalisation is much
                        % better after manual repositioning)
Nsub     = length(dosubs);

% Below assumes that two EOG channels (VEOG and HEOG), which will be
% appended at end of every data-file. Note that this script does not yet
% handle concurrent ECG (see Jason Taylor for how to do this)
for s = 1:Nsub
 subnum = dosubs(s);
 for m = 1:Ntyp;
   Nsubchan(s,m) = Nchan(m);  % In case different number of channels (eg EEG) for some subjects
  chan_thr{s,m} = [ones(1,Nsubchan(s,m))*thr(m) EOGthr EOGthr]; 
 end
end

VitECapsules = ones(1,max(dosubs));  % Whether MRIs have Vitamin E capsule (all here)

%%%%%%%%%%% control flags (1=do step; 0=omit step)
maxfiltflag = 0; maxmvcompflag = 0; maxtransflag = 0; 
usemaxmvcompflag = 0; usemaxtransflag = 1; 
chancheckflag = 0; respmflag = 1; reprocessflag = 1; 
getmriflag = 0;
write2Dflag = [1 0 1 1]; write3Dflag = 0;
grpinvertflag = 0;     % Whether invert using group priors (after individual inversions)
                       % (Litvak & Friston, 2008, Neuroimage)
fusionflag = 0;        % Whether want to simultaneously invert (fuse) modalities (typs)
                       % (Henson et al, submitted)
		       
%%%%%%%%%% General parameters
% Maxfilter
downsample_maxf   = '-ds 4';           % maxfilter downsampling factor (eg 4 to save space)
%downsample_maxf  = '';                % (if none)
format_maxf       = '-format float';   % maxfilter data format (native = float32)
%format_maxf      = '-format short';   % (if to save space)
trans_offset_maxf = [0 -13 +6];        % New centre for trans default
                                       % (see our maxfilter WIKI)

% SPM
downsample_spm    = 100;                % spm new sample rate (Hz; should be at
                                        % least twice filt_cut_spm below)
filt_cut_spm      = 40;                 % Lowpass filter cutoff for SPM (Hz)
dformat_spm       = 'int16';            % data format for spm (eg to save space)
sensor_smooth_spm = [5 5 20];           % Smoothing in SensorSpace-Time [mm mm ms];
source_smooth_spm = [12 12 12];         % Smoothing in Source space [mm mm mm]

%%%%%%%%%%% Initialisation
subsphere = [];
allsssbad = cell(Nsub,1);
nbadchan = cell(Ntyp,Nsub);
nrejects = cell(Ntyp,Nsub);
nevents  = cell(Ntyp,Nsub);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%% Preprocess MEG/EEG data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

for sub = 1:Nsub
 
 subnum    = dosubs(sub);
 Nses(sub) = size(fifdata{subnum},1);

 cd(wd)
 swd = sprintf('sub%d',subnum);
 try cd(swd); catch eval(sprintf('!mkdir %s',swd)); cd(swd); end
  
 for ses = 1:Nses(sub)

   allsssbad{sub} = cell(1,Nses);
   
   fnm_stem = sprintf('sub%d_ses%d',subnum,ses);

   if maxfiltflag

%%%%% Use autobad to detect bad channels from first 20s, and select from output
     rawfile  = fifdata{subnum}{ses};
     sssfile  = sprintf('%s_sss.fif',fnm_stem)
     logfile  = sprintf('%s_autobad.log',fnm_stem)
     headptsfile  = sprintf('%s_headpoints.txt',fnm_stem)

     if exist(sssfile), delete(sssfile), end
     if exist(logfile), delete(logfile), end
     [Centre,Radius]  = meg_fit_sphere(rawfile,pwd,headptsfile);
     disp(sprintf('Subject %d (%d): Session %d: Sphere centre [%d %d %d] and radius %d mm',subnum,sub,ses,Centre(1),Centre(2),Centre(3),Radius))
     subsphere(sub,:) = [Centre Radius];

     disp('Checking first 20s for bad channels...')
     eval(sprintf('!/neuro/bin/util/maxfilter -f %s -o %s -ctc /neuro/databases/ctc/ct_sparse.fif -cal /neuro/databases/sss/sss_cal.dat -frame head -origin %d %d %d -autobad 20 -skip 21 9999999 -v | tee %s',rawfile,sssfile,Centre(1),Centre(2),Centre(3),logfile))
     
     badfile = sprintf('%s_badchan.txt',fnm_stem)
     if exist(badfile), delete(badfile), end
     eval(sprintf('!cat %s | sed -n ''/Static/p'' | cut -f 5- -d '' '' > %s',logfile,badfile));
     sssbadchans{sub}{ses} = unique([textread(badfile,'%d')' badchans{1,subnum,ses}]);
     for bc=1:length(sssbadchans{sub}{ses}); allsssbad{sub}{ses} = [allsssbad{sub}{ses} sprintf(' %04d',sssbadchans{sub}{ses}(bc))]; end

%%%%% Now mark bad channels and run ST 
     logfile = sprintf('%s_ssst.log',fnm_stem)
     if exist(sssfile), delete(sssfile), end    % Don't need previous file from autobad
     sssfile  = sprintf('%s_ssst.fif',fnm_stem)
     if exist(logfile), delete(logfile), end
     posfile = sprintf('%s_mvpos.txt',fnm_stem)

     disp(['Now maxfiltering with bad channels (and tSSS): ' allsssbad{sub}{ses}])
     eval(sprintf('!/neuro/bin/util/maxfilter -f %s -o %s -ctc /neuro/databases/ctc/ct_sparse.fif -cal /neuro/databases/sss/sss_cal.dat -frame head -origin %d %d %d %s -autobad off -bad %s -st 4 -headpos -hpistep 1000 -hpisubt amp -hp %s %s -v | tee %s',rawfile,sssfile,Centre(1),Centre(2),Centre(3),format_maxf,allsssbad{sub}{ses},posfile,downsample_maxf,logfile))

     S.logfile = logfile;
     [max_d(sub),max_r(sub)] = meg_plot_maxfilter_move(S);

     infile = sssfile;
     
%%%%% Now mark bad channels and run MVCOMP
     if maxmvcompflag

      sss2file = sprintf('%s_mvcomp.fif',fnm_stem)
      logfile = sprintf('%s_mvcomp.log',fnm_stem)
      if exist(sss2file), delete(sss2file), end
      if exist(logfile), delete(logfile), end

      disp(['Now compensating movement... (every 200ms)'])
      eval(sprintf('!/neuro/bin/util/maxfilter -f %s -o %s -ctc /neuro/databases/ctc/ct_sparse.fif -cal /neuro/databases/sss/sss_cal.dat -frame head -origin %d %d %d %s -autobad off -bad %s -st 4 -movecomp -hpistep 200 -hpisubt amp %s -v | tee %s',rawfile,sss2file,Centre(1),Centre(2),Centre(3),format_maxf,allsssbad{sub}{ses},downsample_maxf,logfile))

      infile = sss2file;
     end
     
%%%%% Now Trans Default (if requested)
     if maxtransflag
      trans_origin = Centre(1:3) + trans_offset_maxf;
      logfile = sprintf('%s_trans.log',fnm_stem)
      sss3file = sprintf('%s_trans.fif',fnm_stem)
      if exist(sss3file), delete(sss3file), end
      if exist(logfile), delete(logfile), end

      disp(['Now trans-ing to DEFAULT ' num2str(round(trans_origin))])
      eval(sprintf('!/neuro/bin/util/maxfilter -f %s -o %s -ctc /neuro/databases/ctc/ct_sparse.fif -cal /neuro/databases/sss/sss_cal.dat -autobad off -trans default -frame head -origin %d %d %d %s -v -force | tee %s',infile,sss3file,trans_origin(1),trans_origin(2),trans_origin(3),format_maxf,logfile))
     end
    end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% Olaf's channel checking (have not used for a while; should put in SVN!)
    if chancheckflag 
     addpath /imaging/olaf/MEG/artefact_scan_tool/
     global fiffs tasks values criteria sensors datapara figs;
     ini_check4artefacts; % Initialisation of variables
     epochlength = 5;    
     amplitude_threshold_mag = 5000;  
     amplitude_threshold_gra = 10000;         
     out_dir = fullfile(wd,'ChanCheck');
     addfiff(infile,fnm_stem);
     addtask('maxminamp');   % maximum minus minimum amplitude within epoch
     addtask('maxmingrad');  % maximum signal gradient (amplitude difference between successive data points in time) with epoch
     addtask('threshold');   % number of epochs with max-min amplitudes above specified threshold
     addtask('crosscorr');   % intercorrelation matrix for magnetometers and gradiometers separately
     addtask('trendamp');    % linear trend in max-min differences across all epochs
     addtask('trendgrad');   % linear trend in maximum signal gradients across all epochs
     check4artefacts;    % That's where it all happens... lean back and enjoy!
    end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%% Read into SPM (writes separate files for MEG and EEG)

    clear S
    if usemaxtransflag
      S.Fdata = sprintf('%s_trans.fif',fnm_stem);
      if maxmvcompflag
       S.HPIfile = sprintf('%s_mvcomp.fif',fnm_stem);   % If trans'ed (hpi lost)
      else
       S.HPIfile = sprintf('%s_ssst.fif',fnm_stem);      % If trans'ed (hpi lost)
      end
    elseif usemaxmvcompflag
      S.Fdata = sprintf('%s_mvcomp.fif',fnm_stem);
      S.HPIfile = [];
    else
      S.Fdata = sprintf('%s_ssst.fif',fnm_stem);      
      S.HPIfile = [];
    end
    
    % Extra bits for MEG masterclass as maxfiltered files not stored in own working directory.   
    S.Fdata = fullfile(fifd, swd, S.Fdata);
    if ~isempty(S.HPIfile) 
        S.HPIfile = fullfile(fifd, swd, S.HPIfile); 
    end
    [path, name, ext] = fileparts(S.Fdata);
    S.Pout = fullfile(wd, swd, sprintf('%s.mat', name));    % New output location
    % Extra bit ends
    
%    meg_plot_fifpoints(S);                              % If want to check points
    S.Fchannels = 'FIF306_setup.mat';
    S.veogchan  = [62 63]; S.veog_unipolar = 0;
    S.heogchan  = [61 64]; S.heog_unipolar = 0;
    S.trig_chan = 'STI101';
    S.twin      = [0 Inf];
    S.eeg_ref   = 'average';
    S.trig_type = 'positive_from_zero';
%    S.Dtype     = 'float32';                             % make int16 if files too big
    S.Fchannels_eeg = fullfile(spm('dir'),'EEGtemplates', sprintf('cbu_meg_%deeg_montage_old.mat',Nsubchan(sub,find(eegflag)))); % use default montage (which simply explains how to display in 2D), prior to new CBU caps in mid-2008
%    S.Fchannels_eeg =  fullfile(wd,swd,sprintf('eeg_montage_sub%02d.mat',subnum)); % use subject-specific (care labels may not be standard)
    
    if respmflag
      D = spm_eeg_rdata_FIF(S);
      basefile = D.fname(1:(end-4));

%%%%% Downsample, then split Mags and Grads (file too big otherwise)

      clear S; S.D = sprintf('%s-eeg.mat',basefile); disp(S.D)
      S.Radc_new = downsample_spm;
      D = spm_eeg_downsample(S);

      clear S; S.D = basefile;
      S.Radc_new = downsample_spm;
      D = spm_eeg_downsample(S);
      basefile = D.fname(1:(end-4));

      clear S; S.D = D.fname
      D = spm_eeg_splitFIF(S);
    else
      basefile = ['d' S.Fdata(1:(end-4))];
    end
    
%%%%% If want to view rawdata (with Danny's tool):
%     meg_viewdata(D.fname);
     
%%%%% Preprocess each data-type

     for typn = 1:Ntyp
 
       if reprocessflag
	clear S
        S.D = sprintf('%s-%s.mat',basefile,typ{typn}); disp(S.D)
	S.filter.type = 'butterworth';
	S.filter.band = 'low';	S.filter.PHz = filt_cut_spm;
%	S.filter.band = 'stop'; S.filter.PHz = [49 51];
        S.Dtype       = dformat_spm;
	D = spm_eeg_filter(S);

%%%%%% !!!Insert ICA here if want to remove EOG/ECG artifacts!!!
%%%%%% (See Jason Taylor; assume filtered, downsampled data appropriate)
	
	clear S; S.D = D.fname;
 	S.events.start    = expwin(1);
 	S.events.stop     = expwin(2);
 	S.events.types    = expcodes;
 	S.events.Inewlist = 0;
 	S.events.resynch  = offset;
	D = spm_eeg_epochs(S);
	
	% re-classify event-codes
	for e = 1:length(expcodes);
	    fi = find(D.events.code==expcodes(e));
	    if ~isempty(fi)
		D.events.code(fi) = newcodes(e);
	    end
	end
	D.events.types  = unique(D.events.code);
	D.events.Ntypes = length(D.events.types);
	save(D.fname,'D')
	clear S; S.D = D.fname;

      else
        S.D = sprintf('e_fd%s-%s.mat',basefile,typ{typn}); disp(S.D)
	D = spm_eeg_ldata(S.D);
      end
      
%%%%% Threshold channels (eg EOG)

      nc = D.Nchannels;
      S.thresholds.External_list   = 0;
      S.thresholds.Check_Threshold = 1;
      S.thresholds.threshold       = chan_thr{sub,typn};
      S.artefact.weighted          = 0;
      if eegflag(typn)==0
%           S.channels.Bad = unique([D.channels.Bad strcmpi(D.channels.name....sssbadchans{sub}{ses}]);     	% If dont trust MaxFilter channel reconstruction
      else
            S.channels.Bad = unique([D.channels.Bad badchans{2,subnum,ses}]);  
      end
      D = spm_eeg_artefact(S);
      
      nbadchan{typn,sub} = [nbadchan{typn,sub} length(D.channels.Bad)];	
      nrejects{typn,sub} = [nrejects{typn,sub} length(find(D.events.reject))];

%%%%% Re-reference EEG if removed channels
      if eegflag(typn) & ~isempty(D.channels.Bad)
	   D = spm_eeg_ldata(D.fname);
           meg_reavg_ref(D);
	   save(D.fname,'D')
      end
      sesnam{typn,ses} = D.fname;
      
%%%%% Uncomment if want to average and contrast each session separately 
%%%%% (as well as after merging below)
%
%      clear S; S.D = D.fname;
%      D = spm_eeg_average(S);
%
%      clear S; S.D = D.fname;
%      S.c         = expcons;
%      S.WeightAve = 1;
%      D = spm_eeg_weight_epochs(S);
%      nevents{typn,sub} = D.events.repl;
      
    end  % end of typ loop
  end  % end of session loop
    
%%%%% Merge sessions, average, contrast 

  for typn = 1:Ntyp

    if Nses>1
      if ~maxtransflag
        disp(['Concatenating sessions... (NB: merged files will not have correct channel Loc/Orient info unless trans-ed to first or to default!!)']);
      end
      clear S; S.D = strvcat(sesnam{typn,:});
      S.recode = cell(1,Nses);
      D = spm_eeg_merge(S);
      clear S; S.D = D.fname;
    else
      clear S; S.D = sesnam{typn,1};
    end

    D = spm_eeg_average(S);

    clear S; S.D = D.fname;
    S.c = expcons;
    S.WeightAve = 0;
    D = spm_eeg_weight_epochs(S);
    nevents{typn,sub}  = D.events.repl;
    finalnam{typn,sub} = fullfile(D.path,D.fname);
  end

  if any(write2Dflag)
     for typn = find(write2Dflag)
         [pth,nam,ext] = fileparts(finalnam{typn,sub});
         clear S; S.Fname = [nam ext];
	 S.interpolate_bad = 0;
         S.n = 32;
         S.pixsize = 3;
         S.trialtypes = [1:Ncons];
         P = spm_eeg_convertmat2ana3D(S);
	 if any(sensor_smooth_spm)   
	  if length(sensor_smooth_spm)==1; sensor_smooth_spm = ones(1,3)*sensor_smooth_spm; end
	  for con = 1:size(P,1);
	   [pth,nam,ext] = fileparts(P(con,:));
	   Pout          = fullfile(pth,['s' nam ext]);
           spm_smooth(spm_vol(P(con,:)),Pout,sensor_smooth_spm);
	   Pin = strvcat(P(con,:),Pout);
	   spm_imcalc_ui(Pin,Pout,'((i1+eps).*i2)./(i1+eps)',{[],[],'float32',0});   %Reinsert NaNs
 	   SensorTimeImgs{typn}{sub}(con,:) = fullfile(wd,swd,Pout);
	  end
	 else
	  for con = 1:size(P,1);
 	   SensorTimeImgs{typn}{sub}(con,:) = fullfile(wd,swd,P(con,:));
	  end
	 end
     end
  end
end

cd(wd)

for typn = 1:Ntyp
 disp(sprintf('%s...',typ{typn}))
 for sub = 1:Nsub
   subnum = dosubs(sub);
   disp(sprintf('\tSub %d (%d)...',subnum,sub))
   disp(sprintf('\t\tNevents (per condition): %s',mat2str(nevents{typn,sub})))
   disp(sprintf('\t\tRejects (per session): %s',mat2str(nrejects{typn,sub})))
   disp(sprintf('\t\tBadchans (per session): %s',mat2str(nbadchan{typn,sub})))
 end
%%%% Create Grand Mean across subjects
 clear S; S.P = strvcat(finalnam{typn,:});
 S.Pout = sprintf('G%d-%s.mat',Nsub,typ{typn})
 D = spm_eeg_grandmean(S);
end

%return


eval(sprintf('save preproc%d.mat subsphere nrejects nbadchan nevents allsssbad dosubs',length(dosubs)))

disp('!!!NOW USE SPM-Display-M/EEG button to examine results, eg G8-*.mat files !!!')

% Once displaying one of the modalities, you can hold shift and select both 
% conditions 1+2, and click on a posterior right channel to see the M170
% difference between faces (1) and scrambled faces (2). You can also select
% condition 3, which is the differential ERF/ERP between faces and scrambled,
% then press "topography", enter -100ms for initial time, then press and hold
% the time slider to see topography of difference at every time point (displayed
% in Matlab window) - random noise until ~100ms, when strong differences emerge


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%% 2D sensor x 1D Time SPMs 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

stdir = fullfile(wd,'SensorTimeSPMs');
try cd(stdir); catch eval(sprintf('!mkdir %s',stdir)); end

grpsubs{1} = [1:Nsub];
% If want to split subjects, eg into two groups, eg:
% grpsubs{1} = [1:4]; grpsubs{2} = [5:Nsub];

grpcons = [1:2];
Ngrp = length(grpsubs);
for typn = find(write2Dflag)
 outdir = fullfile(stdir,typ{typn})
 for grp = 1:Ngrp
  for sub = 1:length(grpsubs{grp});
   subnum = grpsubs{grp}(sub);
   imgfiles{grp}{sub} = SensorTimeImgs{typn}{subnum}(grpcons,:);
  end
 end
 meg_batch_anova(imgfiles,outdir);
end

disp('!!!NOW press Results button in SPM!!!')

% You need to know a bit about the SPM Results interface, but press the Results 
% button (make sure SPM is in "EEG" mode) (or better still, use the "ns" toolbox
% under "Toolbox" button - see WIKI page below) and select the SPM.mat file for 
% one of the modalities, select the default effects of interest F-contrast
% (because we don't care about polarity, at least for Mags and EEG), choose
% 0.001 uncorrected. Then press "Volume" to get table of stats (ignore brain image). 
% You should see, at least in Mags and EEG, frontal and posterior clusters 
% (simply of different polarity) maximal around 170ms. Not much survives whole-
% image correction because only 8 subjects, so few df's ie low power and RFT 
% conservative) - though effects around 170ms do for corrected extent-level 
% for Mags and EEG (using "ns" toolbox); GRMS results are very poor though. 
% Correction for height would also be significant if you used SVC because
% of an a priori timewindow of interest around 170ms (again see WIKI page below).
%
% For more info on interpreting these SPMs, see
%                   http://imaging.mrc-cbu.cam.ac.uk/meg/SensorSpm
%
% Also, for an example use with EEG data, see Henson et al (2008), Neuroimage.
%
% Note that you can do SVC for a priori timewindows of interest (see end of above WIKI)
% But one use of this SPMs is to define timewindows of interest (in the absence of 
% a priori ones) for the subsequent source localisation below...
%
% (Note that these SPMs can also handle different numbers and locations of channels
% across subjects, provided their locations are digitised in same space, because the 
% data are interpolated to same grid. For MEG data, particularly gradiometers, the
% results benefit from using 'trans -default' above, to realign across different
% headpositions for different subjects - see Smith et al (in press), HBM
% Abstract.