function varargout = DEM_demo(varargin)
% DEM_DEMO M-file for DEM_demo.fig
%      DEM_DEMO, by itself, creates a new DEM_DEMO or raises the existing
%      singleton*.
%
%      H = DEM_DEMO returns the handle to a new DEM_DEMO or the handle to
%      the existing singleton*.
%
%      DEM_DEMO('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in DEM_DEMO.M with the given input arguments.
%
%      DEM_DEMO('Property','Value',...) creates a new DEM_DEMO or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before DEM_demo_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to DEM_demo_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help DEM_demo

% Last Modified by GUIDE v2.5 02-Jan-2020 19:35:25

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @DEM_demo_OpeningFcn, ...
                   'gui_OutputFcn',  @DEM_demo_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before DEM_demo is made visible.
function DEM_demo_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to DEM_demo (see VARARGIN)

% Choose default command line output for DEM_demo
handles.output = hObject;

% default paper
handles.web    = 'The free-energy principle A unified brain theory';

% Display PDF image
axes5_CreateFcn(hObject, eventdata, handles);

% Update handles structure
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function axes5_CreateFcn(hObject, eventdata, handles)
ax = handles.axes5;
imagesc(imread('PDF.jpg'),'Parent',ax), axis(ax,'off');

% --- Outputs from this function are returned to the command line.
function varargout = DEM_demo_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

function run_demo_Callback(hObject, handles, file)
if isdeployed
    h = sprintf('%s: MATLAB code and help are not available in SPM Standalone.',file);
else
    h  = help(file);
end
str{1} = [file ':'];
str{2} = '__________________________________________________________________________ ';
str{3} = ' ';
str{4} = h;
set(handles.help,'String',str);
handles.file = file;
guidata(hObject, handles);

% --- Executes on button press in pushbutton131.
function pushbutton131_Callback(hObject, eventdata, handles)
try,
    url = strcat('http://www.fil.ion.ucl.ac.uk/~karl/',handles.web);
    web(url,'-browser','-notoolbar');
end

% --- Executes on button press in pushbutton51.
function pushbutton51_Callback(hObject, eventdata, handles)

set(handles.pushbutton51,'String','please wait')
drawnow
try
    guidata(1,handles);
catch
    spm_figure('GetWin','DEM');
    guidata(1,handles);
end
eval(handles.file)
handles = set(0,'UserData');
handles = guidata(1);
set(handles.pushbutton51,'String','run demo')

% --- Executes on button press in pushbutton93.
function pushbutton93_Callback(hObject, eventdata, handles)
try
    if isdeployed
        set(hObject,'String','MATLAB code (not available)');
        set(hObject,'Enable','Off');
    else
        edit(handles.file);
    end
end

% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
handles.web = 'Variational free energy and the Laplace approximation';
run_demo_Callback(hObject, handles, 'DEM_demo_GLM')

% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
handles.web = 'Variational free energy and the Laplace approximation';
run_demo_Callback(hObject, handles, 'DEM_demo_PEB')

% --- Executes on button press in pushbutton4.
function pushbutton4_Callback(hObject, eventdata, handles)
handles.web = 'Hierarchical Models in the Brain';
run_demo_Callback(hObject, handles, 'DEM_demo_factor_analysis')

% --- Executes on button press in pushbutton5.
function pushbutton5_Callback(hObject, eventdata, handles)
handles.web = 'DEM A variational treatment of dynamic systems';
run_demo_Callback(hObject, handles, 'DEM_demo_OU')

% --- Executes on button press in pushbutton6.
function pushbutton6_Callback(hObject, eventdata, handles)
handles.web = 'Hierarchical Models in the Brain';
run_demo_Callback(hObject, handles, 'DEM_demo_convolution')

% --- Executes on button press in pushbutton7.
function pushbutton7_Callback(hObject, eventdata, handles)
handles.web = 'DEM A variational treatment of dynamic systems';
run_demo_Callback(hObject, handles, 'DEM_demo_EM')

% --- Executes on button press in pushbutton8.
function pushbutton8_Callback(hObject, eventdata, handles)
handles.web = 'DEM A variational treatment of dynamic systems';
run_demo_Callback(hObject, handles, 'DEM_demo_DEM')

% --- Executes on button press in pushbutton9.
function pushbutton9_Callback(hObject, eventdata, handles)
handles.web = 'DEM A variational treatment of dynamic systems';
run_demo_Callback(hObject, handles, 'DEM_demo_filtering')

% --- Executes on button press in pushbutton10.
function pushbutton10_Callback(hObject, eventdata, handles)
handles.web = 'DEM A variational treatment of dynamic systems';
run_demo_Callback(hObject, handles, 'DEM_demo_Lorenz')

% --- Executes on button press in pushbutton11.
function pushbutton11_Callback(hObject, eventdata, handles)
handles.web = 'Dynamic causal modelling';
run_demo_Callback(hObject, handles, 'DEM_demo_hdm')

% --- Executes on button press in pushbutton12.
function pushbutton12_Callback(hObject, eventdata, handles)
handles.web = 'DEM A variational treatment of dynamic systems';
run_demo_Callback(hObject, handles, 'DEM_demo_double_well')

% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
handles.web = 'Variational filtering';
run_demo_Callback(hObject, handles, 'DEM_demo_DFP')

% --- Executes on button press in pushbutton14.
function pushbutton14_Callback(hObject, eventdata, handles)
handles.web = 'Variational filtering';
run_demo_Callback(hObject, handles, 'DFP_demo_double_well')

% --- Executes on button press in pushbutton15.
function pushbutton15_Callback(hObject, eventdata, handles)
handles.web = 'Cortical circuits for perceptual inference';
run_demo_Callback(hObject, handles, 'DEM_demo_song_priors')

% --- Executes on button press in pushbutton37.
function pushbutton37_Callback(hObject, eventdata, handles)
handles.web = 'Predictive coding under the free-energy principle';
run_demo_Callback(hObject, handles, 'DEM_demo_song_inference')

% --- Executes on button press in pushbutton38.
function pushbutton38_Callback(hObject, eventdata, handles)
handles.web = 'Cortical circuits for perceptual inference';
run_demo_Callback(hObject, handles, 'DEM_demo_song_omission')

% --- Executes on button press in pushbutton40.
function pushbutton40_Callback(hObject, eventdata, handles)
handles.web = 'Learning and inference in the brain';
run_demo_Callback(hObject, handles, 'DEM_demo_face_inference')

% --- Executes on button press in pushbutton41.
function pushbutton41_Callback(hObject, eventdata, handles)
handles.web = 'Attractors in song';
run_demo_Callback(hObject, handles, 'DEM_demo_MMN')

% --- Executes on button press in pushbutton42.
function pushbutton42_Callback(hObject, eventdata, handles)
handles.web = '';
run_demo_Callback(hObject, handles, 'DEM_demo_Gabor')

% --- Executes on button press in pushbutton44.
function pushbutton44_Callback(hObject, eventdata, handles)
handles.web = 'Action and behavior A free-energy formulation';
run_demo_Callback(hObject, handles, 'ADEM_visual')

% --- Executes on button press in pushbutton45.
function pushbutton45_Callback(hObject, eventdata, handles)
handles.web = 'Action and behavior A free-energy formulation';
run_demo_Callback(hObject, handles, 'ADEM_motor')

% --- Executes on button press in pushbutton46.
function pushbutton46_Callback(hObject, eventdata, handles)
handles.web = 'Reinforcement Learning or Active Inference';
run_demo_Callback(hObject, handles, 'ADEM_learning')

% --- Executes on button press in pushbutton47.
function pushbutton47_Callback(hObject, eventdata, handles)
handles.web = 'Action and behavior A free-energy formulation';
run_demo_Callback(hObject, handles, 'ADEM_lorenz')

% --- Executes on button press in pushbutton48.
function pushbutton48_Callback(hObject, eventdata, handles)
handles.web = 'Action and behavior A free-energy formulation';
run_demo_Callback(hObject, handles, 'ADEM_reaching')

% --- Executes on button press in pushbutton49.
function pushbutton49_Callback(hObject, eventdata, handles)
handles.web = 'Free Energy Value and Attractors';
run_demo_Callback(hObject, handles, 'ADEM_lorenz_entropy')

% --- Executes on button press in pushbutton50.
function pushbutton50_Callback(hObject, eventdata, handles)
handles.web = 'Free Energy Value and Attractors';
run_demo_Callback(hObject, handles, 'ADEM_mountaincar_loss')

% --- Executes on button press in pushbutton80.
function pushbutton80_Callback(hObject, eventdata, handles)
handles.web = 'Policies and Priors';
run_demo_Callback(hObject, handles, 'ADEM_SHC_demo')

% --- Executes on button press in pushbutton81.
function pushbutton81_Callback(hObject, eventdata, handles)
handles.web = 'Free Energy Value and Attractors';
run_demo_Callback(hObject, handles, 'ADEM_lorenz_surprise')

% --- Executes on button press in pushbutton83.
function pushbutton83_Callback(hObject, eventdata, handles)
handles.web = 'Generalised Filtering';
run_demo_Callback(hObject, handles, 'DEM_demo_LAP')

% --- Executes on button press in pushbutton84.
function pushbutton84_Callback(hObject, eventdata, handles)
handles.web = 'Generalised Filtering';
run_demo_Callback(hObject, handles, 'DEM_demo_hdm_LAP')

% --- Executes on button press in pushbutton91.
function pushbutton91_Callback(hObject, eventdata, handles)
handles.web = 'Attention uncertainty and free-energy';
run_demo_Callback(hObject, handles, 'DEM_demo_Posner')

% --- Executes on button press in pushbutton92.
function pushbutton92_Callback(hObject, eventdata, handles)
handles.web = 'Policies and Priors';
run_demo_Callback(hObject, handles, 'ADEM_cost_SHC')

% --- Executes on button press in pushbutton94.
function pushbutton94_Callback(hObject, eventdata, handles)
handles.web = '';
run_demo_Callback(hObject, handles, '%%%% DEM_demo_CM_Lorenz %%%')

% --- Executes on button press in pushbutton96.
function pushbutton96_Callback(hObject, eventdata, handles)
handles.web = 'Action understanding and active inference';
run_demo_Callback(hObject, handles, 'ADEM_observe')

% --- Executes on button press in pushbutton97.
function pushbutton97_Callback(hObject, eventdata, handles)
handles.web = 'Network discovery with DCM';
run_demo_Callback(hObject, handles, 'DEM_demo_DCM_LAP')

% --- Executes on button press in pushbutton98.
function pushbutton98_Callback(hObject, eventdata, handles)
handles.web = 'Dynamic modeling of neuronal responses in fMRI using cubature Kalman filtering';
run_demo_Callback(hObject, handles, 'DEM_demo_convolution_LAP')

% --- Executes on button press in pushbutton99.
function pushbutton99_Callback(hObject, eventdata, handles)
handles.web = 'Dynamic modeling of neuronal responses in fMRI using cubature Kalman filtering';
run_demo_Callback(hObject, handles, 'DEM_demo_lorenz_LAP')

% --- Executes on button press in pushbutton100.
function pushbutton100_Callback(hObject, eventdata, handles)
handles.web = 'Dynamic modeling of neuronal responses in fMRI using cubature Kalman filtering';
run_demo_Callback(hObject, handles, 'DEM_demo_doublewell_LAP')

% --- Executes on button press in pushbutton101.
function pushbutton101_Callback(hObject, eventdata, handles)
handles.web = 'Dynamic modeling of neuronal responses in fMRI using cubature Kalman filtering';
run_demo_Callback(hObject, handles, 'DEM_demo_hdm_SCK')

% --- Executes on button press in pushbutton102.
function pushbutton102_Callback(hObject, eventdata, handles)
handles.web = 'Action understanding and active inference';
run_demo_Callback(hObject, handles, 'ADEM_writing')

% --- Executes on button press in pushbutton103.
function pushbutton103_Callback(hObject, eventdata, handles)
handles.web = 'Free energy and dendritic self-organization';
run_demo_Callback(hObject, handles, 'DEM_demo_dendrite')

% --- Executes on button press in pushbutton104.
function pushbutton104_Callback(hObject, eventdata, handles)
handles.web = 'Free-energy and illusions the Cornsweet effect';
run_demo_Callback(hObject, handles, 'DEM_demo_Cornsweet')

% --- Executes on button press in pushbutton105.
function pushbutton105_Callback(hObject, eventdata, handles)
handles.web = 'Smooth Pursuit and Visual Occlusion';
run_demo_Callback(hObject, handles, 'ADEM_pursuit')

% --- Executes on button press in pushbutton117.
function pushbutton117_Callback(hObject, eventdata, handles)
handles.web = 'Dopamine Affordance and Active Inference';
run_demo_Callback(hObject, handles, 'ADEM_cued_response')

% --- Executes on button press in pushbutton118.
function pushbutton118_Callback(hObject, eventdata, handles)
handles.web = 'Attractors in song';
run_demo_Callback(hObject, handles, 'DEM_demo_MMN_deviance')

% --- Executes on button press in pushbutton119.
function pushbutton119_Callback(hObject, eventdata, handles)
handles.web = 'Bayesian State Estimation Using Generalized Coordinates';
run_demo_Callback(hObject, handles, 'DEM_demo_contact_lens')

% --- Executes on button press in pushbutton120.
function pushbutton120_Callback(hObject, eventdata, handles)
handles.web = 'Bayesian State Estimation Using Generalized Coordinates';
run_demo_Callback(hObject, handles, 'DEM_demo_GF_and_KF')

% --- Executes on button press in pushbutton121.
function pushbutton121_Callback(hObject, eventdata, handles)
handles.web = 'Active inference and agency optimal control without cost functions';
run_demo_Callback(hObject, handles, 'spm_MDP_mountain_car')

% --- Executes on button press in pushbutton122.
function pushbutton122_Callback(hObject, eventdata, handles)
handles.web = 'Perceptions as hypotheses saccades as experiments';
run_demo_Callback(hObject, handles, 'ADEM_salience')

% --- Executes on button press in pushbutton123.
function pushbutton123_Callback(hObject, eventdata, handles)
handles.web = 'Perception and self-organized instability';
run_demo_Callback(hObject, handles, 'DEM_demo_SOC')

% --- Executes on button press in pushbutton124.
function pushbutton124_Callback(hObject, eventdata, handles)
handles.web = 'Active inference, eye movements and oculomotor delays';
run_demo_Callback(hObject, handles, 'ADEM_occulomotor_delays')

% --- Executes on button press in pushbutton125.
function pushbutton125_Callback(hObject, eventdata, handles)
handles.web = 'Smooth Pursuit and Visual Occlusion';
run_demo_Callback(hObject, handles, 'ADEM_occlusion')

% --- Executes on button press in pushbutton126.
function pushbutton126_Callback(hObject, eventdata, handles)
handles.web = 'Generalised Filtering';
run_demo_Callback(hObject, handles, 'DEM_demo_ALAP')

% --- Executes on button press in pushbutton127.
function pushbutton127_Callback(hObject, eventdata, handles)
handles.web = 'Active inference sensory attenuation and illusions';
run_demo_Callback(hObject, handles, 'ALAP_demo_attenuation')

% --- Executes on button press in pushbutton128.
function pushbutton128_Callback(hObject, eventdata, handles)
handles.web = 'Observing the Observer I';
run_demo_Callback(hObject, handles, 'spm_meta_model')

% --- Executes on button press in pushbutton129.
function pushbutton129_Callback(hObject, eventdata, handles)
handles.web = 'Predictive Coding or Evidence Accumulation';
run_demo_Callback(hObject, handles, 'DEM_evidence_accumulation')

% --- Executes on button press in pushbutton130.
function pushbutton130_Callback(hObject, eventdata, handles)
handles.web = 'The anatomy of choice active inference and agency';
run_demo_Callback(hObject, handles, 'spm_MDP_offer')

% --- Executes on button press in pushbutton132.
function pushbutton132_Callback(hObject, eventdata, handles)
handles.web = 'Life as we know it';
run_demo_Callback(hObject, handles, 'FEP_Manifold')

% --- Executes on button press in pushbutton133.
function pushbutton133_Callback(hObject, eventdata, handles)
handles.web = 'The anatomy of choice active inference and agency';
run_demo_Callback(hObject, handles, 'spm_MDP_trust')

% --- Executes on button press in pushbutton134.
function pushbutton134_Callback(hObject, eventdata, handles)
handles.web = 'A DCM for resting state fMRI';
run_demo_Callback(hObject, handles, 'DEM_demo_induced_fMRI')

% --- Executes on button press in pushbutton142.
function pushbutton142_Callback(hObject, eventdata, handles)
handles.web = 'Active Inference, Evidence Accumulation, and the Urn Task';
run_demo_Callback(hObject, handles, 'spm_MDP_urn')

% --- Executes on button press in pushbutton143.
function pushbutton143_Callback(hObject, eventdata, handles)
handles.web = 'Network discovery with large DCMs';
run_demo_Callback(hObject, handles, 'DEM_demo_large_fMRI')

% --- Executes on button press in pushbutton144.
function pushbutton144_Callback(hObject, eventdata, handles)
handles.web = 'On nodes and modes in resting state fMRI';
run_demo_Callback(hObject, handles, 'DEM_demo_connectivity_fMRI')

% --- Executes on button press in pushbutton145.
function pushbutton145_Callback(hObject, eventdata, handles)
handles.web = 'On nodes and modes in resting state fMRI';
run_demo_Callback(hObject, handles, 'DEM_demo_modes_fMRI')

% --- Executes on button press in pushbutton146.
function pushbutton146_Callback(hObject, eventdata, handles)
handles.web = 'Dynamic modeling of neuronal responses in fMRI using cubature Kalman filtering';
run_demo_Callback(hObject, handles, 'DEM_demo_hdm_SCK')

% --- Executes on button press in pushbutton147.
function pushbutton147_Callback(hObject, eventdata, handles)
handles.web = 'Generalised Filtering';
run_demo_Callback(hObject, handles, 'DEM_demo_convolution_LAP')

% --- Executes on button press in pushbutton148.
function pushbutton148_Callback(hObject, eventdata, handles)
handles.web = 'Dynamic modeling of neuronal responses in fMRI using cubature Kalman filtering';
run_demo_Callback(hObject, handles, 'DEM_demo_lorenz_LAP')

% --- Executes on button press in pushbutton149.
function pushbutton149_Callback(hObject, eventdata, handles)
handles.web = 'Dynamic modeling of neuronal responses in fMRI using cubature Kalman filtering';
run_demo_Callback(hObject, handles, 'DEM_demo_doublewell_LAP')

% --- Executes on button press in pushbutton150.
function pushbutton150_Callback(hObject, eventdata, handles)
handles.web = 'Cerebral Hierarchies, predictive processing, precision and the pulvinar';
run_demo_Callback(hObject, handles, 'DEM_demo_texture')

% --- Executes on button press in pushbutton151.
function pushbutton151_Callback(hObject, eventdata, handles)
handles.web = 'A Duet for one';
run_demo_Callback(hObject, handles, 'DEM_demo_duet')

% --- Executes on button press in pushbutton152.
function pushbutton152_Callback(hObject, eventdata, handles)
% --- Executes on button press in pushbutton133.
handles.web = 'Active inference and epistemic value';
run_demo_Callback(hObject, handles, 'DEM_demo_MDP_maze')

% --- Executes on button press in pushbutton153.
function pushbutton153_Callback(hObject, eventdata, handles)
handles.web = 'Post hoc Bayesian model selection';
run_demo_Callback(hObject, handles, 'DEM_demo_Bayesian_Model_Reduction')

% --- Executes on button press in pushbutton154.
function pushbutton154_Callback(hObject, eventdata, handles)
handles.web = 'Knowing ones place';
run_demo_Callback(hObject, handles, 'DEM_morphogenesis')

% --- Executes on button press in pushbutton155.
function pushbutton155_Callback(hObject, eventdata, handles)
handles.web = 'Active Inference and Learning in the Cerebellum';
run_demo_Callback(hObject, handles, 'ADEM_eyeblink')

% --- Executes on button press in pushbutton156.
function pushbutton156_Callback(hObject, eventdata, handles)
handles.web = 'Post hoc Bayesian model selection';
run_demo_Callback(hObject, handles, 'DEMO_SLR')

% --- Executes on button press in pushbutton157.
function pushbutton157_Callback(hObject, eventdata, handles)
handles.web = 'Post hoc Bayesian model selection';
run_demo_Callback(hObject, handles, 'DEMO_BMR_PEB')

% --- Executes on button press in pushbutton158.
function pushbutton158_Callback(hObject, eventdata, handles)
handles.web = 'Bayesian model reduction and empirical Bayes for group (DCM) studies';
run_demo_Callback(hObject, handles, 'DEMO_GROUP_PEB')

% --- Executes on button press in pushbutton159.
function pushbutton159_Callback(hObject, eventdata, handles)
handles.web = 'Anatomically informed basis functions';
run_demo_Callback(hObject, handles, 'DEM_spatial_deconvolution')

% --- Executes on button press in pushbutton160.
function pushbutton160_Callback(hObject, eventdata, handles)
handles.web = 'Computational Nosology';
run_demo_Callback(hObject, handles, 'DEM_demo_ontology')

% --- Executes on button press in pushbutton161.
function pushbutton161_Callback(hObject, eventdata, handles)
handles.web = 'Active inference and learning';
run_demo_Callback(hObject, handles, 'DEM_demo_MDP_habits')

% --- Executes on button press in pushbutton162.
function pushbutton162_Callback(hObject, eventdata, handles)
handles.web = 'Computational Phenotyping in Psychiatry';
run_demo_Callback(hObject, handles, 'DEM_demo_MDP_fit')

% --- Executes on button press in pushbutton163.
function pushbutton163_Callback(hObject, eventdata, handles)
handles.web = 'Active Inference A Process Theory';
run_demo_Callback(hObject, handles, 'DEM_demo_MDP_X')

% --- Executes on button press in pushbutton168.
function pushbutton168_Callback(hObject, eventdata, handles)
handles.web = 'Scene Construction,Visual Foraging and Active Inference';
run_demo_Callback(hObject, handles, 'DEM_demo_MDP_search')

% --- Executes on button press in pushbutton169.
function pushbutton169_Callback(hObject, eventdata, handles)
handles.web = 'Deep temporal models and active inference';
run_demo_Callback(hObject, handles, 'DEM_demo_MDP_reading')

% --- Executes on button press in pushbutton170.
function pushbutton170_Callback(hObject, eventdata, handles)
handles.web = 'Active Inference Curiosity and Insight';
run_demo_Callback(hObject, handles, 'DEM_demo_MDP_rule')

% --- Executes on button press in pushbutton197.
function pushbutton197_Callback(hObject, eventdata, handles)
handles.web = 'Empirical Bayes for DCM A Group Inversion Scheme';
run_demo_Callback(hObject, handles, 'DEMO_BMR_PEB')

% --- Executes on button press in pushbutton198.
function pushbutton198_Callback(hObject, eventdata, handles)
handles.web = 'Empirical Bayes for DCM A Group Inversion Scheme';
run_demo_Callback(hObject, handles, 'DEMO_GROUP_PEB')

% --- Executes on button press in pushbutton199.
function pushbutton199_Callback(hObject, eventdata, handles)
handles.web = 'Bayesian model reduction and empirical Bayes for group (DCM) studies';
run_demo_Callback(hObject, handles, 'DEMO_DCM_PEB')

% --- Executes on button press in pushbutton200.
function pushbutton200_Callback(hObject, eventdata, handles)
handles.web = 'Bayesian model reduction and empirical Bayes for group (DCM) studies';
run_demo_Callback(hObject, handles, 'DEMO_DCM_PEB_FIT')

% --- Executes on button press in pushbutton201.
function pushbutton201_Callback(hObject, eventdata, handles)
handles.web = 'Comparing dynamic causal models';
run_demo_Callback(hObject, handles, 'DEMO_BAYES_FACTORS')

% --- Executes on button press in pushbutton202.
function pushbutton202_Callback(hObject, eventdata, handles)
handles.web = '';
run_demo_Callback(hObject, handles, 'DEMO_Lindley_paradox')

% --- Executes on button press in pushbutton203.
function pushbutton203_Callback(hObject, eventdata, handles)
handles.web = 'Bayesian model selection for group studies';
run_demo_Callback(hObject, handles, 'DEMO_BMR_PEB')

% --- Executes on button press in pushbutton210.
function pushbutton210_Callback(hObject, eventdata, handles)
handles.web = 'Bayesian model reduction and empirical Bayes for group (DCM) studies';
run_demo_Callback(hObject, handles, 'DEM_demo_fMRI_PEB')

% --- Executes on button press in pushbutton211.
function pushbutton211_Callback(hObject, eventdata, handles)
handles.web = 'Active inference and epistemic value';
run_demo_Callback(hObject, handles, 'DEM_MDP_decision')

% --- Executes on button press in pushbutton212.
function pushbutton212_Callback(hObject, eventdata, handles)
handles.web = 'The graphical brain';
run_demo_Callback(hObject, handles, 'DEM_demo_MDP_DEM')

% --- Executes on button press in pushbutton213.
function pushbutton213_Callback(hObject, eventdata, handles)
handles.web = 'Computational Phenotyping in Psychiatry';
run_demo_Callback(hObject, handles, 'DEM_demo_MDP_fit_fields')

% --- Executes on button press in pushbutton214.
function pushbutton214_Callback(hObject, eventdata, handles)
handles.web = 'Planning and navigation as active inference';
run_demo_Callback(hObject, handles, 'DEMO_MDP_maze')

% --- Executes on button press in pushbutton215.
function pushbutton215_Callback(hObject, eventdata, handles)
handles.web = 'Life as we know it';
run_demo_Callback(hObject, handles, 'FEP_fluctuations')

% --- Executes on button press in pushbutton216.
function pushbutton216_Callback(hObject, eventdata, handles)
handles.web = 'Life as we know it';
run_demo_Callback(hObject, handles, 'FEP_MB_demo')

% --- Executes on button press in pushbutton217.
function pushbutton217_Callback(hObject, eventdata, handles)
handles.web = 'Knowing ones place';
run_demo_Callback(hObject, handles, 'DEM_cells_cells')

% --- Executes on button press in pushbutton218.
function pushbutton218_Callback(hObject, eventdata, handles)
handles.web = 'Knowing ones place';
run_demo_Callback(hObject, handles, 'DEM_cells')

% --- Executes on button press in pushbutton219.
function pushbutton219_Callback(hObject, eventdata, handles)
handles.web = 'Life as we know it';
run_demo_Callback(hObject, handles, 'DEM_self_entropy')

% --- Executes on button press in pushbutton223.
function pushbutton223_Callback(hObject, eventdata, handles)
handles.web = 'Life as we know it';
run_demo_Callback(hObject, handles, 'FEP_self_entropy')

% --- Executes on button press in pushbutton221.
function pushbutton221_Callback(hObject, eventdata, handles)
handles.web = 'Life as we know it';
run_demo_Callback(hObject, handles, 'DEM_HB_and_LE')

% --- Executes on button press in pushbutton222.
function pushbutton222_Callback(hObject, eventdata, handles)
handles.web = 'Life as we know it';
run_demo_Callback(hObject, handles, 'FEP_physics')

% --- Executes on button press in pushbutton224.
function pushbutton224_Callback(hObject, eventdata, handles)
handles.web = 'Post hoc Bayesian model selection';
run_demo_Callback(hObject, handles, 'DEMO_AI_NLSI')

% --- Executes on button press in pushbutton225.
function pushbutton225_Callback(hObject, eventdata, handles)
handles.web = 'Active inference and the anatomy of oculomotion';
run_demo_Callback(hObject, handles, 'MDP_DEM_Oculomotion_demo')

% --- Executes on button press in pushbutton226.
function pushbutton226_Callback(hObject, eventdata, handles)
handles.web = 'Deep temporal models and active inference';
run_demo_Callback(hObject, handles, 'DEMO_MDP_questions')

% --- Executes on button press in pushbutton227.
function pushbutton227_Callback(hObject, eventdata, handles)
handles.web = 'A Multivariate Analysis of PET Activation Studies';
run_demo_Callback(hObject, handles, 'DEMO_CVA_RSA')

% --- Executes on button press in pushbutton228.
function pushbutton228_Callback(hObject, eventdata, handles)
handles.web = 'Planning and navigation as active inference';
run_demo_Callback(hObject, handles, 'DEMO_niche_construction')

% --- Executes on button press in pushbutton229.
function pushbutton229_Callback(hObject, eventdata, handles)
handles.web = 'Generalised Filtering';
run_demo_Callback(hObject, handles, 'DEM_coupled_oscillators')

% --- Executes on button press in pushbutton230.
function pushbutton230_Callback(hObject, eventdata, handles)
handles.web = 'Generalised Filtering';
run_demo_Callback(hObject, handles, 'KLDemo')

% --- Executes on button press in pushbutton231.
function pushbutton231_Callback(hObject, eventdata, handles)
handles.web = 'Life as we know it';
run_demo_Callback(hObject, handles, 'DEM_FEP_Lorenz')

% --- Executes on button press in pushbutton232.
function pushbutton232_Callback(hObject, eventdata, handles)
handles.web = 'Life as we know it';
run_demo_Callback(hObject, handles, 'DEM_FEP_Least_Action')

% --- Executes on button press in pushbutton233.
function pushbutton233_Callback(hObject, eventdata, handles)
handles.web = 'Deep temporal models and active inference';
run_demo_Callback(hObject, handles, 'spm_voice')

% --- Executes on button press in pushbutton234.
function pushbutton234_Callback(hObject, eventdata, handles)
handles.web = 'Interoceptive inference';
run_demo_Callback(hObject, handles, 'MDP_Heart_Beat')

% --- Executes on button press in pushbutton239.
function pushbutton239_Callback(hObject, eventdata, handles)
handles.web = 'Deep temporal models and active inference';
run_demo_Callback(hObject, handles, 'spm_voice')

% --- Executes on button press in pushbutton240.
function pushbutton240_Callback(hObject, eventdata, handles)
handles.web = 'Deep temporal models and active inference';
run_demo_Callback(hObject, handles, 'spm_voice_P300')

% --- Executes on button press in pushbutton241.
function pushbutton241_Callback(hObject, eventdata, handles)
handles.web = 'Deep temporal models and active inference';
run_demo_Callback(hObject, handles, 'spm_voice_repeat')

% --- Executes on button press in pushbutton242.
function pushbutton242_Callback(hObject, eventdata, handles)
handles.web = 'Deep temporal models and active inference';
run_demo_Callback(hObject, handles, 'spm_voice_read')

% --- Executes on button press in pushbutton243.
function pushbutton243_Callback(hObject, eventdata, handles)
handles.web = 'Deep temporal models and active inference';
run_demo_Callback(hObject, handles, 'DEMO_MDP_voice')

% --- Executes on button press in pushbutton244.
function pushbutton244_Callback(hObject, eventdata, handles)
handles.web = 'Deep temporal models and active inference';
run_demo_Callback(hObject, handles, 'MDP_DEM_Mixed_Models_Movement')

% --- Executes on button press in pushbutton245.
function pushbutton245_Callback(hObject, eventdata, handles)
handles.web = 'A free energy principle for a particular physics';
run_demo_Callback(hObject, handles, 'DEMO_DCM_MB')

% --- Executes on button press in pushbutton247.
function pushbutton247_Callback(hObject, eventdata, handles)
handles.web = 'Active Inference A Process Theory';
run_demo_Callback(hObject, handles, 'DEM_demo_MDP_XX')

% --- Executes on button press in pushbutton248.
function pushbutton248_Callback(hObject, eventdata, handles)
handles.web = 'Planning and navigation as active inference';
run_demo_Callback(hObject, handles, 'DEMO_MDP_maze_X')


function make_animation ( frame_total )

%*****************************************************************************80
%
%% MAKE_ANIMATION creates an AVI animation file from a sequence of frame files.
%
%  Discussion:
%
%    Before running this program close all figures and don't interfere
%    with the generated figures until the recording process is done.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    20 November 2010
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'MAKE_ANIMATION\n' );
  fprintf ( 1, '  Create an AVI animation from a sequence of frame files.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Here we assume a sequence of frame files was created by\n' )
  fprintf ( 1, '  the MAKE_FRAMES program already.\n' );
