function [results] = tapas_ti_example()
%% This script simulates data from different models and checks where it comes 
% from.
%
% Input 
%   mi          Model to be used for inversion
%   session     Session of the experiment (either 1 or 2)
%   block       Block of the experiment, either 3, 4 or 5
%   sbj         Subject
% Output
%
% aponteeduardo@gmail.com
% copyright (C) 2015
%

DIM_THETA = sooner_gamma_ndims();

ptheta = tapas_sooner_ptheta();
ptheta.p0(13:15) = [log(1.0) log(0.5) log(0.5)];
htheta = tapas_sooner_htheta();

pars = struct();
pars.T = linspace(0.0001, 1, 16).^5;
pars.nburnin = 5000;
pars.niter = 5000;
pars.mc3it = 8;
pars.verbose = 1;
pars.samples = 1;

data = load(mat_fname());
data = data.table;
[y, u] = prepare_data_db(data);
[y, u] = select_data(y, u, 3, 1);

[pt, tfe]  = tapas_ti_estimate(y, u, ptheta, htheta, pars);
results.pt = pt;
results.fe = tfe;
results.y = y;

end % gamma_inversion

function [y, u] = select_data(y, u, block, session)
%% Selects a chuck of the data

block = block * session;

y.t = y.t(u.b == block);
y.a = y.a(u.b == block);
y.i = y.i(u.b == block);

u.tt = u.tt(u.b == block);

end % select_data

function [fname] = mat_fname()
%% Generates the name of the simulation

% Get current location
f = mfilename('fullpath');
[tdir, ~, ~] = fileparts(f);

fname = fullfile(tdir, 'data', 'tapas_sooner.mat');


end %

function [y, u] = prepare_data_db(data)
%% Generates the data ready to be feeded into the inversion method 
%
% Input
%
%   data    Matrix as generated by the python script.
%
% Output
%   y       Subjects time, actions, and trial validity
%   u       Trial type and block
%

% aponteeduardo@gmail.com
% copyright (C) 2015
%

y = struct('t', [], 'a', [], 'i', []);
u = struct('tt', [], 'b', []);

nt = size(data, 1);

% Tenths of second!
y.t = data(:, 5)/100;
y.a = data(:, 6);
y.i = zeros(nt, 1);
y.i(isnan(y.t)) = 1;

u.tt = data(:, 4);
u.b =  data(:, 1) .* data(:, 2);

% Because of an inconsistency

for i = 1:nt
    if y.a(i) == 0
        y.a(i) = 1;
    else
        y.a(i) = 0;
    end
    if u.tt(i) == 1
        u.tt(i) = 0;
    else
        u.tt(i) = 1;
    end
end

end % prepare_data_db
