% Add Brainstorm and SPM12 paths to MATLAB
addpath('C:\brainstorm_git\brainstorm3');
addpath('C:/spm12');
ft_defaults;
spm('eeg');

% Initialize Brainstorm
if ~brainstorm('status')
    brainstorm nogui;
end

bstdb = 'path/to/protocolfolder/....';
bst_set('BrainstormDbDir',bstdb);

% Define the path to SPM12 preprocessed and epoched MEG data


spmDataPath = 'path/to/spmdata/';
% Load the SPM12 MEG data
D = spm_eeg_load(spmDataPath);

% Subject ID
SubID = 'Subject01';

% Check if the subject exists, if not, add a new subject
if isempty(bst_get('Subject', SubID))
    sSubject = db_add_subject(SubID);
else
    sSubject = bst_get('Subject', SubID);
end


[sFile, ChannelMat]=in_fopen_spm_bb(spmDataPath);

% Search for existing study or..
[sStudy,iStudy]=bst_get('Study',[SubID,filesep, SubID,'/brainstormstudy.mat']);

% create a new one
if isempty(iStudy)
iStudy = db_add_condition(sSubject.Name, SubID);
[sStudy,iStudy]=bst_get('Study',[SubID,filesep, SubID,'/brainstormstudy.mat']);
end

% Get the study where the channel file should be saved
sStudy = bst_get('Study', iStudy);

% Define the path for the channel file to be saved
ChannelFilePath = bst_fullfile(bst_get('BrainstormDbDir'),'data',filesep,  fileparts(sStudy.FileName), 'channel_kit.mat');

% Save the channel file
bst_save(ChannelFilePath, ChannelMat, 'v7');
db_add_data(iStudy, ChannelFilePath,ChannelMat);

disp(['Channel file saved: ', ChannelFilePath]);
%% SECOND PART: Import epoched MEG data
addpath('C:/spm12');
spm('eeg');
ft_defaults
% Extract necessary data and information from FieldTrip format
data = D.ftraw(0); % Get data in FieldTrip raw format

% Iterate over each trial
for trialNum = 1:length(data.trial)
    % Prepare the Brainstorm data structure for this trial
    bstData = db_template('data');
    bstData.F = data.trial{trialNum};

    bstData.ChannelFlag = channelFlags; % Use channel flags prepared earlier
    bstData.Time = data.time{trialNum};
    bstData.Freqs = [];
    bstData.DataType = 'recordings';
    bstData.Device = 'MEG';
    bstData.Comment = ['Trial ', num2str(trialNum), ' Imported from SPM12'];

    % Generate a unique filename for this trial
    dataFileName = bst_fullfile(bst_get('BrainstormDbDir'),'data',filesep, fileparts(sStudy.FileName), ['data_trial', sprintf('%02d', trialNum), '.mat']);
    bstData.FileName=dataFileName;

    % Use bst_save to save the data
    bst_save(dataFileName, bstData, 'v7');
    % Add the data to the database
    newDataFile = db_add_data(iStudy, bstData.FileName,bstData);

    disp(['Data imported to Brainstorm: ', newDataFile.FileName]);
end