%
%  Make sure we have the number of frames.
%
  if ( nargin < 1 )
    fprintf ( 1, '\n' );
    frame_total = input ( 'Enter the number of frames to view:  ' );
  end
%
%  Set the total number of frames that we will generate.
%
  numframes = frame_total + 1;
%
%  Control how fast final movie will play; total time
%  of movie in seconds will be about (numframes)/(num_frames_per_second)
%
  fps = 10;
  seconds = numframes / fps;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  This movie will contain %d frames.\n', numframes );
  fprintf ( 1, '  The number of frames per second will be %f\n', fps );
  fprintf ( 1, '  so the movie should take %f seconds to play.\n', seconds );
%
%  The AVIFILE function creates a new Audio Video Interleaved (AVI) file.
%  We specify its name and FPS.
%
  aviobj = avifile ( 'peak_movie.avi', 'fps', fps );
%
%  Retrieve each file.
%
  for frame_id = 0 : frame_total
    filename = sprintf ( 'frame%04d.jpg', frame_id );
    H = imshow ( filename );
    set ( H, 'EraseMode', 'xor' );
    set ( gca, 'nextplot', 'replacechildren' );
    shading interp;
    axis tight square off;
    frame = getframe ( gca );
    aviobj = addframe ( aviobj, frame );
  end
