bidsroot= '/project/3011020.13/bids';
subject = dir(fullfile(bidsroot, 'sub-*'));
subject = {subject.name};

for i=1:numel(subject)
  
  anat = dir(fullfile(bidsroot, subject{i}, 'anat', '*.nii'));
  func = dir(fullfile(bidsroot, subject{i}, 'func', '*.nii'));
  dwi  = dir(fullfile(bidsroot, subject{i}, 'dwi', '*.nii'));
  meg  = dir(fullfile(bidsroot, subject{i}, 'meg', '*.ds'));
  
  catfile = @(p, f) fullfile(p, f);
  
  anat = cellfun(catfile, {anat.folder}, {anat.name}, 'UniformOutput', 0);
  func = cellfun(catfile, {func.folder}, {func.name}, 'UniformOutput', 0);
  dwi  = cellfun(catfile, {dwi.folder},  {dwi.name}, 'UniformOutput', 0);
  meg  = cellfun(catfile, {meg.folder},  {meg.name}, 'UniformOutput', 0);
  
  dataset = cat(1, anat(:), func(:), dwi(:), meg(:));
  
  for j=1:numel(dataset)
    cfg = [];
    cfg.dataset                     = dataset{j};
    
    cfg.mri.writesidecar            = 'merge';
    cfg.meg.writesidecar            = 'replace';
    cfg.channels.writesidecar       = 'replace';
    cfg.events.writesidecar         = 'replace';
    cfg.coordsystem.writesidecar    = 'replace';
    
    cfg.InstitutionName             = 'Radboud University';
    cfg.InstitutionalDepartmentName = 'Donders Institute for Brain, Cognition and Behaviour';
    cfg.InstitutionAddress          = 'Kapittelweg 29, 6525 EN, Nijmegen, The Netherlands';
    
    if contains(cfg.dataset, 'task-rest')
      cfg.TaskName = 'Resting state';
    elseif contains(cfg.dataset, 'task-visual')
      cfg.TaskName = 'Visual language task';
    elseif  contains(cfg.dataset, 'task-auditory')
      cfg.TaskName = 'Auditory language task';
    end
    
    if endsWith(cfg.dataset, '.ds')
      
      if contains(cfg.dataset, 'task-auditory') || contains(cfg.dataset, 'task-visual')
        % this only applies to MEG task data
        pfile = dir(fullfile(bidsroot, 'source', 'meg', [subject{i}(5:end) '*.log']));
        cfg.presentationfile = fullfile(pfile.folder, pfile.name);
        cfg.trigger.eventtype  = 'UPPT001';
        cfg.trigger.eventvalue = 1;
        cfg.presentation.eventtype  = 'Nothing';
        cfg.presentation.eventvalue = '1 Audio onset';
      end
      
      cfg.meg.DigitizedLandmarks      = true;
      cfg.meg.DigitizedHeadPoints     = true;
      cfg.meg.PowerLineFrequency      = 50;
      cfg.meg.DewarPosition           = 'upright';
      cfg.meg.SoftwareFilters         = 'n/a';
      
      % this will be specified on basis of the CTF dataset header
      % cfg.coordsystem.MEGCoordinateSystem
      % cfg.coordsystem.MEGCoordinateUnits
      cfg.coordsystem.MEGCoordinateSystemDescription = 'CTF coordinates relative to the localizer coils, with the localizer coils at nasion and left and right ear canal';
      
      % this will be specified on basis of the CTF dataset header
      % cfg.coordsystem.HeadCoilCoordinates
      % cfg.coordsystem.HeadCoilCoordinateSystem
      % cfg.coordsystem.HeadCoilCoordinateUnits
      cfg.coordsystem.HeadCoilCoordinateSystemDescription = 'CTF coordinates relative to the localizer coils, with the localizer coils at nasion and left and right ear canal';
      cfg.coordsystem.IntendedFor = sprintf('anat/%s_space-CTF_T1w.nii', subject{i});
      
      cfg.coordsystem.DigitizedHeadPoints = sprintf('%s_headshape.pos', subject{i});
      cfg.coordsystem.DigitizedHeadPointsCoordinateSystem = 'CTF';
      cfg.coordsystem.DigitizedHeadPointsCoordinateUnits = 'cm';
      cfg.coordsystem.DigitizedHeadPointsCoordinateSystemDescription = 'CTF coordinates relative to the nasion and left and right pre-auricular points';
      
      % cfg.coordsystem.AnatomicalLandmarkCoordinates
      % cfg.coordsystem.AnatomicalLandmarkCoordinateSystem
      % cfg.coordsystem.AnatomicalLandmarkCoordinateUnits
      % cfg.coordsystem.AnatomicalLandmarkCoordinateSystemDescription
      
      cfg.coordsystem.FiducialsDescription = [ ...
        'Coregistration was initially done using the approximate position of the '...
        'head localizer coils in the anatomical MRI and subsequently refined using the full '...
        'headshape measured with the Polhemus. The positions of the head localizer coils at '...
        'the ear canals (relative to the Polhemus coordinates) is included in the headshape file. '...
        'CTF coordinates in the MEG data and in the coregistered anatomical MRI are specified '...
        'relative to the localizer coils at nasion and left and right ear canal.'...
        ];
      
    elseif endsWith(cfg.dataset, '.nii')
      % this only applies to anatomical MR data
      if contains(cfg.dataset, 'anat')
        cfg.mri.deface = 'yes';
      end
      
      if contains(cfg.dataset, 'space-CTF')
        % these are added by dcm2niix to the original MRI, but differ for the coregistered anatomical MRI
        cfg.mri.ConversionSoftware = 'FieldTrip';
        cfg.mri.ConversionSoftwareVersion = ft_version;
      end
      
      if contains(cfg.dataset, 'task-auditory') || contains(cfg.dataset, 'task-visual')
        % this only applies to fMRI task data
        pfile = dir(fullfile(bidsroot, 'source', 'mri_task', [subject{i}(5:end) '*.log']));
        cfg.presentationfile = fullfile(pfile.folder, pfile.name);
        cfg.presentation.eventtype = 'Pulse';
        cfg.presentation.eventvalue = [];
      end
      
    end % if MEG or MRI
    
    try
      % this fails if the number of triggers is inconsistent with presentatino
      data2bids(cfg)
    end
    
    save_all_figures('/project_ext/3011020.13/bids/code');
    close all % figures
    
  end % for each dataset
end % for each subject
