% fixed mobilab version

% close all
% clear all

if ~exist('mobilab','var'); eeglab; runmobilab; end

which runmobilab
which datasource
which datasourceXDF


%% use old mobilab version with my own bugged linspace
%
%
% close all
% clear all
%
% rmpath(genpath('P:\Marius\toolboxes\eeglab14_1_0b\plugins\mobilab'))
%
% addpath(genpath('M:\Toolboxes_Skripts_and_Coding_examples\eeglab-by-marius\eeglab14_1_0b\plugins\mobilab'))
%
% which runmobilab
% which datasource
% which datasourceXDF
%
%
% if ~exist('mobilab','var')
% 	eeglab;
% 	rmpath(genpath('P:\Marius\toolboxes\eeglab14_1_0b\plugins\mobilab'))
% 	addpath(genpath('M:\Toolboxes_Skripts_and_Coding_examples\eeglab-by-marius\eeglab14_1_0b\plugins\mobilab'))
% 	runmobilab;
% end
%
% which runmobilab
% which datasource
% which datasourceXDF

%% load directly

filenames = {'vp_7_walk','U','Z','example_EEG_eyeTracking_rigidBody','test_body','test_joy'};

for i_filename = 1:length(filenames)
	filename = filenames{i_filename};
	
	directly_from_xdf = load_xdf(fullfile(pwd,[filename, '.xdf']));
	
	%% find eeg and marker stream
	
	
	has_eeg = false;
	has_events = false;
	has_mocap = false;
	
	for i_stream = 1:length(directly_from_xdf)
		
		if ( contains(directly_from_xdf{i_stream}.info.name,'brain','IgnoreCase',true) ||...
				contains(directly_from_xdf{i_stream}.info.name,'eeg','IgnoreCase',true) ) &&...
				(~has_eeg && ~ strcmp(directly_from_xdf{i_stream}.info.type, 'Markers'))
			idx_eeg_xdf = i_stream;
			has_eeg = true;
		elseif contains(directly_from_xdf{i_stream}.info.name,'exp','IgnoreCase',true) && ~has_events
			idx_marker_xdf = i_stream;
			has_events = true;
		elseif contains(directly_from_xdf{i_stream}.info.name,'rigid','IgnoreCase',true)  && ~has_mocap
			idx_mocap_xdf = i_stream;
			has_mocap = true;
		end
		
	end
	%%