%
%  Tell MATLAB we have completed the movie.
%
  aviobj = close ( aviobj );

  fprintf ( 1, '\n' );
  fprintf ( 1, 'MAKE_ANIMATION:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );

  return
end


function dat =  gen(algo)
%
%           data =  gen(algorithm)
%
%  Data will be generated from a generative model. This should be
%  equivalent to
%                    test(algo)
%  (no data is supplied to the test function)

  dat = generate(algo);


function mappedModel = mapModelMets(model,mnx)
%mapModelMets  Retrieve and assign standard IDs to model metabolites.
%
% USAGE:
%
%   mappedModel = mapModelMets(model,mnx);
%
% INPUTS:
%
%   model   A genome scale model structure, containing metabolite related
%           fields (e.g., mets, metNames, etc.).
%
%   mnx     An MNX metabolite database structure generated using the
%           buildMNXmodel('met') function.
%
% OUTPUS:
%
%   mappedModel   The model returned with additional metabolite-related
%                 fields, associating various metabolite IDs to MNX IDs, as
%                 well as a metMNXID field which combines the MNX IDs
%                 obtained by mapping metabolites along each of its
%                 available ID fields.
%                 *NOTE: Some of the met-related fields in mappedModel may
%                        contain multiple columns, which contain the
%                        multiple IDs that matched to one or more of the
%                        metabolites.
%

% handle input arguments
if nargin < 2
    mnx = [];
end

% get list of metID fields
ignoreFields = {'metFormulas','metMiriams','metComps','mets', ...
                'metNamesAlt','metCharges','metSMILES','metPdMap'};
metIDfields = fields(model);
metIDfields(~startsWith(metIDfields,'met') | ismember(lower(metIDfields),lower(ignoreFields))) = [];

% load metabolite information from MNX database file
if isempty(mnx)
    mnx = buildMNXmodel('met');
end

% associate each set of IDs to MNX IDs
fprintf('Mapping metabolite external IDs to MNX IDs:\n');
for i = 1:length(metIDfields)

    % skip field if it isn't present in the MNX database model structure
    if ~isfield(mnx,metIDfields{i})
        continue
    end

    fprintf('\t%s\n',metIDfields{i});
    if strcmp(metIDfields{i},'metNames')  % the 'metNames' field is handled differently than others

        % combine names and alternative names into single cell array
        if isfield(model,'metNamesAlt')
            metNames = [model.metNames,model.metNamesAlt];
        else
            metNames = model.metNames;
        end

        % ignore case
        metNames = lower(metNames);
        mnx.mnxID2name(:,2) = lower(mnx.mnxID2name(:,2));

        % Perform the name-matching process twice. The first pass will
        % search for exact name matches (ignoring case), whereas the second
        % pass will loosen the criteria by removing all special characters
        % (e.g., hyphens, parentheses, spaces, etc.) from the met names,
        % and search again for any mets that were not matched during the
        % first pass.
        for ii = 1:2

            if ii == 2
                % remove special characters from metabolite names
                metNames = regexprep(metNames,'[^a-zA-Z0-9]','');
                mnx.mnxID2name(:,2) = regexprep(mnx.mnxID2name(:,2),'[^a-zA-Z0-9]','');
            else
                model.metName2MNX = repmat({''},size(model.mets));
            end

            % extract subset of MNXID-name pairs containing matching names (for faster processing)
            keep_ind = ismember(mnx.mnxID2name(:,2),metNames);
            mnx_ids = mnx.mnxID2name(keep_ind,1);
            mnx_names = mnx.mnxID2name(keep_ind,2);

            % convert metNames from cell array to column vector of nested cells (for next processing step)
            metNamesNest = nestCell(metNames,true);
            ignore_inds = ~cellfun(@isempty,model.metName2MNX) | cellfun(@isempty,metNamesNest);

            % retrieve all matching IDs for each met
            model.metName2MNX(~ignore_inds) = cellfun(@(x) mnx_ids(ismember(mnx_names,x)),metNamesNest(~ignore_inds),'UniformOutput',false);

        end

        % remove entries that have matched to too many IDs (>100)
        model.metName2MNX(cellfun(@numel,model.metName2MNX) > 100) = {''};

        % flatten cell array
        model.metName2MNX = flattenCell(model.metName2MNX,true);

    else
        % get model met IDs, and compress each row into nested cells
        % (this is to deal with fields that have multiple columns)
        model_ids = nestCell(model.(metIDfields{i}),true);

        % extract only subset of MNX model containing matching IDs (for faster processing)
        keep_ind = ismember(mnx.mnxID2extID(:,2),metIDfields(i)) & ismember(mnx.mnxID2extID(:,3),model.(metIDfields{i}));
        ext_ids = mnx.mnxID2extID(keep_ind,3);
        mnx_ids = mnx.mnxID2extID(keep_ind,1);

        % get empty indices for current field
        empty_inds = cellfun(@isempty,model_ids);

        % retrieve all matching IDs for each met
        newField = strcat(metIDfields{i},'2MNX');
        model.(newField) = repmat({''},size(model.mets));
        model.(newField)(~empty_inds) = cellfun(@(x) mnx_ids(ismember(ext_ids,x)),model_ids(~empty_inds),'UniformOutput',false);

        % flatten cell array
        model.(newField) = flattenCell(model.(newField),true);
    end

end
fprintf('Done.\n');

% now combine all the MNX IDs for each metabolite
mnxIDfields = fields(model);
mnxIDfields(~(startsWith(mnxIDfields,'met') & endsWith(mnxIDfields,'2MNX'))) = [];
metMNXIDs = {};  % intialize cell array of met MNX IDs
for i = 1:length(mnxIDfields)
    % append each field as new column(s)
    metMNXIDs = [metMNXIDs,model.(mnxIDfields{i})];
end
empty_inds = cellfun(@isempty,metMNXIDs);
% metMNXIDs(empty_inds) = {''};

% obtain unique set of MNX IDs for each metabolite
met_index = transpose(1:length(model.mets));
model.metMNXID = arrayfun(@(i) unique(metMNXIDs(i,~empty_inds(i,:))),met_index,'UniformOutput',false);
model.metMNXID = flattenCell(model.metMNXID,true);

% assign output
mappedModel = model;

end


function fighandle=dockfig(varargin)
% fighandle=dockfig(figs)      DOCK one or more FIGures.
%   "fighandle" is an array of handle numbers for the figures.
%   "figs" is an array of figure handles.
%       If "figs" is empty then all figures are docked.
%   Examples:
%       figh=dockfig([4,3,5]), dockfig, dockfig 4 3 5
% Note that the command line format is supported.

%   Copyright 2006 Mirtech, Inc.
%   created 09/20/2006  by Mirko Hrovat on Matlab Ver. 7.2
%   Mirtech, Inc.       email: mhrovat@email.com
figs=[];
if nargin>0,
    for n=1:length(varargin),
        arg=varargin{n};
        if ischar(arg),
            tmp=str2num(arg);   %#ok
            if isempty(tmp),    % since it is empty then it may be a variable
                tmp = evalin('base',arg);
                if isempty(tmp),
                    error ('  Syntax error in argument!'),
                end
            end  % isempty(tmp)
        else
            tmp=arg;
        end  % ischar(arg)
        figs=[figs,tmp];
    end  % for
end  % if nargin
if isempty(figs),       figs=0;     end

% set this to "on" so that all figures with "HandleVisibility" set to off can be seen.
set(0,'ShowHiddenHandles','on')
% Below are two alternative methods to find all of the figures.
% Second method should be more foolproof.
% allhands=get(0,'Children');
allhands=findobj('Type','figure');
set(0,'ShowHiddenHandles','off')
if figs==0,
    figs=sort(allhands)';
else
    [tmp,indx]=intersect(figs,allhands);    %#ok tmp not used, view figures that exist
    figs=figs(sort(indx));                  % order the figures as specified
end
numfigs=numel(figs);

if isempty(figs),
    warning('MATLAB:EmptyValue','There are no figures to dock.')
else
    for n=numfigs:-1:1,
        set(figs(n),'WindowStyle','docked');
        figure(figs(n))             % bring figure to front.
    end
end

if nargout==1,
    fighandle=figs;
end


function c = char(u)

%tstoolbox/@unit/char
%   gives the unit's label (e.g. V for Volt) back.
%
% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt

c = u.label;


%% parbound
% Below is a demonstration of the features of the |parbound| function

%%
clear; close all; clc;

%% Syntax
% |Pb=parbound(P,Ps);|

%% Description
% UNDOCUMENTED
%% Examples
%
%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>
%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.


%% magma
% Below is a demonstration of the features of the |magma| function

%%
clear; close all; clc;

%% Syntax
% |[cMap]=magma(varargin);|

%% Description
% UNDOCUMENTED
%% Examples
%
%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>
%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.


function qual_obj_array = load_qual_files(filenames)
% This function loads quality measures from files into an array of
% Quality objects.
% Inputs:
%   filenames: A list of files containing quality measures.
% Output:
%   qual_obj_array: An array of Quality objects containing the same
%     number of elements as filenames.

assert(iscell(filenames))

num_systems = length(filenames);
qual_obj_array = Quality.empty(num_systems,0);

log_info('quality:\n');

for ii=1:num_systems
    qual_obj_array(ii) = Quality.read(filenames{ii});
    log_info(' %s\n',filenames{ii});
end


% shell to start SCNlab BrainTools

global EXPT
global cl

% for timeseries viewer
global VOL
global f
global f2

hewma_gui;


function vocabList = getVocabList()
%GETVOCABLIST reads the fixed vocabulary list in vocab.txt and returns a
%cell array of the words
%   vocabList = GETVOCABLIST() reads the fixed vocabulary list in vocab.txt
%   and returns a cell array of the words in vocabList.

%% Read the fixed vocabulary list
fid = fopen('vocab.txt');

% Store all dictionary words in cell array vocab{}
n = 1899;  % Total number of words in the dictionary

% For ease of implementation, we use a struct to map the strings => integers
% In practice, you'll want to use some form of hashmap
vocabList = cell(n, 1);
for i = 1:n
    % Word Index (can ignore since it will be = i)
    fscanf(fid, '%d', 1);
    % Actual Word
    vocabList{i} = fscanf(fid, '%s', 1);
end
fclose(fid);

end


function handles = setSimGraphEdits(hObject, handles)
% setSimGraphEdits Enables or disables the text edits depending on the
% current similarity graph type

switch handles.SimGraphType
    case 1
        enableNeighbors = 'off';
        enableEps = 'off';
        enableSigma = 'on';
    case {2,3}
        enableNeighbors = 'on';
        enableEps = 'off';
        enableSigma = 'on';
    case 4
        enableNeighbors = 'off';
        enableEps = 'on';
        enableSigma = 'off';
end

set(handles.edtSimGraphNeighbors, 'Enable', enableNeighbors);
set(handles.edtSimGraphEps, 'Enable', enableEps);
set(handles.edtSimGraphSigma, 'Enable', enableSigma);

guidata(hObject, handles);


classdef RangeAnnotation < handle
    properties (Access = public)
        startSample;
        endSample;
        label;
    end

    properties (Dependent)
        nSamples;
    end

    methods
        function n = get.nSamples(obj)
            n = obj.endSample - obj.startSample + 1;
        end
    end

    methods (Access = public)
        function obj = RangeAnnotation(startSample,endSample,label)
            if nargin > 0
                obj.startSample = startSample;
                obj.endSample = endSample;
                obj.label = label;
            end
        end
    end
end


classdef InheritStateEnum < matlab.mixin.SetGet
    %InheritStateEnum Summary of this class goes here
    %   Detailed explanation goes here

    enumeration
        InheritFromLastState('Inherit From Last State')
        InheritFromSpecifiedEvent('Inherit From Specified Event')
    end

    properties
        name
    end

    methods
        function obj = InheritStateEnum(name)
            obj.name = name;
        end
    end

    methods(Static)
        function listBoxStr = getListBoxStr()
            m = enumeration('InheritStateEnum');
            [~,I] = sort({m.name});
            listBoxStr = {m(I).name};
        end

        function [ind, enum] = getIndForName(name)
            m = enumeration('InheritStateEnum');
            [~,I] = sort({m.name});
            m = m(I);
            ind = find(ismember({m.name},name),1,'first');
            enum = m(ind);
        end

        function [enum, ind] = getEnumForListboxStr(nameStr)
            m = enumeration('InheritStateEnum');
            ind = find(ismember({m.name},nameStr),1,'first');
            enum = m(ind);
        end
    end
end


function tfocs_ver2 = tfocs_version

%TFOCS_VERSION   Version information.
%    Prints information about the version of TFOCS being used, and the
%    system on which it is running. When submitting a bug report, please
%    run this function and include its output in your report.

tfocs_ver = '1.4';
if nargout == 0,
    fprintf( 'TFOCS v%s\n', tfocs_ver );
    verd = ver('MATLAB');
    fprintf( 'MATLAB version %s %s on %s\n', verd.Version, verd.Release, computer );
else
    tfocs_ver2 = tfocs_ver;
end

% TFOCS v1.4 by Stephen Becker, Emmanuel Candes, and Michael Grant.
% Copyright 2015 California Institute of Technology and CVX Research.
% See the file LICENSE for full license information.


function add_rx_tx_io(hRD)

% add AXI4 and AXI4-Lite slave interfaces
hRD.addAXI4SlaveInterface( ...
    'InterfaceConnection', 'axi_cpu_interconnect/M11_AXI', ...
    'BaseAddress',         '0x43C00000', ...
    'MasterAddressSpace',  'sys_ps7/Data');

% % AGC control input for transceiver
% hRD.addInternalIOInterface( ...
%     'InterfaceID',    'Enable AGC', ...
%     'InterfaceType',  'OUT', ...
%     'PortName',       'en_agc', ...
%     'PortWidth',      1, ...
%     'InterfaceConnection', 'gpio_en_agc', ...
%     'IsRequired',     false);

% GPIO status output for transceiver
hRD.addInternalIOInterface( ...
    'InterfaceID',    'CTRL_STATUS', ...
    'InterfaceType',  'IN', ...
    'PortName',       'gpio_status', ...
    'PortWidth',      8, ...
    'InterfaceConnection', 'gpio_status', ...
    'IsRequired',     false);

% GPIO Control input for transceiver
hRD.addInternalIOInterface( ...
    'InterfaceID',    'AD9361 CTRL IN', ...
    'InterfaceType',  'OUT', ...
    'PortName',       'gpio_ctl', ...
    'PortWidth',      4, ...
    'InterfaceConnection', 'gpio_ctl', ...
    'IsRequired',     false);

% DMA Ready signal
hRD.addInternalIOInterface( ...
    'InterfaceID',    'DMA Ready', ...
    'InterfaceType',  'IN', ...
    'PortName',       'dma_rdy', ...
    'PortWidth',      1, ...
    'InterfaceConnection', 'axi_ad9361_adc_dma/s_axis_ready', ...
    'IsRequired',     false);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Rx Reference design interfaces
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
hRD.addInternalIOInterface( ...
    'InterfaceID',    'IP Data Valid OUT', ...
    'InterfaceType',  'OUT', ...
    'PortName',       'dut_data_valid', ...
    'PortWidth',      1, ...
    'InterfaceConnection', 'util_ad9361_adc_pack/adc_valid_0', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'IP Data 0 OUT', ...
    'InterfaceType',  'OUT', ...
    'PortName',       'dut_data_0', ...
    'PortWidth',      16, ...
    'InterfaceConnection', 'util_ad9361_adc_pack/adc_data_0', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'IP Data 1 OUT', ...
    'InterfaceType',  'OUT', ...
    'PortName',       'dut_data_1', ...
    'PortWidth',      16, ...
    'InterfaceConnection', 'util_ad9361_adc_pack/adc_data_1', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'IP Data 2 OUT', ...
    'InterfaceType',  'OUT', ...
    'PortName',       'dut_data_2', ...
    'PortWidth',      16, ...
    'InterfaceConnection', 'util_ad9361_adc_pack/adc_data_2', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'IP Data 3 OUT', ...
    'InterfaceType',  'OUT', ...
    'PortName',       'dut_data_3', ...
    'PortWidth',      16, ...
    'InterfaceConnection', 'util_ad9361_adc_pack/adc_data_3', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'AD9361 ADC Data I0', ...
    'InterfaceType',  'IN', ...
    'PortName',       'sys_wfifo_0_dma_wdata', ...
    'PortWidth',      16, ...
    'InterfaceConnection', 'util_ad9361_adc_fifo/dout_data_0', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'AD9361 ADC Data Q0', ...
    'InterfaceType',  'IN', ...
    'PortName',       'sys_wfifo_1_dma_wdata', ...
    'PortWidth',      16, ...
    'InterfaceConnection', 'util_ad9361_adc_fifo/dout_data_1', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'AD9361 ADC Data I1', ...
    'InterfaceType',  'IN', ...
    'PortName',       'sys_wfifo_2_dma_wdata', ...
    'PortWidth',      16, ...
    'InterfaceConnection', 'util_ad9361_adc_fifo/dout_data_2', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'AD9361 ADC Data Q1', ...
    'InterfaceType',  'IN', ...
    'PortName',       'sys_wfifo_3_dma_wdata', ...
    'PortWidth',      16, ...
    'InterfaceConnection', 'util_ad9361_adc_fifo/dout_data_3', ...
    'IsRequired',     false);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Tx Reference design interfaces
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
hRD.addInternalIOInterface( ...
    'InterfaceID',    'AD9361 DAC Data I0', ...
    'InterfaceType',  'OUT', ...
    'PortName',       'axi_ad9361_dac_data_i0', ...
    'PortWidth',      16, ...
    'InterfaceConnection', 'axi_ad9361_dac_fifo/din_data_0', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'AD9361 DAC Data Q0', ...
    'InterfaceType',  'OUT', ...
    'PortName',       'axi_ad9361_dac_data_q0', ...
    'PortWidth',      16, ...
    'InterfaceConnection', 'axi_ad9361_dac_fifo/din_data_1', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'AD9361 DAC Data I1', ...
    'InterfaceType',  'OUT', ...
    'PortName',       'axi_ad9361_dac_data_i1', ...
    'PortWidth',      16, ...
    'InterfaceConnection', 'axi_ad9361_dac_fifo/din_data_2', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'AD9361 DAC Data Q1', ...
    'InterfaceType',  'OUT', ...
    'PortName',       'axi_ad9361_dac_data_q1', ...
    'PortWidth',      16, ...
    'InterfaceConnection', 'axi_ad9361_dac_fifo/din_data_3', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'IP Data 0 IN', ...
    'InterfaceType',  'IN', ...
    'PortName',       'util_dac_unpack_dac_data_00', ...
    'PortWidth',      16, ...
    'InterfaceConnection', 'util_ad9361_dac_upack/dac_data_0', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'IP Data 1 IN', ...
    'InterfaceType',  'IN', ...
    'PortName',       'util_dac_unpack_dac_data_01', ...
    'PortWidth',      16, ...
    'InterfaceConnection', 'util_ad9361_dac_upack/dac_data_1', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'IP Data 2 IN', ...
    'InterfaceType',  'IN', ...
    'PortName',       'util_dac_unpack_dac_data_02', ...
    'PortWidth',      16, ...
    'InterfaceConnection', 'util_ad9361_dac_upack/dac_data_2', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'IP Data 3 IN', ...
    'InterfaceType',  'IN', ...
    'PortName',       'util_dac_unpack_dac_data_03', ...
    'PortWidth',      16, ...
    'InterfaceConnection', 'util_ad9361_dac_upack/dac_data_3', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'IP Load Tx Data OUT', ...
    'InterfaceType',  'OUT', ...
    'PortName',       'util_dac_unpack_dac_valid_00', ...
    'PortWidth',      1, ...
    'InterfaceConnection', 'util_ad9361_dac_upack/dac_valid_0', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'IP Valid Tx Data IN', ...
    'InterfaceType',  'IN', ...
    'PortName',       'util_dac_unpack_upack_valid_00', ...
    'PortWidth',      1, ...
    'InterfaceConnection', 'util_ad9361_dac_upack/upack_valid_0', ...
    'IsRequired',     false);


function cl=cleanRequired(seqFolder)

cl = ~isempty(strfind(seqFolder,'MOT16')) || ~isempty(strfind(seqFolder,'MOT17'));


function rv = mostver(varargin)
%MOSTVER  Prints or returns MOST version info for current installation.
%   V = MOSTVER returns the current MOST version number.
%   V = MOSTVER('all') returns a struct with the fields Name, Version,
%   Release and Date (all strings). Calling MOSTVER without assigning the
%   return value prints the version and release date of the current
%   installation of MOST.
%
%   See also MPVER.

%   MOST
%   Copyright (c) 2010-2022, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MOST.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://github.com/MATPOWER/most for more info.

v = struct( 'Name',     'MOST', ...
            'Version',  '1.2', ...
            'Release',  '', ...
            'Date',     '13-Dec-2022' );
if nargout > 0
    if nargin > 0
        rv = v;
    else
        rv = v.Version;
    end
else
    fprintf('%-22s Version %-9s  %11s\n', v.Name, v.Version, v.Date);
end


function varargout = process_import_channel( varargin )
% PROCESS_IMPORT_CHANNEL: Import a raw file in the database.

% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2012-2017

eval(macro_method);
end

%% ===== GET DESCRIPTION =====
function sProcess = GetDescription() %#ok<DEFNU>
    % ===== EEG DEFAULTS =====
    strList = {''};
    % Get registered Brainstorm EEG defaults
    bstDefaults = bst_get('EegDefaults');
    % Build a list of strings representing all the defaults
    for iGroup = 1:length(bstDefaults)
        for iDef = 1:length(bstDefaults(iGroup).contents)
            strList{end+1} = [bstDefaults(iGroup).name ': ' bstDefaults(iGroup).contents(iDef).name];
        end
    end

    % ===== PROCESS =====
    % Description the process
    sProcess.Comment     = 'Set channel file';
    sProcess.Category    = 'Custom';
    sProcess.SubGroup    = {'Import', 'Channel file'};
    sProcess.Index       = 30;
    sProcess.Description = 'https://neuroimage.usc.edu/brainstorm/Tutorials/Epilepsy#Prepare_the_channel_file';
    % Definition of the input accepted by this process
    sProcess.InputTypes  = {'data', 'raw', 'matrix'};
    sProcess.OutputTypes = {'data', 'raw', 'matrix'};
    sProcess.nInputs     = 1;
    sProcess.nMinFiles   = 1;
    sProcess.isSeparator = 1;
    % Option: File to import
    sProcess.options.channelfile.Comment = 'File to import:';
    sProcess.options.channelfile.Type    = 'filename';
    sProcess.options.channelfile.Value   = {...
        '', ...                                % Filename
        '', ...                                % FileFormat
        'open', ...                            % Dialog type: {open,save}
        'Import channel file', ...             % Window title
        'ImportChannel', ...                   % LastUsedDir: {ImportData,ImportChannel,ImportAnat,ExportChannel,ExportData,ExportAnat,ExportProtocol,ExportImage,ExportScript}
        'single', ...                          % Selection mode: {single,multiple}
        'files_and_dirs', ...                  % Selection mode: {files,dirs,files_and_dirs}
        bst_get('FileFilters', 'channel'), ... % Get all the available file formats
        'ChannelIn'};                          % DefaultFormats
    % Option: Default channel files
    sProcess.options.usedefault.Comment = 'Or use default:';
    sProcess.options.usedefault.Type    = 'combobox';
    sProcess.options.usedefault.Value   = {1, strList};
    % Separator
    sProcess.options.separator.Type = 'separator';
    sProcess.options.separator.Comment = ' ';
    % Align sensors
    sProcess.options.channelalign.Comment = 'Align sensors using headpoints';
    sProcess.options.channelalign.Type    = 'checkbox';
    sProcess.options.channelalign.Value   = 1;
    % Fix units
    sProcess.options.fixunits.Comment = 'Fix distance units automatically';
    sProcess.options.fixunits.Type    = 'checkbox';
    sProcess.options.fixunits.Value   = 1;
    % Fix units
    sProcess.options.vox2ras.Comment = 'Apply voxel=>subject transformation from the MRI';
    sProcess.options.vox2ras.Type    = 'checkbox';
    sProcess.options.vox2ras.Value   = 1;
end

%% ===== FORMAT COMMENT =====
function Comment = FormatComment(sProcess) %#ok<DEFNU>
    Comment = sProcess.Comment;
end

%% ===== RUN =====
function OutputFiles = Run(sProcess, sInputs) %#ok<DEFNU>
    OutputFiles = {};

    % ===== GET FILE =====
    % Get filename to import
    ChannelFile = sProcess.options.channelfile.Value{1};
    FileFormat  = sProcess.options.channelfile.Value{2};

    % ===== GET DEFAULT =====
    if isempty(ChannelFile)
        % Get registered Brainstorm EEG defaults
        bstDefaults = bst_get('EegDefaults');
        % Get default channel file
        iSel   = sProcess.options.usedefault.Value{1};
        strDef = sProcess.options.usedefault.Value{2}{iSel};
        % If there is something selected
        if ~isempty(strDef)
            % Format: "group: name"
            cDef   = strtrim(str_split(strDef, ':'));
            % Find the selected group in the list
            iGroup = find(strcmpi(cDef{1}, {bstDefaults.name}));
            % If group is found
            if ~isempty(iGroup)
                % Find the selected default in the list
                iDef = find(strcmpi(cDef{2}, {bstDefaults(iGroup).contents.name}));
                % If default was found
                if ~isempty(iDef)
                    ChannelFile = bstDefaults(iGroup).contents(iDef).fullpath;
                end
            end
        end
        FileFormat = 'BST';
    end
    % If nothing was selected (file or default)
    if isempty(ChannelFile)
        bst_report('Error', sProcess, [], 'No channel file selected.');
        return
    end

    % ===== SET CHANNEL FILE =====
    % Get channel studies
    [tmp, iChanStudies] = bst_get('ChannelForStudy', [sInputs.iStudy]);
    iChanStudies = unique(iChanStudies);
    % Channel align
    ChannelAlign = 2 * double(sProcess.options.channelalign.Value);
    % Other options
    if isfield(sProcess.options, 'fixunits') && isfield(sProcess.options.fixunits, 'Value')
        isFixUnits = sProcess.options.fixunits.Value;
    else
        isFixUnits = 1;
    end
    if isfield(sProcess.options, 'vox2ras') && isfield(sProcess.options.vox2ras, 'Value')
        isApplyVox2ras = sProcess.options.vox2ras.Value;
    else
        isApplyVox2ras = 1;
    end
    % Import channel files
    ChannelReplace = 2;
    isSave = 1;
    import_channel(iChanStudies, ChannelFile, FileFormat, ChannelReplace, ChannelAlign, isSave, isFixUnits, isApplyVox2ras);
    % Return all the files in input
    OutputFiles = {sInputs.FileName};
end


function disp(sncl)
% DISP - scnl disp overloaded operator

% VERSION: 1.0 of filter objects
% AUTHOR: Celso Reyes
% LASTUPDATE: 1/30/2007
if numel(sncl) > 1;
    disp(' ');
    DispStr = sprintf('%d',size(sncl,1));
    for n = 2 : numel(size(sncl))
        DispStr = sprintf('%sx%d', DispStr, size(sncl,n));
    end
    disp(sprintf('%s %s object with fields:', DispStr, class(sncl)));
    disp('    station');
    disp('    channel');
    disp('    network');
    disp('   location');
else
    disp(['   station: ' sncl.tag.station]);
    disp(['   channel: ' sncl.tag.channel]);
    disp(['   network: ' sncl.tag.network]);
    disp(['  location: ' sncl.tag.location]);
end;


function [timelock] = ft_datatype_timelock(timelock, varargin)

% FT_DATATYPE_TIMELOCK describes the FieldTrip MATLAB structure for timelock data
%
% The timelock data structure represents averaged or non-averaged event-releted
% potentials (ERPs, in case of EEG) or ERFs (in case of MEG). This data structure is
% usually generated with the FT_TIMELOCKANALYSIS or FT_TIMELOCKGRANDAVERAGE function.
%
% An example of a timelock structure containing the ERF for 151 channels MEG data is
%
%     dimord: 'chan_time'       defines how the numeric data should be interpreted
%        avg: [151x600 double]  the average values of the activity for 151 channels x 600 timepoints
%        var: [151x600 double]  the variance of the activity for 151 channels x 600 timepoints
%      label: {151x1 cell}      the channel labels (e.g. 'MRC13')
%       time: [1x600 double]    the timepoints in seconds
%       grad: [1x1 struct]      information about the sensor array (for EEG data it is called elec)
%        cfg: [1x1 struct]      the configuration used by the function that generated this data structure
%
% Required fields:
%   - label, dimord, time
%
% Optional fields:
%   - avg, var, dof, cov, trial, trialinfo, sampleinfo, grad, elec, opto, cfg
%
% Deprecated fields:
%   - <none>
%
% Obsoleted fields:
%   - fsample
%
% Revision history:
%
% (2017/latest) The data structure cannot contain an average and simultaneously single
% trial information any more, i.e. avg/var/dof and trial/individual are mutually exclusive.
%
% (2011v2) The description of the sensors has changed, see FT_DATATYPE_SENS
% for further information.
%
% (2011) The field 'fsample' was removed, as it was redundant.
%
% (2003) The initial version was defined.
%
% See also FT_DATATYPE, FT_DATATYPE_COMP, FT_DATATYPE_FREQ, FT_DATATYPE_RAW

% Copyright (C) 2011, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

% get the optional input arguments, which should be specified as key-value pairs
version       = ft_getopt(varargin, 'version', 'latest');
hassampleinfo = ft_getopt(varargin, 'hassampleinfo', 'ifmakessense'); % can be yes/no/ifmakessense
hastrialinfo  = ft_getopt(varargin, 'hastrialinfo',  'ifmakessense'); % can be yes/no/ifmakessense

% convert it into true/false
if isequal(hassampleinfo, 'ifmakessense')
  hassampleinfo = makessense(timelock, 'sampleinfo');
else
  hassampleinfo = istrue(hassampleinfo);
end
if isequal(hastrialinfo, 'ifmakessense')
  hastrialinfo = makessense(timelock, 'trialinfo');
else
  hastrialinfo = istrue(hastrialinfo);
end

if strcmp(version, 'latest')
  version = '2017';
end

if isempty(timelock)
  return;
end

% do some sanity checks
assert(isfield(timelock, 'time') && isfield(timelock, 'label'), 'inconsistent timelock data structure, some field is missing');
assert(length(unique(timelock.label))==length(timelock.label), 'channel labels must be unique');

% ensure consistency between the dimord string and the axes that describe the data dimensions
timelock = fixdimord(timelock);

% remove these very obsolete fields, it is unclear when they were precisely used
if isfield(timelock, 'numsamples'),       timelock = rmfield(timelock, 'numsamples');       end
if isfield(timelock, 'numcovsamples'),    timelock = rmfield(timelock, 'numcovsamples');    end
if isfield(timelock, 'numblcovsamples'),  timelock = rmfield(timelock, 'numblcovsamples');  end

if ~iscolumn(timelock.label)
  timelock.label = timelock.label';
end
if ~isrow(timelock.time)
  timelock.time = timelock.time';
end
if ~isfield(timelock, 'label')
  ft_warning('data structure is incorrect since it has no channel labels');
end

switch version
  case '2017'
    % ensure that the sensor structures are up to date
    if isfield(timelock, 'grad')
      timelock.grad = ft_datatype_sens(timelock.grad);
    end
    if isfield(timelock, 'elec')
      timelock.elec = ft_datatype_sens(timelock.elec);
    end
    if isfield(timelock, 'opto')
      timelock.opto = ft_datatype_sens(timelock.opto);
    end

    fn = fieldnames(timelock);
    fn = setdiff(fn, ignorefields('appendtimelock'));
    fn = fn(~endsWith(fn, 'dimord'));
    dimord = cell(size(fn));
    hasrpt = false(size(fn));
    for i=1:numel(fn)
      dimord{i} = getdimord(timelock, fn{i});
      hasrpt(i) = ~isempty(strfind(dimord{i}, 'rpt')) || ~isempty(strfind(dimord{i}, 'subj'));
    end
    if any(hasrpt) && ~all(hasrpt)
      ft_warning('timelock structure contains field with and without repetitions');
      str = sprintf('%s, ', fn{hasrpt});
      str = str(1:end-2);
      ft_notice('selecting these fields that have repetitions: %s', str);
      str = sprintf('%s, ', fn{~hasrpt});
      str = str(1:end-2);
      ft_notice('removing these fields that do not have repetitions: %s', str);
      timelock = removefields(timelock, fn(~hasrpt));
      if isfield(timelock, 'dimord') && ~ismember(timelock.dimord, dimord(hasrpt))
        % the dimord does not apply to any of the existing fields any more
        timelock = rmfield(timelock, 'dimord');
        timelock = fixdimord(timelock);
      end
    end

    if (hassampleinfo && ~isfield(timelock, 'sampleinfo')) || (hastrialinfo && ~isfield(timelock, 'trialinfo'))
      % try to reconstruct the sampleinfo and trialinfo
      timelock = fixsampleinfo(timelock);
    end

    if ~hassampleinfo && isfield(timelock, 'sampleinfo')
      timelock = rmfield(timelock, 'sampleinfo');
    end

    if ~hastrialinfo && isfield(timelock, 'trialinfo')
      timelock = rmfield(timelock, 'trialinfo');
    end

    % this field can be present in raw data, but is not desired in timelock data
    timelock = removefields(timelock, {'fsample'});

    % ensure that the structure has all required fields
    % note that dimord is listed as required field, but it might also be xxxdimord, or dynamically determined with GETDIMORD
    for required={'label' 'time'}
      assert(isfield(timelock, required), 'required field "%s" is missing', required{:});
    end

  case '2011v2'
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % ensure that the sensor structures are up to date
    if isfield(timelock, 'grad')
      timelock.grad = ft_datatype_sens(timelock.grad);
    end
    if isfield(timelock, 'elec')
      timelock.elec = ft_datatype_sens(timelock.elec);
    end
    if isfield(timelock, 'opto')
      timelock.opto = ft_datatype_sens(timelock.opto);
    end

    % these fields can be present in raw data, but are not desired in timelock data
    timelock = removefields(timelock, {'sampleinfo', 'fsample'});

  case '2003'
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % there are no known conversions for backward or forward compatibility support

  otherwise
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    ft_error('unsupported version "%s" for timelock datatype', version);
end


function commentAllTryCatch(comment)
% SYNTAX:
%    commentAllTryCatch(comment)
% EXAMPLE:
%    commentAllTryCatch(true)
%
% DESCRIPTION:
%    comment or uncomment all  try    cathc for debugging purpouse
%
% INPUT:
%   comment : if true comment if false decomment
%--- * --. --- --. .--. ... * ---------------------------------------------
%               ___ ___ ___
%     __ _ ___ / __| _ | __|
%    / _` / _ \ (_ |  _|__ \
%    \__, \___/\___|_| |___/
%    |___/                    v 1.0RC1
%
%--------------------------------------------------------------------------
%  Copyright (C) 2021 Geomatics Research & Development srl (GReD)
%  A list of all the historical goGPS contributors is in CREDITS.nfo
%--------------------------------------------------------------------------
%
%   This program is free software: you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation, either version 3 of the License, or
%   (at your option) any later version.
%
%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You should have received a copy of the GNU General Public License
%   along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------------------------------------
% 01100111 01101111 01000111 01010000 01010011
%--------------------------------------------------------------------------

if nargin < 1
    comment = true;
end

% find all the m files in goGPS directory

base_dir = '.';
filter = '*.m';
if ~exist(base_dir, 'dir')
    if iscell(base_dir)
        list = base_dir;
    else
        list = {base_dir};
    end
else
    [~, list] = dos(['find ' base_dir ' -name \' filter]);
    if ~isempty(list)
        list = textscan(list,'%s','Delimiter','\n','whitespace','');
        list = list{1};
    end
end
if comment
    tic
    for i = 1 : length(list)
        file_name = list{i};
        if isempty(strfind(file_name,'thirdParty')) & isempty(strfind(file_name,'commentAllTryCatch'))
        fid = fopen(file_name, 'r');
        txt = fread(fid,'*char')';
        fclose(fid);
        %occurencies = regexp(txt, expression, 'once');
        %clean_txt = regexprep(txt, expression, replace);
        occurencies = regexp(txt,' try');

        clean_txt = regexprep(txt, ' try', '%AUTCOMMS try');
        clean_txt = regexprep(clean_txt, '\ttry', '%AUTCOMMT try');

        occurencies = strfind(clean_txt, 'catch');
        clean_txt = strrep(clean_txt, 'catch', 'if false %AUTCOMM');

        if not(isempty(clean_txt)) && ~isempty(occurencies)
            fprintf('Opening file %3d/%3d: %s', i, length(list), file_name);
            fid = fopen(file_name, 'w');
            fwrite(fid, clean_txt);
            fclose(fid);
            fprintf(' -> changed\n');
        end
        end
    end
    toc;
else
    tic
    for i = 1 : length(list)
        file_name = list{i};
                if isempty(strfind(file_name,'thirdParty')) & isempty(strfind(file_name,'commentAllTryCatch'))

        fid = fopen(file_name, 'r');
        txt = fread(fid,'*char')';
        fclose(fid);
        %occurencies = regexp(txt, expression, 'once');
        %clean_txt = regexprep(txt, expression, replace);
        occurencies = strfind(txt, '%AUTCOMMS try');
        clean_txt = strrep(txt,'%AUTCOMMS try', ' try');
        clean_txt = strrep(clean_txt,'%AUTCOMMT try', '\ttry');

        occurencies = strfind(clean_txt,  'if false %AUTCOMM');
        clean_txt = strrep(clean_txt, 'if false %AUTCOMM', 'catch');

        if not(isempty(clean_txt)) && ~isempty(occurencies)
            fprintf('Opening file %3d/%3d: %s', i, length(list), file_name);
            fid = fopen(file_name, 'w');
            fwrite(fid, clean_txt);
            fclose(fid);
            fprintf(' -> changed\n');
        end
                end
    end
    toc;
end


function webKeggMapper(id,str)
% Small script that links to kegg mapper.
%
% USAGE:
%
%    webKeggMapper(id,str)
%
% INPUTS:
%    id:    Either 'ec' or 'kegg'
%    str:   ID of themetabolite / reaction
%
% .. Author: - Stefan G. Thorleifsson March 2011
% .. In case of changes of the website  I keep this script.
%
% .. rBioNet is published under GNU GENERAL PUBLIC LICENSE 3.0+
% .. Thorleifsson, S. G., Thiele, I., rBioNet: A COBRA toolbox extension for
% .. reconstructing high-quality biochemical networks, Bioinformatics, Accepted.
% .. rbionet@systemsbiology.is

if isempty(str) %No id
    msgbox(['There is no ' id ' ID available for this metabolite/reaction.'],'Help','help');
    return;
end

switch id
    case 'ec'
        web(['http://www.genome.jp/kegg-bin/show_pathway?ec01100+' str],'-browser');
    case 'kegg'
        web(['http://www.genome.jp/kegg-bin/show_pathway?rn01100+' str],'-browser');
    otherwise
        msgbox('unknown source');
end


function refactor_fcn_name(fcnname, newfcnname, topdir, domove)
% refactor the name of a function, changing all references to the function
% name in the path and moving the function file to the new named file
%
% Syntax
%
% refactor_fcn_name(fcnname, newfcnname)
% refactor_fcn_name(fcnname, newfcnname, topdir)
% refactor_fcn_name(fcnname, newfcnname, topdir, domove)
%
% Description
%
% refactor_fcn_name(fcnname, newfcnname) finds all uses of the function
% name in fcnname and replaces it with the string in newfcnname in the
% entire matlab path. The function must be function in an m-file on the
% Matlab path. By default the mfile containing the fuction is also then
% renamed to the new name.
%
% refactor_fcn_name(fcnname, newfcnname, topdir) performs the same action
% but searching the folder provided in 'topdir' and all it's subdirectories
% rather than the entire Matlab path.
%
% refactor_fcn_name(fcnname, newfcnname, topdir, domove) performs the same
% action but the 'domove' flag determines whether the function file is
% actually moved or not. If this evaluates to true the file is moved to the
% mfile with the new name, if false nothing is moved.
%
%
% See also: regexprepfile
%

% Created by Richard Crozier 2013

    if ~ischar(fcnname)
        error('fcnname must be a string');
    end

    if ~ischar(newfcnname)
        error('newfcnname must be a string');
    end

    % refactor_fcn_name
    loc = which(fcnname);

    if isempty(loc)
        error('fcnname is not a function or class on the path')
    end

    [pathstr, ~, ext] = fileparts(which(fcnname));

    if isempty(strcmpi(ext, '.m'))
       error('function is not an m-file on the path.')
    end

    if nargin < 3 || isempty(topdir)
        thepath = path2cell(path);
    else
        if ~ischar(topdir)
            error('topdir must be a string');
        end
        if exist(topdir, 'file') ~= 7
            error('supplied directory name does not exist.')
        end
        thepath = path2cell(genpath(topdir));
    end

    if nargin < 4
        domove = true;
    end

    for indi = 1:numel(thepath)

        mfiles = dir([ thepath{indi}, '\*.m' ]);

        for indii = 1:numel(mfiles)
            % replace string in file using regexprepfile, with a regex
            % looking for word boundaries to avoid functions with similar
            % substrings
            regexprepfile(fullfile(thepath{indi}, mfiles(indii).name), ['\<', fcnname, '\>'], newfcnname);
        end

    end

    if domove
        % finally move the function file to the new m-file with the correct
        % name,
        if ispc
            % On windows we can't use the built-in movefile function as the
            % file system is not case sensitive, and will refuse to move
            % the file to what it beleives is the same location, so we take
            % the roundabout route

            % move to a temporary location
            tmpdest = [tempname, '_', newfcnname, ext];
            movefile(fullfile(pathstr, [fcnname, ext]), tmpdest);

            % move it again to where we really want it
            movefile(tmpdest, fullfile(pathstr, [newfcnname, ext]));

        else
            % on other systems, just move it!
            movefile(fullfile(pathstr, [fcnname, ext]), fullfile(pathstr, [newfcnname, ext]));
        end

    end

end

function pathlist = path2cell(pathstr)
%PATH2CELL Convert search path to cell array.
%
%   PATH2CELL returns a cell array where each element is a directory
%   in the search path.
%
%   PATH2CELL(MYPATH) converts MYPATH rather than the search path.
%
%   Empty directories are removed, so under UNIX, PATH2CELL('foo::bar')
%   returns {'foo', 'bar'} rather than {'foo', '', 'bar'}.

%   Author:      Peter J. Acklam
%   Time-stamp:  2001-10-18 21:23:19 +0200
%   E-mail:      pjacklam@online.no
%   URL:         http://home.online.no/~pjacklam

   % check number of input arguments
%    error(nargchk(0, 1, nargin));

   % use MATLAB's search path if no input path is given
   if ~nargin
      pathstr = path;
   end

   k = find(pathstr == pathsep);            % find path separators
   k = [0 k length(pathstr)+1];             % find directory boundaries
   ndirs = length(k)-1;                     % number of directories
   pathlist = cell(0);                      % initialize output argument
   for i = 1 : ndirs
      dir = pathstr(k(i)+1 : k(i+1)-1);     % get i'th directory
      if ~isempty(dir)                      % if non-empty...
         pathlist{end+1,1} = dir;           % ...append to list
      end
   end
end