% 	
% 	for i_stream = 1:length(directly_from_xdf)
% 		switch directly_from_xdf{i_stream}.info.name
% 			case 'BrainVision RDA'
% 				idx_eeg = i_stream
% 			case 'ExpLogger'
% 				idx_marker = i_stream
% 			case 'ExperimentMarkerStream'
% 				idx_marker = i_stream
% 			case 'vizard_hand_rigid'
% 				idx_mocap = i_stream
% 		end
% 	end
	%%
	% In case you want to do it manually
	
	% for example...
	% idx_eeg = 5;
	% idx_marker = 2;
	
	% for U.xdf
	
	% idx_eeg = 2;
	% idx_marker = 3;
	
	% for test_body.xdf
	
	% idx_eeg = 1;
	% idx_marker = 3;
	
	% for test_joy.xdf
	
	% idx_eeg = 2;
	% idx_marker = 4;
	
	%% adjust for the offset, which can't really be evaluated since mobilab cuts it away
	eeg_timestamps_from_xdf = directly_from_xdf{idx_eeg_xdf}.time_stamps * 1000;
	offset = eeg_timestamps_from_xdf(1);
	
	eeg_timestamps_from_xdf = eeg_timestamps_from_xdf - offset;
	
	marker_timestamps_from_xdf = directly_from_xdf{idx_marker_xdf}.time_stamps * 1000;
	marker_timestamps_from_xdf = marker_timestamps_from_xdf - offset;
	
	%% load data into mobilab
	
	disp(['Importing file: ' filename '...']);
	
	input_filepath = fullfile(pwd,[filename '.xdf']);
	
	% this suffix neds to be changed if you redo it
	output_filepath = fullfile(pwd,[filename '_MoBI']);
	
	mobilab.allStreams = dataSourceXDF(input_filepath,output_filepath);
	
	mobilab.refresh
	
	disp('...done.');
	
	%% find eeg, marker, and mocap in mobilab
	% ADJUST ACCORDING TO DATASET!
	
	has_eeg = false;
	has_events = false;
	has_mocap = false;
	
	for i_stream = 1:length(mobilab.allStreams.item)
		
		if ( contains(mobilab.allStreams.item{i_stream}.name,'brain','IgnoreCase',true) ||...
				contains(mobilab.allStreams.item{i_stream}.name,'eeg','IgnoreCase',true) ) && ~has_eeg
			idx_eeg_mobilab = i_stream;
			has_eeg = true;
		elseif contains(mobilab.allStreams.item{i_stream}.name,'ex','IgnoreCase',true) && ~has_events
			idx_marker_mobilab = i_stream;
			has_events = true;
		elseif contains(mobilab.allStreams.item{i_stream}.name,'rigid','IgnoreCase',true)  && ~has_mocap
			idx_mocap_mobilab = i_stream;
			has_mocap = true;
		end
		
	end
	
	%% export to EEGLAB
	
	exported_from_mobilab_EEG_only = mobilab.allStreams().export2eeglab([idx_eeg_mobilab idx_mocap_mobilab],idx_marker_mobilab);
	
	%%
	% if you want to set the streams manually
	
	% for example...
	% exported_from_mobilab_EEG_only = mobilab.allStreams().export2eeglab([1 3],2);
	
	% for U.xdf
	% exported_from_mobilab_EEG_only = mobilab.allStreams().export2eeglab([1 6],3);
	
	% for test_body.xdf
	% exported_from_mobilab_EEG_only = mobilab.allStreams().export2eeglab([1 3],2);
	
	
	%% get the timestamp vector
	
	eeg_timestamps_from_mobilab = exported_from_mobilab_EEG_only.times;
	marker_timestamps_from_mobilab = [exported_from_mobilab_EEG_only.times([exported_from_mobilab_EEG_only.event.latency])];
	
	%% get the differences between the vectors
	
	%
	size(eeg_timestamps_from_xdf);
	size(eeg_timestamps_from_mobilab);
	
	% eeg_timestamps_from_xdf(1:10)
	% eeg_timestamps_from_mobilab(1:10)
	
	size(marker_timestamps_from_xdf);
	size(marker_timestamps_from_mobilab);
	
	% marker_timestamps_from_xdf(1:10)
	% marker_timestamps_from_mobilab(1:10)
	% marker_timestamps_from_xdf(end-10:end)
	% marker_timestamps_from_mobilab(end-10:end)
	
	% make them all the same vector
	marker_timestamps_from_xdf = marker_timestamps_from_xdf(:);
	marker_timestamps_from_mobilab = marker_timestamps_from_mobilab(:);
	eeg_timestamps_from_xdf = eeg_timestamps_from_xdf(:);
	eeg_timestamps_from_mobilab = eeg_timestamps_from_mobilab(:);
	
	% compute differences
	eeg_timestamp_differences = eeg_timestamps_from_xdf(1:length(eeg_timestamps_from_mobilab)) - eeg_timestamps_from_mobilab;
	marker_timestamp_differences = marker_timestamps_from_xdf(1:length(marker_timestamps_from_mobilab)) - marker_timestamps_from_mobilab;
	
	%% plot
	
	figure; subplot(211)
	plot(eeg_timestamp_differences)
% 	title({['EEG timestamp diffs, n=' num2str(length(eeg_timestamp_differences)) ', mean=' num2str(mean(eeg_timestamp_differences))] ...
% 		which('runmobilab')...
% 		filename...
% 		['nominal - effective srate = ' num2str(directly_from_xdf{idx_mocap_xdf}.info.effective_srate - str2num(directly_from_xdf{idx_mocap_xdf}.info.nominal_srate))]})
	ylabel('[ms]')
	ylabel('[ms]')
	xlabel('sample')
	
	subplot(212)
	plot(marker_timestamp_differences)
	title(['event timestamp diffs, n=' num2str(length(marker_timestamp_differences)) ', mean=' num2str(mean(marker_timestamp_differences))])
	ylabel('[ms]')
	xlabel('sample')
	
	%% export using my personalized script
	
	% addpath('P:\Marius\toolboxes\export_fig')
	% export_fig_all([filename '_linspace'])
	
end

%% Save figures Added by RMC

FigHandles = get(0, 'Children');
for i = 1:length(FigHandles)-1
    savefig(FigHandles,['Fig_' num2str(i+1)]);
end
