function [DCM] = spm_dcm_fmri_check(P, varargin)
% post-hoc diagnostics for DCM (bilinear or nonlinear) of fMRI data
% FORMAT [DCM] = spm_dcm_fmri_check(DCM)
%   DCM     - DCM structure or its filename
%
% FORMAT [GCM] = spm_dcm_fmri_check(GCM)
%   GCM     - Subjects x Models cell array of DCM structures or filenames
%
% FORMAT [DCM] = spm_dcm_fmri_check(DCM, nograph, GCM)
%   DCM     - DCM structure or its filename
%   nograph - (Optional) if true, disables graphical output
%   GCM     - (Optional) full GCM array from which the DCM in P was sourced
%             for use in graphics
%
% This routine provides some diagnostics to ensure model inversion has
% converged. It plots the predicted and observed responses over all regions
% and provides the coefficient of determination - or percent variance
% explained. This should normally be above 10%. An abnormally low
% coefficient of determination is highlighted in red. Quantitatively, one
% would normally expect to see one or more extrinsic (between source)
% connections with the strength of 1/8 Hz or greater. If all the extrinsic
% posterior expectations are below this value, then this suggests a failure
% of convergence or that the data are very noisy (possibly due to using
% very small regions of interest to summarise regional responses). Finally,
% the posterior correlations among all parameters are shown in terms of a
% correlation matrix. The number of effective parameters estimated is
% reported in terms of the (KL) divergence between the posterior and
% prior densities over parameters. This is divided by the log of the
% number of observations, by appealing to the Bayesian information
% criterion. The divergence corresponds to complexity or Bayesian
% surprise. Normally, one would expect the posterior and prior to diverge
% in a non-trivial fashion.
%
% Posterior densities are shown as bars with 90% confidence intervals in
% pink. An informed model inversion would normally provide posterior
% densities with confidence intervals that are, for some connections,
% displaced from prior expectations (at or around zero).
%
% The following diagnostics are stored in the returned DCM:
%
% DCM.diagnostics(1) - Percent variance explained
% DCM.diagnostics(2) - Largest absolute parameter estimate
% DCM.diagnostics(3) - Effective number of parameters estimated
%
% This routine is compatible with DCM8, DCM10 and DCM12 files.
%__________________________________________________________________________
% Copyright (C) 2012-2013 Wellcome Trust Centre for Neuroimaging

% Karl Friston
% $Id: spm_dcm_fmri_check.m 7639 2019-07-16 14:48:11Z peter $

%-Prepare inputs
%--------------------------------------------------------------------------
if isempty(varargin)
    nograph = false;
else
    nograph = varargin{1};
end

if length(varargin) < 2
    GCM = [];
else
    GCM = varargin{2};
end

%-Load DCM structure
%--------------------------------------------------------------------------
if ~nargin
    [P, sts] = spm_select(1,'^(D|G)CM.*\.mat$','select DCM or GCM mat');
    if ~sts, DCM = []; return; end
end

if isstruct(P)
    DCM = P;
elseif ischar(P)
    DCM = load(P);
    if isfield(DCM,'DCM')
        DCM = DCM.DCM;
    elseif isfield(DCM,'GCM')
        DCM = DCM.GCM;
    else
        error('Unknown DCM format');
    end
elseif iscell(P)
    DCM = P;
end

%-Handle multiple DCMs (group DCM structure)
%--------------------------------------------------------------------------
if iscell(DCM)

    % Prepare figure
    if ~nograph
        datacursormode off;
        f = spm_figure('GetWin','DCM diagnostics'); spm_clf;
        colormap(jet);
        add_title('Loading...',...
                  'Position',[0,0.5,1,0.2], ...
                  'ForegroundColor',[0.7 0.7 0.7]);
        drawnow;
    end

    % Load if filenames given
    if ischar(DCM{1})
        DCM = spm_dcm_load(DCM);
    end

    % Call spm_dcm_fmri_check recursively to assemble diagnostics
    [stats,DCM] = get_diagnostics(DCM);

    if nograph, return; end

    % Extract explained variance
    data = cellfun(@(x)x(1),stats);

    % Add title
    spm_clf; subplot(10,2,1:2); axis off;
    p = get(gca,'Position');
    add_title('DCM for fMRI Diagnostics','Position',[0,p(2)+p(4)/2,1,0.06]);

    % Plot grid of models
    subplot(10,2,3:2:13);
    im = plot_model_space(data, f);

    % Create diagnostic panel
    subplot(10,2,4:2:14); axis off;
    h = create_diagnostic_panel();

    % Store handles and DCM in image
    h.DCM = DCM;
    set(im,'UserData',h);

    % Enable clicks
    datacursormode on;

    % Plot performance over empirical bayes iterations
    if isfield(DCM{1},'FEB')
        subplot(10,3,[25 28]), bar(DCM{1}.FEB(:) - DCM{1}.FEB(1))
        xlabel('iteration','FontSize',12);
        title('Free energy','FontSize',16)
        axis square

        subplot(10,3,[26 29]), bar(cellfun(@mean,DCM{1}.EEB(:)),'b')
        xlabel('iteration','FontSize',12)
        title('Log precision','FontSize',16)
        axis square

        subplot(10,3,[27 30]), bar(DCM{1}.HEB(:) - DCM{1}.HEB(1),'c')
        xlabel('iteration','FontSize',12)
        title('Posterior uncertainty','FontSize',16)
        axis square
    end

    return;
end

% Assemble diagnostics
%==========================================================================

% coefficient of determination (percent variance explained)
%--------------------------------------------------------------------------

% Check if spectral DCM (DCM for cross spectra)
%--------------------------------------------------------------------------
try
    analysis = DCM.options.analysis;
catch
    analysis = '';
end
if strcmp(analysis,'CSD') && isfield(DCM,'Hc')
    PSS   = sum(sum(sum(abs(DCM.Hc).^2)));
    RSS   = sum(sum(sum(abs(DCM.Rc).^2)));
elseif isfield(DCM,'y')
    PSS   = sum(sum(DCM.y.^2));
    RSS   = sum(sum(DCM.R.^2));
else
    PSS   = NaN;
    RSS   = NaN;
end

D(1)  = 100*PSS/(PSS + RSS);

% largest absolute posterior expectation (extrinsic connections)
%--------------------------------------------------------------------------
try
    A = DCM.Ep.A;
catch
    A = DCM.A;
end

if isfield(DCM.options,'two_state') && DCM.options.two_state
    A = exp(A);
end

D(2)  = max(max(abs(A - diag(diag(A)))));

% complexity and effective number of parameters estimated
%--------------------------------------------------------------------------
qE    = spm_vec(DCM.Ep);
pE    = spm_vec(DCM.M.pE);
qC    = DCM.Cp;
pC    = full(DCM.M.pC);
k     = rank(full(pC));
pC    = pinv(pC);

D(3)  = trace(pC*qC) + (pE - qE)'*pC*(pE - qE) - spm_logdet(qC*pC) - k;
D(3)  = D(3)/log(DCM.v);

D     = full(D);
DCM.diagnostics = D;

if nograph
    return;
end

% Plot summary of inversion
%==========================================================================
spm_figure('GetWin','DCM diagnostics'); clf

% back to GCM link if needed
%--------------------------------------------------------------------------
if ~isempty(GCM)
   uicontrol('Style','PushButton','String','Return to models',...
        'Enable','Inactive','ButtonDownFcn',@backbutton_clicked, ...
        'Units','Normalized','Position',[0.04 0.96 0.2 0.03],...
        'HorizontalAlignment','Left','UserData',GCM);
end

% plot predicted and observed regional responses
%--------------------------------------------------------------------------
subplot(2,1,1);

% Check if spectral DCM (DCM for cross spectra)
%--------------------------------------------------------------------------
if strcmp(analysis,'CSD')

    %-CSD data
    %----------------------------------------------------------------------
    Hz   = DCM.Hz;                 % frequencies
    name = {DCM.xY.name};          % names
    ns   = size(DCM.a,1);          % number of regions
    ns   = min(ns,8);              % bounded number of regions

    c = lines(ns);
    h = [];
    for i = 1:ns
        Hc(:,i) = abs(DCM.Hc(:,i,i));
        Yc(:,i) = abs(DCM.Hc(:,i,i) + DCM.Rc(:,i,i));

        h(i)=plot(Hz,Hc(:,i),'Color',c(i,:)); hold on
        plot(Hz,Yc(:,i),':','Color',c(i,:))
    end
    hold off

    str = sprintf('variance explained %0.0f%%', D(1));
    str = {'Responses and Predictions',str};

    if D(1) > 10
        title(str,'FontSize',16);
    else
        title(str,'FontSize',16,'Color','r');
    end

    xlabel('frequency (Hz)')
    ylabel('abs(CSD)')
    axis square, spm_axis tight
    try
        legend(h,name)
    end
else
    t   = (1:DCM.v)*DCM.Y.dt;
    plot(t,DCM.y,t,DCM.y + DCM.R,':');
    str = sprintf('variance explained %0.0f%%', D(1));
    str = {'Responses and Predictions',str};

    if D(1) > 10
        title(str,'FontSize',16);
    else
        title(str,'FontSize',16,'Color','r');
    end

    xlabel('time {seconds}');
end

% posterior densities over A parameters
%--------------------------------------------------------------------------
try
    i = spm_fieldindices(DCM.Ep,'A');
catch
    i = 1 + (1:DCM.n^2);
end
qE  = spm_vec(DCM.Ep);
qC  = DCM.Cp;

if DCM.options.two_state
    qE = exp(qE);
end

subplot(2,2,3)
spm_plot_ci(qE(i),qC(i,i)), hold on
str = sprintf('largest connection strength %0.2f', D(2));
str = {'Intrinsic and Extrinsic connections',str};
if D(2) > 1/8
    title(str,'FontSize',16);
else
    title(str,'FontSize',16,'Color','r');
end
xlabel('parameters');
axis square

% posterior correlations among all parameters
%--------------------------------------------------------------------------
subplot(2,2,4)
imagesc(spm_cov2corr(DCM.Cp))
title('Posterior Correlations','FontSize',16)
str = sprintf('estimable parameters %0.0f', D(3));
str = {'Posterior Correlations',str};
if D(3) > 1
    title(str,'FontSize',16);
else
    title(str,'FontSize',16,'Color','r');
end
axis square

% =========================================================================
function [stats,GCM] = get_diagnostics(GCM)
% Builds a [s x m] cell array of diagnostic stats for an array of DCMs

stats    = cell(size(GCM));
stats(:) = {zeros(1,3)};
[Ns, Nm] = size(GCM);
counter = 1;
for s = 1:Ns
    for m = 1:Nm
        if isfield(GCM{s,m},'Ep')
            GCM{s,m}.v  = GCM{s,1}.v;
            GCM{s,m}    = spm_dcm_fmri_check(GCM{s,m}, true);
            stats{s,m}  = GCM{s,m}.diagnostics;
        else
            stats{s,m}  = zeros(3,1);
        end
        counter = counter + 1;
    end
end

% =========================================================================
function add_title(str,varargin)
% Draws a title
uicontrol('Style','Text','String',str,'Fontsize',20,...
          'Units','Normalized','HorizontalAlignment','Center',...
          'BackgroundColor','w',varargin{:});

% =========================================================================
function im = plot_model_space(data, f)
% Plots the model space. Returns a graphics handle to the image

% Plot explained variances
im = imagesc(data, [0 100]);

[Ns, Nm] = size(data);
set(gca,'xtick', linspace(0.5,Nm+0.5,Nm+1), ...
        'ytick', linspace(0.5,Ns+.5,Ns+1));
set(gca,'xgrid', 'on', 'ygrid', 'on', ...
        'gridlinestyle', '-', 'xcolor', 'w', 'ycolor', 'w');
ylabel('Subjects','FontSize',14,'Color','k');
xlabel('Models','FontSize',14,'Color','k');
title('Variance explained (%)','FontSize',16);
axis equal

% Create small colorbar
cbar = colorbar;
p    = get(cbar,'Position');
t    = p(2) + p(4);
p(2) = t - 0.2;
p(4) = 0.2;
set(cbar,'Position',p);

% Handle mouseclicks
dcm_obj = datacursormode(f);
set(dcm_obj,'UpdateFcn',@gcm_clicked);

% =========================================================================
function h = create_diagnostic_panel()
% Create a panel to show details / controls for the selected model

% Get axes top
p = get(gca,'Position');
t = p(2)+p(4);

% Add panel
he = 0.15; % Height
h = struct();
h.panel = uipanel('Units','normalized',...
'BackgroundColor',[1 1 1],'Title','Diagnostics',...
'Position',[0.5 t-he 0.4 he],'FontSize',12);

% Add explained variance label
h.expvar = uicontrol('Style','text','Units','normalized',...
          'String','Please select a model, left.',...
          'BackgroundColor',[1 1 1],'Position',[0,0.6,1,0.2],...
          'Parent',h.panel,'HorizontalAlignment','center');

% Add button
h.infobutton = uicontrol('Style','pushbutton','Units','normalized',...
          'String','Diagnostics',...
          'Position',[0.1,0.2,0.8,0.25],...
          'Parent',h.panel,'Callback',@info_clicked,'Enable','Off',...
          'Visible','Off');

% =========================================================================
function txt = gcm_clicked(varargin)
% Handle mouseclick on DCM array

% Unpack handles and explained variance matrix
im     = get(varargin{2},'Target');
h      = get(im,'UserData');
expvar = get(im,'CData');

% Get DCM for this click position
xy  = get(varargin{2},'Position');
m   = xy(1);
s   = xy(2);
GCM = h.DCM;
DCM = GCM{s,m};

% Update DCM info panel text
if isnan(expvar(s,m))
    str = 'Variance explained: unavailable';
    set(h.infobutton,'Enable','off');
else
    str = sprintf('Variance explained: %2.2f%%', expvar(s,m));
    set(h.infobutton,'Enable','on');
end
set(h.expvar, 'String', str);
set(h.panel,  'Title', sprintf('Subject %d Model %d',s,m));

% Update DCM info panel button
button_data = struct();
button_data.DCM = DCM;
button_data.GCM = GCM;
set(h.infobutton,'UserData', button_data);
set(h.infobutton,'Visible', 'on');

% Return tooltip
txt = sprintf('Subject %d model %d',s,m);

% =========================================================================
function info_clicked(varargin)
% Callback for the Diagnostics button being clicked

button_data = get(varargin{1},'UserData');
DCM = button_data.DCM;
GCM = button_data.GCM;

if ~isempty(button_data.DCM)
    dcm_obj = datacursormode(gcf);
    set(dcm_obj,'UpdateFcn',[]);
    datacursormode off;
    spm_dcm_fmri_check(DCM, false, GCM);
end

% =========================================================================
function backbutton_clicked(varargin)
% Callback for the back button, to return to the model space
GCM = get(varargin{1},'UserData');
clf; drawnow();
spm_dcm_fmri_check(GCM);


function pot = convert_to_pot(CPD, pot_type, domain, evidence)
% CONVERT_TO_POT Convert a tabular utility node to one or more potentials
% pot = convert_to_pot(CPD, pot_type, domain, evidence)

switch pot_type
 case 'u',
  sz = [CPD.sizes 1]; % the utility node itself has size 1
  pot = upot(domain, sz, 1*myones(sz), myreshape(CPD.T, sz));
 otherwise,
  error(['can''t convert a utility node to a ' pot_type ' potential']);
end


classdef TestAdd
    %TestAdd

    methods (Static)
        function test_rgb_image
            img = cv.imread(fullfile(mexopencv.root(),'test','img001.jpg'), 'ReduceScale',2);
            [h,w,~] = size(img);
            mask = false(h,w);
            mask(100:h-100,100:w-100) = true;

            out = cv.add(img, img);
            validateattributes(out, {class(img)}, {'size',size(img)});
            if mexopencv.require('images')
                expected = my_add(img, img);
                assert(isequal(out, expected));
            end

            out = cv.add(img, img, 'DType','double');
            validateattributes(out, {'double'}, {'size',size(img)});
            if mexopencv.require('images')
                expected = my_add(img, img, 'double');
                assert(isequal(out, expected));
            end

            out = cv.add(img, img, 'Mask',mask);
            validateattributes(out, {class(img)}, {'size',size(img)});
            if mexopencv.require('images')
                expected = my_add(img, img, class(img), mask);
                assert(isequal(out, expected));
            end

            out = cv.add(img, img, ...
                'Dest',img, 'Mask',mask, 'DType',class(img));
            validateattributes(out, {class(img)}, {'size',size(img)});
            if mexopencv.require('images')
                expected = my_add(img, img, class(img), mask, img);
                assert(isequal(out, expected));
            end
        end

        function test_2d_matrix
            M = uint8([100 150; 200 250]);
            mask = true(size(M));
            mask(4) = false;

            out = ones(size(M), 'uint8');
            out = cv.add(M, M, 'Mask',mask, 'Dest',out);
            validateattributes(out, {'uint8'}, {'size',size(M)});
            expected = uint8([200 255; 255 1]);
            assert(isequal(out, expected));

            out = cv.add(M, M, 'Mask',mask);
            validateattributes(out, {'uint8'}, {'size',size(M)});
            expected = uint8([200 255; 255 0]);
            assert(isequal(out, expected));

            out = cv.add(M, M);
            validateattributes(out, {'uint8'}, {'size',size(M)});
            expected = M + M;
            assert(isequal(out, expected));

            out = cv.add(M, 1);
            validateattributes(out, {'uint8'}, {'size',size(M)});
            expected = M + 1;
            assert(isequal(out, expected));

            out = cv.add(1, M);
            validateattributes(out, {'uint8'}, {'size',size(M)});
            expected = 1 + M;
            assert(isequal(out, expected));

            out = cv.add(1, 1);
            validateattributes(out, {'double'}, {'scalar'});
            expected = 1 + 1;
            assert(isequal(out, expected));
        end

        function test_output_depth
            out = cv.add(uint16(1), int8(1), 'DType','single');
            validateattributes(out, {'single'}, {'scalar'});
            assert(isequal(out, 2));
        end

        function test_saturation
            out = cv.add(uint8(200), uint8(200), 'DType','uint8');
            validateattributes(out, {'uint8'}, {'scalar'});
            assert(isequal(out, 255));

            out = cv.add(uint8(200), uint8(200), 'DType','uint16');
            validateattributes(out, {'uint16'}, {'scalar'});
            assert(isequal(out, 400));

            % saturation not applied for int32 (result overflows)
            out = cv.add(int32(1073741824), int32(1073741824), 'DType','int32');
            %validateattributes(out, {'int32'}, {'scalar', '<',0});

            % unlike MATLAB where result saturates
            %out = int32(1073741824) + int32(1073741824);
            %assert(isequal(out, intmax('int32')));
        end

        function test_error_argnum
            try
                cv.add();
                throw('UnitTest:Fail');
            catch e
                assert(strcmp(e.identifier,'mexopencv:error'));
            end
        end
    end

end

function out = my_add(src1, src2, dtype, mask, dst)
    %MY_ADD  Similar to cv.add using imadd from IPT

    if nargin < 3, dtype = class(src1); end
    if nargin < 4, mask = true(size(src1,1),size(src1,2)); end
    if nargin < 5, dst = zeros(size(src1), dtype); end

    % add two images with specified output class
    out = imadd(src1, src2, dtype);

    % apply masking
    if ~isempty(mask)
        for k=1:size(out,3)
            out_slice = out(:,:,k);
            dst_slice = dst(:,:,k);
            out_slice(~mask) = dst_slice(~mask);
            out(:,:,k) = out_slice;
        end
    end
end


function plotExcitationPhase(varargin)
% Plots the excitation force phase for each hydro structure's bodies in
% the heave, surge and pitch degrees of freedom.
%
% Usage:
% ``plotExcitationPhase(hydro, hydro2, hydro3, ...)``
%
% Parameters
% ----------
%     varargin : struct(s)
%         The hydroData structure(s) created by the other BEMIO functions.
%         One or more may be input.
%

if isempty(varargin)
    error(['plotExcitationPhase: No arguments passed. Include one or more hydro ' ...
        'structures when calling: plotExcitationPhase(hydro1, hydro2, ...)']);
end

B=1;  % Wave heading index
figHandle = figure('Position',[950,300,975,521]);
titleString = ['Excitation Force Phase: $$\phi_i(\omega,\theta)$$'];
subtitleString = {'Surge','Heave','Pitch'};
xString = {'$$\omega (rad/s)$$','$$\omega (rad/s)$$','$$\omega (rad/s)$$'};
yString = {['$$\phi_1(\omega,\theta$$',' = ',num2str(varargin{1}.theta(B)),'$$^{\circ})$$'],...
    ['$$\phi_3(\omega,\theta$$',' = ',num2str(varargin{1}.theta(B)),'$$^{\circ}$$)'],...
    ['$$\phi_5(\omega,\theta$$',' = ',num2str(varargin{1}.theta(B)),'$$^{\circ}$$)']};

notes = {''};

numHydro = length(varargin);
for ii = 1:numHydro
    numBod = varargin{ii}.Nb;
    tmp1 = strcat('X',num2str(ii));
    X.(tmp1) = varargin{ii}.w;
    tmp2 = strcat('Y',num2str(ii));
    a = 0;
    for i = 1:numBod
        m = varargin{ii}.dof(i);
        Y.(tmp2)(1,i,:) = squeeze(varargin{ii}.ex_ph(a+1,B,:));
        Y.(tmp2)(2,i,:) = squeeze(varargin{ii}.ex_ph(a+3,B,:));
        Y.(tmp2)(3,i,:) = squeeze(varargin{ii}.ex_ph(a+5,B,:));
        legendStrings{i,ii} = [varargin{ii}.body{i}];
        a = a + m;
    end
end

formatPlot(figHandle,titleString,subtitleString,xString,yString,X,Y,legendStrings,notes)
saveas(figHandle,'Excitation_Phase.png');

end


function test_failed = test_blocprocoffline()

% Scanario 1) Block reading from a wav and block writing to a wav
%
%
inName = 'test_in.wav';
outName = 'test_out.wav';
f = 2*rand(44100,1)*0.9-1;
wavwsave(f,44100,inName);

fs=block(inName,'offline','outfile',outName);

flag = 1;
while flag
   [fb,flag] = blockread();
   blockwrite(fb/2);
end

% Scanario 2) blockwrite from vector to wav
%
%

f = gspi;
f2 = 2*rand(numel(f),1)*0.9-1;

fs = block([f,f2],'fs',44100,'offline','outfile',outName);

flag = 1;
while flag
   [fb,flag] = blockread(44100);
   blockwrite(fb/2);
end

delete(inName);
delete(outName);


report_this_filefun(mfilename('fullpath'));

ax = findobj('Tag','main_map_ax');
[x,y, mouse_points_overlay] = select_polygon(ax);
figure_w_normalized_uicontrolunits(map)

plos2 = plot(x,y,'k-','Linewidth',2);        % plot outline
sum3 = 0.;
pause(0.3)

do = [' s' num2str(k) ' = [ x(1) y(1) ; x(2) y(2) ; x(4) y(4) ; x(3) y(3) ]; '];
eval(do)

if k == 1
    do = [' save peruzones.mat  s' num2str(k) ' k  '];
    eval(do)
else
    do = [' save peruzones.mat  s' num2str(k) ' k  -append  '];
    eval(do)
end

cu = cu+1;
do = [ ' s = s' num2str(k) ' ;' ]; eval(do);
p = s; v = s;
% resort polygons from seisrisk format
if length(s(:,1)) == 4;  p(3,:) = s(4,:); p(4,:) = s(3,:); p = [p ; p(1,:) ];  end
if length(s(:,1)) == 6;  p(3,:) = s(4,:); p(4,:) = s(6,:); p(6,:) = s(3,:); p = [p ; p(1,:) ];end
if length(s(:,1)) == 8;  p(3,:) = s(4,:); p(4,:) = s(6,:); p(5,:) = s(8,:); p(6,:) = s(6,:);  p(7,:) = s(5,:); p(8,:) = s(3,:); p = [p ; p(1,:) ];end

pl = plot(p(:,1),p(:,2),'r');
set(pl,'Linewidth',2)

x = [p(:,1)];
y = [p(:,2)];      %  closes polygon

sum3 = 0.;
XI = a.Longitude;          % this substitution just to make equation below simple
YI = a.Latitude;
    l2 = polygon_filter(x,y, XI, YI, 'inside');
newt2 = a.subset(l2);

if newt2.Count > 10   % nur wenn mindestens 6 EQ in zone

    timeplot

    set(pl,'color','k')
    figure_w_normalized_uicontrolunits(map); hold on;
    plot(newt2.Longitude,newt2.Latitude,'go')
    disp(['This is source zone # ' num2str(k) ]);

    %This adjust the data for the completeness and computes rates per year
    l2 = newt2.Date >= 1963; newt3 = newt2(l2,:);td = 30;

    l = newt3(:,6) >= 4.75 & newt3(:,6) < 5.25;
    r0 = length(newt3(l,6))/td;
    l = newt3(:,6) >= 5.25 & newt3(:,6) < 5.75;
    r1 = length(newt3(l,6))/td;
    l = newt3(:,6) >= 5.75 & newt3(:,6) < 6.25;
    r2 = length(newt3(l,6))/td;

    l2 = newt2.Date >= 1930; newt3 = newt2(l2,:); td = 63;

    l = newt3(:,6) >= 6.25 & newt3(:,6) < 6.75;
    r3 = length(newt3(l,6))/td;
    l = newt3(:,6) >= 6.75 & newt3(:,6) < 7.25;
    r4 = length(newt3(l,6))/td;
    l = newt3(:,6) >= 7.25 & newt3(:,6) < 7.95;
    r5 = length(newt3(l,6))/td;

    if r4 == 0 r4 = r5; end
    if r3 == 0 r3 = r4; end
    if r2 == 0 r2 = r3; end
    if r1 == 0 r1 = r2; end
    if r0 == 0 r0 = r1; end

    r = [r0 r1 r2 r3 r4 r5 ];
    f = min(find(r(2:6) == 0));
    %  if isempty(f) == 0
    %   if f < 6  && f > 1
    %      r(f) = r(f-1)*0.0035
    %  end
    %end
    % write info to file
    % cd /home2/stefan/ZMAP/aspar

    s = ['98   1.     -1          zn9930.00' ]; s = s';
    fprintf(fid2,'%s\n',s);
    s = [num2str(length(v)/2,1) ' 1 1']; s = s';
    fprintf(fid2,'%s\n',s);
    s = [num2str(-v(3,1),5) ' ' num2str(-v(3,2),5) ' ' num2str(-v(4,1),5) ' ' num2str(-v(4,2),5)]; s = s';

    fprintf(fid2,'%s\n',s);
    s = [num2str(-v(1,1),5) ' ' num2str(-v(1,2),5) ' ' num2str(-v(2,1),5) ' ' num2str(-v(2,2),5)]; s = s';

    fprintf(fid2,'%s\n',s);

    anz = [r(1) 5.0 ; r(2) 5.5 ; r(3) 6 ; r(4) 6.5 ; r(5) 7.0 ; r(6) 7.5 ];

    fprintf(fid2,'%7.6f    ',anz(:,1));
    fprintf(fid2,'\n');
    fprintf(fid2,'\n');
    fprintf(fid2,'%3.2f  ',anz(:,2));
    fprintf(fid2,'\n');
end %if at leats 6

ans_ = questdlg('  ',...
    'Define More source zones',...
    'Yes please','No thank you','No' );

switch ans_
    case 'Yes please'
        k = k+1;
        defzones
    case 'No thank you'
        return
end


function Q=getbasematrix(X,ind)
%GETBASEMATRIX Internal function to extract basematrix for variable IND

if ind==0
    base = X.basis(:,1);
    Q = reshape(base,X.dim);
    return;
end

here = find(X.lmi_variables==ind);
if isempty(here)
    error
else
    base = X.basis(:,here+1);
    Q = reshape(base,X.dim);
end


% fmri_glm_design_matrix
%
% Specify and/or create an fmri_glm_design_matrix object. This object is designed to contain
% all the information about a model necessary to create a design matrix
% and, when combined with an fmri_data object, to fit the model.
%
% The information contained in this object (its attributes) are designed to
% be very similar or identical to those defined by SPM in using
% spm_fmri_design.m. This should help with inter-operability and standards
% for storing information.
%
% See methods(fmri_glm_design_matrix) for things you can do with this.
% See the code of this function for additional details about all the
% fields.
%
% The general way to create/initialize CANlab objects is to call them with
% no or minimal input arguments. In this case, TR is required as the first
% input.  After that, pairs of arguments can be entered in the
%'fieldname', value format standard for Matlab inputs. If the fields are
% valid attributes of the object, they will be entered.
%
% For example:
%
% my_model = fmri_glm_design_matrix(2);
% creates an empty fmri_glm_design_matrix object with a TR of 2 (which is used to
% create a default b-spline basis set for the HRF.
%
% my_model = fmri_glm_design_matrix(2, 'nscan', [198 198 198]);
% creates an empty structure but assigns data to the field nscans, number
% of scans per session.
%
% my_model = fmri_glm_design_matrix(TR, 'nscan', nscan, 'units', 'secs', 'onsets', ons_temperature, 'condition_names', names_temperature);
% does the above and also adds onsets and names to the appropriate place
% in the object structure.
% my_model.Sess(1).U(2).name : names for session 1, condition 2
% my_model.Sess(1).U(2).ons : onsets for session 1, condition 2 in UNITS(secs or TRs)
%
% add methods:
% There are some special methods to add specific types of data:
%
% 'onsets', {cell array of onsets for conditions within sessions}
%
% 'condition_names', {cell array of condition names} -- assumed to be the same for all sessions
%
% 'pm', '*name of condition to modulate*', '*modulator name*', {cell with modulators for each session}
%
% You can also specify different basis sets for different conditions, which
% SPM will not allow you to do.  Here is an example of a process of
% creating an fmri_glm_design_matrix object from onsets, etc., building it, and then
% replacing the basis set for one event type with another one.
%
% reportmod_model = fmri_glm_design_matrix(TR, 'nscan', nscan, 'units', 'secs', 'onsets', ons_reportmod, ...
% 'condition_names', names_reportmod, 'pm', PM, 'pmnames', PM_names);
%
% reportmod_model = build(reportmod_model);
% plot(reportmod_model)
%
% % Generate a new basis set for the Anticipation conditions (condition 1)
% [xBF_hires, xBF] = fmri_spline_basis(2, 'length', 12, 'nbasis', 3, 'order', 3, 'plot');
% reportmod_model = replace_basis_set(reportmod_model, 1, xBF_hires);
% reportmod_model = build(reportmod_model);
% plot(reportmod_model)
%

%    SPM.Sess(s)
%            U: - Input structure array
%            C: - User specified covariate structure
%          row: - scan   indices for session s
%          col: - effect indices for session s
%           Fc: - F Contrast information for input-specific effects
%
%    SPM.xX
%            X: - design matrix
%           iH: - vector of H partition (indicator variables) indices
%           iC: - vector of C partition (covariates)          indices
%           iB: - vector of B partition (block effects)       indices
%           iG: - vector of G partition (nuisance variables)  indices
%         name: - cellstr of names for design matrix columns
%

%        3rd level
%        ------------------------------------------------------------------
%        SPM.Sess(s).U
%               dt: - time bin length {seconds}
%             name: - {1 x j} cell of names for each input or cause
%              ons: - (q x 1) onsets for q  trials {in UNITS}
%              dur: - (q x 1) durations for trials {in UNITS}
%                P: - Parameter stucture
%                u: - (t x j) inputs or stimulus function matrix
%              pst: - (1 x k) peristimulus times (seconds)
%
%
%        SPM.Sess(s).C
%
%                C: - [kx1 double] of user specified regressors
%             name: - {1xk} cellstr of regressor names
%
%
%        SPM.Sess(s).Fc
%
%                i: - F Contrast colums for input-specific effects
%             name: - F Contrast names  for input-specific effects
%
%
%            4th level
%            --------------------------------------------------------------
%            SPM.Sess(s).U(i).P(p)
%
%
%                 name: - parameter name
%                    P: - (q x 1) parameter matrix
%                    h: - order of polynomial expansion (0 = none)
%                    i: - sub-indices of U(i).u for plotting

classdef fmri_glm_design_matrix

    properties

        TR = NaN;

        % custom: not in SPM
        build_method
        history

        % 1st level
        % --------------------------------------------------------------------------
        % SPM.
        xY % : [1x1 struct] - data structure
        nscan % : [1xs double] - nscan(s) = number of scans in session s
        xBF % : [1x1 struct] - Basis function structure
        Sess % : [1xs struct] - Session structure array
        xX % : [1x1 struct] - Design matrix structure

    end % properties

    methods

        % Class constructor
        function obj = fmri_glm_design_matrix(varargin)
            %
            % [obj, cl_with_averages] = fmri_data(image_names, mask_image, varargin)
            %
            % Reads a set of image files and a mask image, and returns
            % an fmri_data object with data for all in-mask voxels.

            % ---------------------------------
            % Create empty fmri_data object, and return if no additional
            % arguments
            % ---------------------------------

%             if nargin == 0
%                 error('Must define TR, repetition time for scans, as first input.')
%             end

            if nargin > 0
                obj.TR = varargin{1};
            end

            obj.build_method = 'Separate sessions';

            obj.xY  = [];   % : [1x1 struct] - data structure
            obj.nscan = []; % : [1xs double] - nscan(s) = number of scans in session s
            obj.xBF = [];   % : [1x1 struct] - Basis function structure
            obj.Sess = [];  % : [1xs struct] - Session structure array
            obj.xX = [];

            % Default basis set
            %    ----------------------------------------------------------------------
            obj.xY.RT = obj.TR; % : - repetition time {seconds)

            obj.xBF = fmri_spline_basis(obj.TR, 0);
            % obj.xBF.name: - name of basis set
            % obj.xBF.length: - support of basis set {seconds}
            % obj.xBF.order: - order of basis set
            % obj.xBF.bf: - basis set matrix
            % obj.xBF.dt = TR ./ 16; % : - length of time bin {seconds}

            obj.xBF.T = 16; % : - number of time bins per scan
            obj.xBF.T0 = 1; % : - first time bin (see slice timing)
            obj.xBF.UNITS = [];  %: - 'scans'|'secs' - units in which onsets are specified
            obj.xBF.Volterra = 1; % : - 1|2 - order of [Volterra] convolution

            % Parameters for parametric modulation
            P = struct('name', '', 'P', [], 'h', 0, 'dur', [], 'i', []);

            % Onset structure
            U = struct('dt', obj.TR ./ obj.xBF.T , 'name', {}, 'ons', [], 'dur', 1, 'P', P, 'u', [], 'pst', []);

            % Covariate structure
            C = struct('C', [], 'name', {'User-specified regressors here'});

            % Session structure
            S = struct('U', U, 'C', C, 'row', [], 'col', [], 'Fc', []);

            obj.Sess = S;

            % Design structure
            obj.xX = struct('X', [], 'iH', [], 'iC', [], 'iB', [], 'iG', [], 'name', {});

            % The code below can be generic to any class definition
            % It parses 'fieldname', value pairs of inputs
            % and returns a warning if unexpected strings are found.

            if nargin == 1
                return
            end

            % all valid fieldnames
            valid_names = fieldnames(obj);

            for i = 1:length(varargin)
                if ischar(varargin{i})

                    % Look for a field (attribute) with the input name
                    wh = strmatch(varargin{i}, valid_names, 'exact');

                    % behaviors for valid fields
                    if ~isempty(wh)

                        obj.(varargin{i}) = varargin{i + 1};

                        % eliminate strings to prevent warnings on char
                        % inputs
                        if ischar(varargin{i + 1})
                            varargin{i + 1} = [];
                        end

                        % special methods for specific fields
                        switch varargin{i}

                        end

                    else
                        % Unique to this method: special subfields/other valid
                        % entries
                        % Try to add using the add method, which returns a
                        % warning if the field name is invalid.

                        obj = add(obj, varargin{i}, varargin{i + 1});

                        varargin{i + 1} = []; % eliminate to avoid confusing the parsing

                    end % not empty
                end % string input
            end % process inputs

        end % class constructor function

    end % properties

end % classdef


classdef ShFunc_Chomog_EnforceCh_CCstar_eq < ShFunc_Chomog_EnforceCh
    properties
        component
        initial_value = 1;
    end
    methods
        function obj=ShFunc_Chomog_EnforceCh_CCstar_eq(settings,n)
            obj.init(settings);
            obj.compute_Ch_star(settings.TOL, settings.selectiveC_Cstar);
            obj.component = n;
        end

        function computeCostAndGradient(obj,x)
            obj.computePhysicalData(x);
            obj.computeCCstar(x);

            obj.value = obj.value(obj.component);
            obj.gradient = obj.gradient(:,obj.component);
            obj.value = obj.value/obj.initial_value;
            obj.gradient = obj.gradient/obj.initial_value;
            obj.passFilter();
        end
    end
end


%COLAMD_DEMO demo for colamd, column approx minimum degree ordering algorithm
%
% Example:
%   colamd_demo
%
% The following m-files and mexFunctions provide alternative sparse matrix
% ordering methods for MATLAB.  They are typically faster (sometimes much
% faster) and typically provide better orderings than their MATLAB counterparts:
%
%       colamd          a replacement for colmmd.
%
%                       Typical usage:  p = colamd (A) ;
%
%       symamd          a replacement for symmmd.  Based on colamd.
%
%                       Typical usage:  p = symamd (A) ;
%
% For a description of the methods used, see the colamd.c file.
%
% http://www.cise.ufl.edu/research/sparse/colamd/
%
% See also colamd, symamd

% Minor changes:  in MATLAB 7, symmmd and colmmd are flagged as "obsolete".
% This demo checks if they exist, so it should still work when they are removed.

%    Copyright 1998-2007, Timothy A. Davis, and Stefan Larimore
%    Developed in collaboration with J. Gilbert and E. Ng.

%-------------------------------------------------------------------------------
% Print the introduction, the help info, and compile the mexFunctions
%-------------------------------------------------------------------------------

fprintf (1, '\n-----------------------------------------------------------\n') ;
fprintf (1, 'Colamd2/symamd2 demo.') ;
fprintf (1, '\n-----------------------------------------------------------\n') ;
help colamd_demo ;

fprintf (1, '\n-----------------------------------------------------------\n') ;
fprintf (1, 'Colamd help information:') ;
fprintf (1, '\n-----------------------------------------------------------\n') ;
help colamd2 ;

fprintf (1, '\n-----------------------------------------------------------\n') ;
fprintf (1, 'Symamd help information:') ;
fprintf (1, '\n-----------------------------------------------------------\n') ;
help symamd2 ;

%-------------------------------------------------------------------------------
% Solving Ax=b
%-------------------------------------------------------------------------------

n = 100 ;
fprintf (1, '\n-----------------------------------------------------------\n') ;
fprintf (1, 'Solving Ax=b for a small %d-by-%d random matrix:', n, n) ;
fprintf (1, '\n-----------------------------------------------------------\n') ;
fprintf (1, '\nNote: Random sparse matrices are AWFUL test cases.\n') ;
fprintf (1, 'They''re just easy to generate in a demo.\n') ;

% set up the system

rand ('state', 0) ;
randn ('state', 0) ;
spparms ('default') ;
A = sprandn (n, n, 5/n) + speye (n) ;
b = (1:n)' ;

fprintf (1, '\n\nSolving via lu (PAQ = LU), where Q is from colamd2:\n') ;
q = colamd2 (A) ;
I = speye (n) ;
Q = I (:, q) ;
[L,U,P] = lu (A*Q) ;
fl = luflops (L, U) ;
x = Q * (U \ (L \ (P * b))) ;
fprintf (1, '\nFlop count for [L,U,P] = lu (A*Q):          %d\n', fl) ;
fprintf (1, 'residual:                                     %e\n', norm (A*x-b));

try
    fprintf (1, '\n\nSolving via lu (PAQ = LU), where Q is from colmmd:\n') ;
    q = colmmd (A) ;
    I = speye (n) ;
    Q = I (:, q) ;
    [L,U,P] = lu (A*Q) ;
    fl = luflops (L, U) ;
    x = Q * (U \ (L \ (P * b))) ;
    fprintf (1, '\nFlop count for [L,U,P] = lu (A*Q):          %d\n', fl) ;
    fprintf (1, 'residual:                                     %e\n', ...
	norm (A*x-b)) ;
catch
    fprintf (1, 'colmmd is obsolete; test skipped\n') ;
end

fprintf (1, '\n\nSolving via lu (PA = LU), without regard for sparsity:\n') ;
[L,U,P] = lu (A) ;
fl = luflops (L, U) ;
x = U \ (L \ (P * b)) ;
fprintf (1, '\nFlop count for [L,U,P] = lu (A*Q):          %d\n', fl) ;
fprintf (1, 'residual:                                     %e\n', norm (A*x-b));

%-------------------------------------------------------------------------------
% Large demo for colamd2
%-------------------------------------------------------------------------------

fprintf (1, '\n-----------------------------------------------------------\n') ;
fprintf (1, 'Large demo for colamd2 (symbolic analysis only):') ;
fprintf (1, '\n-----------------------------------------------------------\n') ;

rand ('state', 0) ;
randn ('state', 0) ;
spparms ('default') ;
n = 1000 ;
fprintf (1, 'Generating a random %d-by-%d sparse matrix.\n', n, n) ;
A = sprandn (n, n, 5/n) + speye (n) ;

fprintf (1, '\n\nUnordered matrix:\n') ;
lnz = symbfact (A, 'col') ;
fprintf (1, 'nz in Cholesky factors of A''A:            %d\n', sum (lnz)) ;
fprintf (1, 'flop count for Cholesky of A''A:           %d\n', sum (lnz.^2)) ;

tic ;
p = colamd2 (A) ;
t = toc ;
lnz = symbfact (A (:,p), 'col') ;
fprintf (1, '\n\nColamd run time:                          %f\n', t) ;
fprintf (1, 'colamd2 ordering quality: \n') ;
fprintf (1, 'nz in Cholesky factors of A(:,p)''A(:,p):  %d\n', sum (lnz)) ;
fprintf (1, 'flop count for Cholesky of A(:,p)''A(:,p): %d\n', sum (lnz.^2)) ;

try
    tic ;
    p = colmmd (A) ;
    t = toc ;
    lnz = symbfact (A (:,p), 'col') ;
    fprintf (1, '\n\nColmmd run time:                          %f\n', t) ;
    fprintf (1, 'colmmd ordering quality: \n') ;
    fprintf (1, 'nz in Cholesky factors of A(:,p)''A(:,p):  %d\n', sum (lnz)) ;
    fprintf (1, 'flop count for Cholesky of A(:,p)''A(:,p): %d\n', ...
	sum (lnz.^2)) ;
catch
    fprintf (1, 'colmmd is obsolete; test skipped\n') ;
end

%-------------------------------------------------------------------------------
% Large demo for symamd2
%-------------------------------------------------------------------------------

fprintf (1, '\n-----------------------------------------------------------\n') ;
fprintf (1, 'Large demo for symamd2 (symbolic analysis only):') ;
fprintf (1, '\n-----------------------------------------------------------\n') ;

fprintf (1, 'Generating a random symmetric %d-by-%d sparse matrix.\n', n, n) ;
A = A+A' ;

fprintf (1, '\n\nUnordered matrix:\n') ;
lnz = symbfact (A, 'sym') ;
fprintf (1, 'nz in Cholesky factors of A:       %d\n', sum (lnz)) ;
fprintf (1, 'flop count for Cholesky of A:      %d\n', sum (lnz.^2)) ;

tic ;
p = symamd2 (A) ;
t = toc ;
lnz = symbfact (A (p,p), 'sym') ;
fprintf (1, '\n\nSymamd run time:                   %f\n', t) ;
fprintf (1, 'symamd2 ordering quality: \n') ;
fprintf (1, 'nz in Cholesky factors of A(p,p):  %d\n', sum (lnz)) ;
fprintf (1, 'flop count for Cholesky of A(p,p): %d\n', sum (lnz.^2)) ;

try
    tic ;
    p = symmmd (A) ;
    t = toc ;
    lnz = symbfact (A (p,p), 'sym') ;
    fprintf (1, '\n\nSymmmd run time:                   %f\n', t) ;
    fprintf (1, 'symmmd ordering quality: \n') ;
    fprintf (1, 'nz in Cholesky factors of A(p,p):  %d\n', sum (lnz)) ;
    fprintf (1, 'flop count for Cholesky of A(p,p): %d\n', sum (lnz.^2)) ;
catch
    fprintf (1, 'symmmd is obsolete\n') ;
end


function makecmap(bins,fighandle)
    %  MAKECMAP Interactive colormap maker.
    %
    %     usage:    makecmap
    %               makecmap(map)
    %               makecmap(map,fighandle)
    %               makecmap(bins)
    %    		makecmap(bins,fighandle)
    %		makecmap(fighandle,'fig')
    %
    %       bins - size of colormap (default - 64)
    %       map - rgb colormap (matrix)
    %       fighandle - figure(s); to apply colormap (optional)
    %	fighandle,'fig' - reads colormap from figure (fighandle)
    %
    %
    %     Nodes are displayed as circles. To move a node use mouse
    %       button #1. To add a node use mouse button #2. To delete use
    %       button #3.
    %
    %    Mouse buttons     button 1 - move    (3 button mouse)
    %                      button 2 - add
    %                      button 3 - erase
    %
    %    There are four graphs. The first three corresond to the relative
    %       rgb values. And the fourth graph is a luminance factor
    %       which the rgb values are multiplied by.
    %
    %     colormap = [red,green,blue] * luminance
    %
    %    Reset button - resets the colormap to the original values.
    %    Export button - assigns the colormap to a desktop variable.
    %    Close button - closes the figure window.
    %
    %    Runs under Matlab 5
    %

    % Note: the readcolormap option is not perfect. It works well if the
    % colormap contains straight lines like most matlab colormaps. You can play
    % with the tolerance. Also, the more nodes in an axes the slower the mouse
    % handler routines will run.

    % Written by Colin Humphries, Salk Institute, March 1997
    %             colin@salk.edu
    %

    % TODO untangle the confusing global situation -CGR

    %report_this_filefun();

    nargs = nargin;

    if nargs == 0
        bins = 64;
        nargs = 1;
    end

    if ~ischar(bins)

        if size(bins,2) == 3
            map = bins;
            bins = size(map,1);
            if nargs == 1
                fighandle = [];
            end
        else
            map = [];
            if nargs == 2
                if ischar(fighandle)
                    fighandle = bins;
                    map = get(fighandle,'Colormap');
                    bins = size(map,1);
                end
            else
                fighandle = [];
            end
        end

        if isempty(map)
            red = [1 0;bins 1];       % default colormap
            green = [1 0;bins 1];
            blue = [1 0;bins 1];
        else
            % Note: this routine cycles through all
            % the data points and assigns nodes to
            % the points where straight lines end.
            % This does not work well in every
            % occasion. If the colormap is nonlinear
            % in many places, a lot of nodes will be
            % assigned.

            for j = 1:3           % cycle through each column
                for i = 1:bins      % cycle through each row
                    if i == 1         % assign the first point as the first node
                        nodes(1,:) = [1 map(1,j)];
                        lastnode = nodes;   % last node assigned
                    elseif i == 2
                        oldtempnode = [i map(2,j)]; % assigns point 2 as the test node
                    else
                        tempnode = [i map(i,j)];    % look at current point
                        if (abs((oldtempnode(2)-lastnode(2))/(oldtempnode(1)...
                                -lastnode(1))) <= abs((tempnode(2)-lastnode(2))...
                                /(tempnode(1)-lastnode(1)))*1.01) & ...
                                (abs((oldtempnode(2)-lastnode(2))/...
                                (oldtempnode(1)-lastnode(1))) >= ...
                                abs((tempnode(2)-lastnode(2))/...
                                (tempnode(1)-lastnode(1)))*.99) % Check whether the line
                            % from the last node to
                            % tempnode and
                            % oldtempnode have the
                            % same slope.
                            % Tolerance is +/- 1%

                            oldtempnode = tempnode;    % if so then move oldtempnode
                        else
                            nodes = [nodes;oldtempnode]; % if not then assign a new
                            lastnode = oldtempnode;      % node.
                            oldtempnode = tempnode;
                        end
                    end
                end
                nodes = [nodes;bins map(bins,j)];  % the last node is the last point
                if j == 1
                    red = nodes;  % get red nodes
                    nodes = [];
                elseif j == 2
                    green = nodes;% get green nodes
                    nodes = [];
                elseif j == 3
                    blue = nodes; % get blue nodes
                    nodes = [];
                end
            end
        end

        mcmfighandle = figure_w_normalized_uicontrolunits('color','k');

        if isempty(fighandle)
            fighandle = mcmfighandle;
        end

        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        % Set up Colormap from nodes
        %   Converts each set of nodes into a discrete vector

        for i = 1:size(red,1)-1
            W = linspace(red(i,2),red(i+1,2),red(i+1,1)-red(i,1)+1);
            mapred(red(i,1):red(i+1,1)-1) = W(1:red(i+1,1)-red(i,1))';
        end
        mapred(red(i+1,1)) = red(i+1,2);
        for i = 1:size(green,1)-1
            W = linspace(green(i,2),green(i+1,2),green(i+1,1)-green(i,1)+1);
            mapgreen(green(i,1):green(i+1,1)-1) = W(1:green(i+1,1)-green(i,1))';
        end
        mapgreen(green(i+1,1)) = green(i+1,2);
        for i = 1:size(blue,1)-1
            W = linspace(blue(i,2),blue(i+1,2),blue(i+1,1)-blue(i,1)+1);
            mapblue(blue(i,1):blue(i+1,1)-1) = W(1:blue(i+1,1)-blue(i,1))';
        end
        mapblue(blue(i+1,1)) = blue(i+1,2);
        map = [mapred(:),mapgreen(:),mapblue(:)]; % get new colormap

        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        % Set up Graphs

        nodenum = size(red,1);
        subplot(3,2,1)                 % Red Graph
        set(gca,'NextPlot','add')
        for i = 1:nodenum-1
            plot(red(i,1),red(i,2),'ow')
            line([red(i,1),red(i+1)],[red(i,2),red(i+1,2)],'color','r')
        end
        plot(red(nodenum,1),red(nodenum,2),'ow')
        axis([1 red(nodenum,1) 0 1])
        redax = gca;
        set(redax,'UserData',red,'tag','r','box','on','color','k',...
            'xcolor','w','ycolor','w','xgrid','on','ygrid','on',...
            'Ytick',(0:.2:1));
        ylabel('Red','FontSize',14)

        subplot(3,2,3)                % Green Graph
        nodenum = size(green,1);
        set(gca,'NextPlot','add')
        for i = 1:nodenum-1
            plot(green(i,1),green(i,2),'ow')
            line([green(i,1),green(i+1)],[green(i,2),green(i+1,2)],'color','g')
        end
        plot(green(nodenum,1),green(nodenum,2),'ow')
        axis([1 green(nodenum,1) 0 1])
        greenax = gca;
        set(greenax,'UserData',green,'tag','g','box','on','color','k',...
            'xcolor','w','ycolor','w','xgrid','on','ygrid','on',...
            'YTick',(0:.2:1));
        ylabel('Green','FontSize',14)

        subplot(3,2,5)                % Blue Graph
        nodenum = size(blue,1);
        set(gca,'NextPlot','add')
        for i = 1:nodenum-1
            plot(blue(i,1),blue(i,2),'ow')
            line([blue(i,1),blue(i+1)],[blue(i,2),blue(i+1,2)],'color','b')
        end
        plot(blue(nodenum,1),blue(nodenum,2),'ow')
        axis([1 blue(nodenum,1) 0 1])
        blueax = gca;
        set(blueax,'UserData',blue,'tag','b','box','on','color','k',...
            'xcolor','w','ycolor','w','xgrid','on','ygrid','on',...
            'YTick',(0:.2:1));
        ylabel('Blue','FontSIze',14)

        colormap(map)                % Apply Colormap
        set(fighandle,'Colormap',map)

        transax = axes('Position',[.578 .4056 .327 .2238]); % Transfer Graph
        set(gca,'NextPlot','add')
        trans = [1 1;bins 1];
        nodenum = 2;
        cla
        for i = 1:nodenum-1
            plot(trans(i,1),trans(i,2),'ow')
            line([trans(i,1),trans(i+1)],[trans(i,2),trans(i+1,2)],'color','y')
        end
        plot(trans(nodenum,1),trans(nodenum,2),'ow')
        axis([1 trans(nodenum,1) 0 1])
        trans = ones(1,bins);
        title('luminance','color','w','FontSize',14)
        set(transax,'UserData',[1 1;bins 1],'tag','y','box','on','color','k',...
            'xcolor','w','ycolor','w','xgrid','on','ygrid','on',...
            'YTick',(0:.2:1))
        set(mcmfighandle,'UserData',[map,trans(:)],'tag',int2str(fighandle))

        cbax = axes('Position',[.578 .75 .327 .1072]);  % Colorbar Graph
        colorbar(cbax)
        set(cbax,'tag','cb','xcolor','w','ycolor','w',...
            'UserData',[size(red,1),0;...
            size(green,1),0;...
            size(blue,1),0;...
            red;...
            green;...
            blue])

        % Title axis

        hdaxes = axes('Position',[.57 .93 .327 .05],'Visible','off',...
            'tag','hd','UserData',map);
        text(.5,0,'Colormap Editor','FontSize',16,'Color','w',...
            'HorizontalAlignment','center')

        % Uicontrols

        uicontrol('style','pushbutton','string','Reset',...
            'Units','Normalized',...
            'Position',[.55 .0929 .1071 .0595],...
            'callback',@callbackfun_001)

        uicontrol('style','pushbutton','string','Export',...
            'Units','Normalized',...
            'Position',[.675 .0929 .1071 .0595],...
            'callback',@callbackfun_002)

        uicontrol('style','pushbutton','string','Close',...
            'Units','Normalized',...
            'Position',[.80 .0929 .1071 .0595],...
            'callback',@callbackfun_003)

        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        % Set up callbacks

        set(mcmfighandle,'WindowButtonDownFcn','makecmap(''down'');')
        set(mcmfighandle,'WindowButtonUpFcn','makecmap(''up'');')
        set(mcmfighandle,'WindowButtonMotionFcn','makecmap(''motion'');')
        set(mcmfighandle,'CloseRequestFcn','makecmap(''close'');')

        % End of main function
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    else
        if strcmp(bins,'down')           % Mouse Button Down Handler
            figh = gcbf;
            axhandle = gca;
            lcolor = get(axhandle,'tag');  % find out what axis we are in
            if strcmp(lcolor,'cb') | strcmp(lcolor,'hd')
                return           % if colorbar or title axis then return
            end
            xlimits = get(axhandle,'Xlim');
            ylimits = get(axhandle,'Ylim');
            nodes = get(axhandle,'UserData');
            nodenum = size(nodes,1);      % get nodes
            P = get(axhandle,'CurrentPoint'); % get mouse position
            X = P(1,1);
            Y = P(1,2);
            button = get(gcbf,'SelectionType'); % get button
            if X <= xlimits(1)-xlimits(2)*.05 || X >= xlimits(2)*1.05 || ...
                    Y <= ylimits(1)-ylimits(2)*.07 || Y >= ylimits(2)*1.07
                return    % if outside of axis limits then return
            end

            if strcmp(button,'normal')    % left mouse button
                global M_BUTTON_DOWN M_PNTS M_LINES M_TEXT
                ii = find(X > nodes(:,1));  % find node above point
                minnode = max(ii);
                ii = find(X < nodes(:,1));  % find node below point
                maxnode = min(ii);
                if (X - nodes(minnode,1)) > (nodes(maxnode,1)-X) % if closer to maxnode
                    if maxnode == nodenum;     % if maxnode is the endnode
                        nodes(maxnode,2) = max(min(Y,1),0);  % only move Y-position
                    else
                        nodes(maxnode,1) = round(X);         % move node
                        nodes(maxnode,2) = max(min(Y,1),0);
                    end
                    M_BUTTON_DOWN = maxnode;               % save what node was selected
                elseif (X - nodes(minnode,1)) < (nodes(maxnode,1)-X)% if closer to minnode
                    if minnode == 1     %if firstnode
                        nodes(minnode,2) = max(min(Y,1),0); % only move Y-position
                    else
                        nodes(minnode,1) = round(X);        % move node
                        nodes(minnode,2) = max(min(Y,1),0);
                    end
                    M_BUTTON_DOWN = minnode;              % save what node was selected
                end
                cla
                for i = 1:nodenum-1                 % Redraw axis
                    M_PNTS(i) = plot(nodes(i,1),nodes(i,2),'ow');
                    M_LINES(i) = line([nodes(i,1),nodes(i+1)],...
                        [nodes(i,2),nodes(i+1,2)],'color',lcolor);
                end
                M_PNTS(i+1) = plot(nodes(nodenum,1),nodes(nodenum,2),'ow');

                M_TEXT = text(0,1.05,...
                    [' ',int2str(nodes(M_BUTTON_DOWN,1)),', ',...
                    num2str(nodes(M_BUTTON_DOWN,2),2)],...
                    'Color','w','clipping','off',...
                    'VerticalAlignment','bottom',...
                    'FontSize',10);

                axis([1 nodes(nodenum,1) 0 1])

            elseif strcmp(button,'extend')     % Middle Mouse Button
                %global M_BUTTON_DOWN M_PNTS M_LINES M_TEXT

                ii = find(X > nodes(:,1));       % find node below
                minnode = max(ii);
                ii = find(X < nodes(:,1));       % find node above
                maxnode = min(ii);
                nodes = [nodes(1:minnode,:);[round(X),max(min(Y,1),0)];...
                    nodes(maxnode:nodenum,:)];   % add node shifting those above
                nodenum = size(nodes,1);
                M_BUTTON_DOWN = minnode+1;
                cla
                for i = 1:nodenum-1              % Redraw axis
                    M_PNTS(i) = plot(nodes(i,1),nodes(i,2),'ow');
                    M_LINES(i) = line([nodes(i,1),nodes(i+1)],...
                        [nodes(i,2),nodes(i+1,2)],'color',lcolor);
                end
                M_PNTS(i+1) = plot(nodes(nodenum,1),nodes(nodenum,2),'ow');
                M_TEXT = text(0,1.05,...
                    [' ',int2str(nodes(M_BUTTON_DOWN,1)),', ',...
                    num2str(nodes(M_BUTTON_DOWN,2),2)],...
                    'Color','w','clipping','off',...
                    'VerticalAlignment','bottom',...
                    'FontSize',10);

                axis([1 nodes(nodenum,1) 0 1])

            elseif strcmp(button,'alt')          % Right Mouse Button
                ii = find(X > nodes(:,1));         % find node below
                minnode = max(ii);
                ii = find(X < nodes(:,1));         % find node above
                maxnode = min(ii);
                if (X - nodes(minnode,1)) > (nodes(maxnode,1)-X)    % reassign nodes
                    if maxnode < nodenum
                        nodes = [nodes(1:maxnode-1,:);nodes(maxnode+1:nodenum,:)];
                    end
                elseif (X - nodes(minnode,1)) < (nodes(maxnode,1)-X)
                    if minnode > 1
                        nodes = [nodes(1:minnode-1,:);nodes(minnode+1:nodenum,:)];
                    end
                end
                nodenum = size(nodes,1);
                cla
                for i = 1:nodenum-1       %redraw axis
                    plot(nodes(i,1),nodes(i,2),'ow')
                    line([nodes(i,1),nodes(i+1)],[nodes(i,2),nodes(i+1,2)],'color',lcolor)
                end
                plot(nodes(nodenum,1),nodes(nodenum,2),'ow')
                axis([1 nodes(nodenum,1) 0 1])
            end
            set(axhandle,'UserData',nodes)  % update nodes

            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        elseif strcmp(bins,'up')            % Mouse Button Up Handler
            figh = gcbf;
            %global M_TEXT
            delete(M_TEXT)
            clear global M_BUTTON_DOWN M_LINES M_PNTS M_TEXT % clear variables
            UserData = get(figh,'UserData');
            fighandle = str2num(get(figh,'tag')); % get figure to apply colormap
            axhandle = gca;
            nodes = get(axhandle,'UserData');    % get nodes
            tagval = get(axhandle,'tag');
            if strcmp(tagval,'cb') | strcmp(tagval,'hd')
                return   % if colorbar or title axis then return
            end
            for i = 1:size(nodes,1)-1
                W = linspace(nodes(i,2),nodes(i+1,2),nodes(i+1,1)-nodes(i,1)+1);
                map(nodes(i,1):nodes(i+1,1)-1) = W(1:nodes(i+1,1)-nodes(i,1))';
            end
            map(nodes(i+1,1)) = nodes(i+1,2);
            if strcmp(tagval,'r')
                UserData(:,1) = map';
            elseif strcmp(tagval,'g')
                UserData(:,2) = map';
            elseif strcmp(tagval,'b')
                UserData(:,3) = map';
            elseif strcmp(tagval,'y')
                UserData(:,4) = map';
            end
            set(figh,'UserData',UserData,'Colormap',...      % assign new colormap
                UserData(:,1:3).*(UserData(:,4)*ones(1,3)))
            if fighandle ~= figh
                set(fighandle,'Colormap',UserData(:,1:3).*(UserData(:,4)*ones(1,3)))
            end

            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        elseif strcmp(bins,'motion')      % Mouse Motion Handler
            %global M_BUTTON_DOWN M_LINES M_PNTS M_TEXT
            if isempty(M_BUTTON_DOWN)
                return     % If mouse button is not down then return
            end
            axhandle = gca;
            nodes = get(gca,'UserData');
            tagval = get(gca,'tag');
            P = get(axhandle,'CurrentPoint');
            X = P(1,1);
            Y = P(1,2);
            nodenum = size(nodes,1);
            if M_BUTTON_DOWN == 1 | M_BUTTON_DOWN == nodenum % move selected node to
                nodes(M_BUTTON_DOWN,2) = max(min(Y,1),0);       % new mouse position
            else
                nodes(M_BUTTON_DOWN,1) = max(nodes(M_BUTTON_DOWN-1,1), ...
                    min(nodes(M_BUTTON_DOWN+1,1),round(X)));
                nodes(M_BUTTON_DOWN,2) = max(min(Y,1),0);
            end

            delete(M_PNTS(M_BUTTON_DOWN))
            M_PNTS(M_BUTTON_DOWN) = plot(nodes(M_BUTTON_DOWN,1),...
                nodes(M_BUTTON_DOWN,2),'ow');
            if M_BUTTON_DOWN > 1
                delete(M_LINES(M_BUTTON_DOWN-1))
                M_LINES(M_BUTTON_DOWN-1) = line([nodes(M_BUTTON_DOWN-1,1),...
                    nodes(M_BUTTON_DOWN,1)],...
                    [nodes(M_BUTTON_DOWN-1,2),nodes(M_BUTTON_DOWN,2)],'color',tagval);
            end
            if M_BUTTON_DOWN < nodenum
                delete(M_LINES(M_BUTTON_DOWN))
                M_LINES(M_BUTTON_DOWN) = line([nodes(M_BUTTON_DOWN,1),...
                    nodes(M_BUTTON_DOWN+1,1)],...
                    [nodes(M_BUTTON_DOWN,2),nodes(M_BUTTON_DOWN+1,2)],'color',tagval);
            end

            delete(M_TEXT)
            M_TEXT = text(0,1.05,...
                [' ',int2str(nodes(M_BUTTON_DOWN,1)),', ',...
                num2str(nodes(M_BUTTON_DOWN,2),2)],...
                'Color','w','clipping','off',...
                'VerticalAlignment','bottom',...
                'FontSize',10);

            axis([1 nodes(nodenum,1) 0 1])
            set(axhandle,'UserData',nodes)

        elseif strcmp(bins,'export')   % export colormap to desktop
            fig = gcbf;
            pos = get(fig,'Position');
            figx = 400;                  % set up dialog figure
            figy = 200;
            figh = figure_w_normalized_uicontrolunits('Units','pixels',...
                'Position',...
                [pos(1)+pos(3)/2-figx/2 pos(2)+pos(4)/2-figy/2 figx figy],...
                'Resize','off','CloseRequestFcn','',...
                'numbertitle','off');
            uicolor = get(figh,'Color');

            % text uicontrol
            uicontrol('Style','Text','Units','Pixels',...
                'String','Output Colormap to Desktop Variable:',...
                'Position',[20 figy-40 300 22],'HorizontalAlignment','left',...
                'FontSize',14,'BackGroundColor',uicolor)

            % edit uicontrol
            ui1 = uicontrol('Style','Edit','Units','Pixels',...
                'String','cmap','FontSize',12,...
                'Position',[120 figy-100 150 30]);

            % OK Button
            uicontrol('Style','PushButton','Units','Pixels',...
                'String','OK','FontSize',14,...
                'Position',[figx/4-20 10 65 30],...
                'UserData',[ui1 fig],'Callback',@timestringA) %does not get data back proerly, I'd bet

            % Cancel Button
            uicontrol('Style','PushButton','Units','Pixels',...
                'String','Cancel','FontSize',14,...
                'Position',[3*figx/4-20 10 65 30],...
                'Callback',@timestringB) %does not get data back proerly, I'd bet

        elseif strcmp(bins,'close')   % Close Request function
            figh = gcbf;
            clear global M_BUTTON_DOWN M_LINES M_PNTS M_TEXT % get rid of global vars
            delete(figh)

        elseif strcmp(bins,'reset')   % reset Colormap to original values
            fighandle = gcbf;
            obj = findobj('tag','hd','parent',fighandle);
            map = get(obj,'UserData');  % get original colormap stored in hd axes
            set(fighandle,'Colormap',map,...
                'UserData',[map , ones(size(map,1),1)])

            obj = findobj('tag','cb','parent',fighandle);
            nodes = get(obj,'UserData');  % get node values stored in cb axes
            red = nodes(4:nodes(1,1)+3,:);
            green = nodes(nodes(1,1)+4:nodes(1,1)+nodes(2,1)+3,:);
            blue = nodes(nodes(1,1)+nodes(2,1)+4:nodes(1,1)+nodes(2,1)+...
                nodes(3,1)+3,:);

            obj = findobj('tag','r','parent',fighandle);
            axes(obj)                         % reset colormap graphs
            cla
            nodenum = nodes(1,1);
            for i = 1:nodenum-1
                plot(red(i,1),red(i,2),'ow')
                line([red(i,1),red(i+1)],[red(i,2),red(i+1,2)],'color','r')
            end
            plot(red(nodenum,1),red(nodenum,2),'ow')
            set(obj,'UserData',red)

            obj = findobj('tag','g','parent',fighandle);
            axes(obj)
            cla
            nodenum = nodes(2,1);
            for i = 1:nodenum-1
                plot(green(i,1),green(i,2),'ow')
                line([green(i,1),green(i+1)],[green(i,2),green(i+1,2)],'color','g')
            end
            plot(green(nodenum,1),green(nodenum,2),'ow')
            set(obj,'UserData',green)

            obj = findobj('tag','b','parent',fighandle);
            axes(obj)
            cla
            nodenum = nodes(3,1);
            for i = 1:nodenum-1
                plot(blue(i,1),blue(i,2),'ow')
                line([blue(i,1),blue(i+1)],[blue(i,2),blue(i+1,2)],'color','b')
            end
            plot(blue(nodenum,1),blue(nodenum,2),'ow')
            set(obj,'UserData',blue)

            obj = findobj('tag','y','parent',fighandle);
            axes(obj)
            cla
            trans = [1 1;size(map,1) 1];
            nodenum = 2;
            for i = 1:nodenum-1
                plot(trans(i,1),trans(i,2),'ow')
                line([trans(i,1),trans(i+1)],[trans(i,2),trans(i+1,2)],'color','y')
            end
            plot(trans(nodenum,1),trans(nodenum,2),'ow')
            set(obj,'UserData',trans)
            figh = str2double(get(fighandle,'tag'));
            if figh~=fighandle
                set(figh,'Colormap',map)
            end
        end
    end

    function callbackfun_001(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        makecmap('reset');
    end

    function callbackfun_002(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        makecmap('export');
    end

    function callbackfun_003(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        makecmap('close');
    end

    function timestringA(src,ev)
        [OBJ1,FIGH1] = gcbo;
        OBJHAN = get(OBJ1,'UserData');
        LAB1 = get(OBJHAN(1),'string');
        DATA1 = get(OBJHAN(2),'Colormap');
        eval([LAB1,' = DATA1;']); % YUCK. Yuck. yuck.
        delete(FIGH1);
    end

    function timestringB(src,ev)
        [OBJ1,FIGH1] = gcbo;
        delete(FIGH1);
    end
end


function combined_waveforms = combine (waveformlist)
   %COMBINE merges waveforms based on start/end times and ChannelTag info.
   % combined_waveforms = combine (waveformlist) takes a vector of waveforms
   % and combines them based on SCNL information and start/endtimes.
   % DOES NO OTHER CHECKS

   % AUTHOR: Celso Reyes, Geophysical Institute, Univ. of Alaska Fairbanks
   % $Date$
   % $Revision$
   % Glenn Thompson 2018/01/09: replaced splice_waveform routine as it was
   % failing as part of drumplot.plot

   if numel(waveformlist) < 2  %nothing to do
      combined_waveforms = waveformlist;
      return
   end

   channelinfo = get(waveformlist,'channeltag');
   [uniquescnls, idx, scnlmembers] = unique(channelinfo);

   %preallocate
   combined_waveforms = repmat(waveform,size(uniquescnls));

   for i=1:numel(uniquescnls)
      w = waveformlist(scnlmembers == i);
      w = timesort(w);
      for j=(numel(w)-1):-1:1
         w(j) = piece_together(w(j:j+1));
         w(j+1) = waveform;
      end
      combined_waveforms(i) = w(1);
   end
end

function w = piece_together(w)
   if numel(w) > 2
      for i = numel(w)-1: -1 : 1
         w(i) = piece_together(w(i:i+1));
      end
      w = w(1);
      return;
   elseif numel(w) == 1
      return
   end
   if isempty(w(1))
      w = w(2);
      return;
   end;
   dt = dt_seconds(w(1),w(2));  %time overlap in seconds.
   sampleRates = round(get(w,'freq'));
   sampleInterval = 1 ./ sampleRates(1);

   if overlaps(dt, sampleInterval)
      w = spliceWaveform(w(1), w(2));
   else
      paddingAmount = round((dt * sampleRates(1))-1);
      w = spliceAndPad(w(1),w(2), paddingAmount);
   end
   w = w(1);
end

function w = spliceAndPad(w1, w2, paddingAmount)
   if paddingAmount > 0 && ~isinf(paddingAmount)
      toAdd = nan(paddingAmount,1);
   else
      toAdd = [];
   end

   w = set(w1,'data',[w1.data; toAdd; w2.data]);
end

% function w = spliceWaveform(w1, w2)
%
%    % NOTE * Function uses direct field access
%    timesToGrab = sum(get(w1,'timevector') < get(w2,'start'));
%
%    samplesRemoved = numel(w1.data) - timesToGrab;
%
%    w = set(w1,'data',[double(extract(w1,'index',1,timesToGrab)); w2.data]);
%
%    w= addhistory(w,'SPLICEPOINT: %s, removed %d points (overlap)',...
%       datestr(get(w2,'start')),samplesRemoved);
% end

function w = spliceWaveform(w1, w2)
%
%    % NOTE * Function uses direct field access
    snum1 = get(w1,'start');
    snum2 = get(w2,'start');
    enum1 = get(w1,'end');
    enum2 = get(w2,'end');
    [snummin, snuminindex] = min([snum1 snum2]);
    [enummax, enumaxindex] = max([enum1 enum2]);
    dnum1 = get(w1,'timevector');
    dnum2 = get(w2,'timevector');
    data1 = get(w1,'data');
    data2 = get(w2,'data');
    w = w1;
    dnum=dnum1;
    data=data1;
    ind = find(dnum2<snum1);
    if numel(ind)>0
        dnum = [dnum2(ind); dnum];
        data = [data2(ind); data];
    end
    ind = find(dnum2>enum1);
    if numel(ind)>0
        dnum = [dnum; dnum2(ind)];
        data = [data; data2(ind)];
    end
    snum = dnum(1);
    w = set(w, 'start', snum, 'data', data);

end

function result = overlaps(dt, sampleInterval)
   result = (dt- sampleInterval .* 1.25) < 0;
end

function t = dt_seconds(w1,w2)
   %  w1----] t [----w2
   firstsampleT = get(w2,'start');
   lastsampleT = get(w1,'timevector'); lastsampleT = lastsampleT(end);
   t = firstsampleT*86400 - lastsampleT * 86400;
end

function w = timesort(w)
   [~, I] = sort(get(w,'start'));
   w = w(I);
end


function updatelarvaspecies(hfly,hfly_extra,pos)

set(hfly,'XData',pos.xspine([1,6,11]),'YData',pos.yspine([1,6,11]));
%set(hfly,'XData',[pos.xcontour;nan;pos.xspine],'YData',[pos.ycontour;nan;pos.yspine]);
% xhead = pos.x + 2*pos.a*cos(pos.theta);
% yhead = pos.y + 2*pos.a*sin(pos.theta);
xhead = pos.xspine(1);
yhead = pos.yspine(1);
set(hfly_extra,'XData',xhead,'YData',yhead);


%% Winter conference - Fig 3
clear; close all; clc;

Time = {'BN', '24'};
%% MT_textfile load
Path_M = 'H:\1. Journal\NeuroImage\SLEEP_DATA_24H\';
DirGroup_M = dir(fullfile(Path_M,'*'));
FileNamesGroup_M = {DirGroup_M.name};
FileNamesGroup_M = FileNamesGroup_M(1,3:end);
Time_M = {'BN','24'};
removal_word = [".jpg"];
%% load
% Data_BN=importdata('ks_min_20200330_BN_recall_visuo.txt');
ccnt = 0;
for n = 1:size(FileNamesGroup_M,2)
%% PM Task (Succeful)
    % Recall
    for t = 1:size(Time,2)
        Data_recall=textscan(fopen([FileNamesGroup_M{n} '_' Time_M{t} '_recall_visuo.txt']), '%s %s %s %s %s %s %s');
        Data_recall=[Data_recall{:}];
        Hash_Table_recall = str2double(erase(Data_recall([2:end],3),removal_word));
        Hash_Table_recall = [cellfun(@(x) sprintf('%02d',x),num2cell(Hash_Table_recall),'UniformOutput',false)...
            Data_recall([2:end],4) Data_recall([2:end],6) Data_recall([2:end],2)];
        Hash_Table_recall = sortrows(Hash_Table_recall,1);

        for i = 1:size(Hash_Table_recall,1)
            if string(Hash_Table_recall(i,2)) == 'o'
                res(i,t) = 1;
            elseif string(Hash_Table_recall(i,2)) == 'n'
                res(i,t) = 0;
            elseif isspace(string(Hash_Table_recall(i,2))) == 1 % i don't know
                res(i,t) = 2;
            end
        end

        % four possible reponse categories
        temp=[1,0];% 1: old, 0: new
        for i=1:2
            for j=1:2
                if i == 1
                    trial{i,j,t} = find(res(1:38,t)==temp(j));
                elseif i == 2
                    trial{i,j,t} = find(res(39:end,t)==temp(j))+38;
                end
            end
        end
        if t == 1
            Suc = [trial{1,1,t}];
            Succ = sortrows(str2double(Hash_Table_recall(Suc,4)));
        end
    end
%% Picture memory hits
    label = intersect(trial{1,1,1}, trial{1,1,2});

    % Before nap
    Data_recall=textscan(fopen([FileNamesGroup_M{n} '_' Time_M{1} '_recall_visuo.txt']), '%s %s %s %s %s %s %s');
    Data_recall=[Data_recall{:}];
    Hash_Table_recall = str2double(erase(Data_recall([2:end],3),removal_word));
    Hash_Table_recall = [cellfun(@(x) sprintf('%02d',x),num2cell(Hash_Table_recall),'UniformOutput',false)...
        Data_recall([2:end],4) Data_recall([2:end],6) Data_recall([2:end],2)];
    Hash_Table_recall = sortrows(Hash_Table_recall,1);

    Label = sortrows(str2double(Hash_Table_recall(label,4)));
    y = double(ismember(Succ, Label));
    y_ = nonzeros(y);
    STM_hits(n,1) = size(Succ,1);
    LTM_hits(n,1) = size(y_,1);
end

hits = [STM_hits LTM_hits];


function [sys,prn]=satsys(sat)

global glc
sys=0;

if sat<=0||sat>glc.MAXSAT
    sat=0;
elseif sat<=glc.NSATGPS
    sys=glc.SYS_GPS; sat=sat+glc.MINPRNGPS-1;
elseif (sat-glc.NSATGPS)<=glc.NSATGLO
    sys=glc.SYS_GLO; sat=(sat-glc.NSATGPS)+glc.MINPRNGLO-1;
elseif (sat-glc.NSATGPS-glc.NSATGLO)<=glc.NSATGAL
    sys=glc.SYS_GAL; sat=(sat-glc.NSATGPS-glc.NSATGLO)+glc.MINPRNGAL-1;
elseif (sat-glc.NSATGPS-glc.NSATGLO-glc.NSATGAL)<=glc.NSATBDS
    sys=glc.SYS_BDS; sat=(sat-glc.NSATGPS-glc.NSATGLO-glc.NSATGAL)+glc.MINPRNBDS-1;
elseif (sat-glc.NSATGPS-glc.NSATGLO-glc.NSATGAL-glc.NSATBDS)<=glc.NSATQZS
    sys=glc.SYS_QZS; sat=(sat-glc.NSATGPS-glc.NSATGLO-glc.NSATGAL-glc.NSATBDS)+glc.MINPRNQZS-1;
else
    sat=0;
end

prn=sat;

return


classdef TotalThrustConstraint < AbstractConstraint
    %TotalThrustConstraint Summary of this class goes here
    %   Detailed explanation goes here

    properties
        normFact = 1;
        event LaunchVehicleEvent
        eventNode(1,1) ConstraintStateComparisonNodeEnum = ConstraintStateComparisonNodeEnum.FinalState;

        lb(1,1) double = 0;
        ub(1,1) double = 0;

        evalType(1,1) ConstraintEvalTypeEnum = ConstraintEvalTypeEnum.FixedBounds;
        stateCompType(1,1) ConstraintStateComparisonTypeEnum = ConstraintStateComparisonTypeEnum.Equals;
        stateCompEvent LaunchVehicleEvent
        stateCompNode(1,1) ConstraintStateComparisonNodeEnum = ConstraintStateComparisonNodeEnum.FinalState;
    end

    methods
        function obj = TotalThrustConstraint(event, lb, ub)
            obj.event = event;
            obj.lb = lb;
            obj.ub = ub;

             obj.id = rand();
        end

        function [lb, ub] = getBounds(obj)
            lb = obj.lb;
            ub = obj.ub;
        end

        function [c, ceq, value, lwrBnd, uprBnd, type, eventNum, valueStateComp] = evalConstraint(obj, stateLog, celBodyData)
            type = obj.getConstraintType();

            switch obj.eventNode
                case ConstraintStateComparisonNodeEnum.FinalState
                    stateLogEntry = stateLog.getLastStateLogForEvent(obj.event);

                case ConstraintStateComparisonNodeEnum.InitialState
                    stateLogEntry = stateLog.getFirstStateLogForEvent(obj.event);

                otherwise
                    error('Unknown event node.');
            end

            totalThrust = TotalThrustConstraint.getTotalThrust(stateLogEntry);
            value = totalThrust;

            if(obj.evalType == ConstraintEvalTypeEnum.StateComparison)
                switch obj.stateCompNode
                    case ConstraintStateComparisonNodeEnum.FinalState
                        stateLogEntryStateComp = stateLog.getLastStateLogForEvent(obj.stateCompEvent);

                    case ConstraintStateComparisonNodeEnum.InitialState
                        stateLogEntryStateComp = stateLog.getFirstStateLogForEvent(obj.stateCompEvent);

                    otherwise
                        error('Unknown event node.');
                end

                valueStateComp = TotalThrustConstraint.getTotalThrust(stateLogEntryStateComp); %it's probably not a bad idea to leave the state here in the original reference frame.
            else
                valueStateComp = NaN;
            end

            [c, ceq] = obj.computeCAndCeqValues(value, valueStateComp);

            lwrBnd = obj.lb;
            uprBnd = obj.ub;

            eventNum = obj.event.getEventNum();
        end

        function sF = getScaleFactor(obj)
            sF = obj.normFact;
        end

        function setScaleFactor(obj, sF)
            obj.normFact = sF;
        end

        function tf = usesStage(obj, stage)
            tf = false;
        end

        function tf = usesEngine(obj, engine)
            tf = false;
        end

        function tf = usesTank(obj, tank)
            tf = false;
        end

        function tf = usesEngineToTankConn(obj, engineToTank)
            tf = false;
        end

        function tf = usesEvent(obj, event)
            tf = obj.event == event;
            if(obj.evalType == ConstraintEvalTypeEnum.StateComparison)
                tf = tf || obj.stateCompEvent == event;
            end
        end

        function tf = usesStopwatch(obj, stopwatch)
            tf = false;
        end

        function tf = usesExtremum(obj, extremum)
            tf = false;
        end

        function tf = canUseSparseOutput(obj)
            tf = true;
        end

        function event = getConstraintEvent(obj)
            event = obj.event;
        end

        function type = getConstraintType(obj)
            type = 'Total Thrust';
        end

%         function name = getName(obj)
%             name = sprintf('%s - Event %i', obj.getConstraintType(), obj.event.getEventNum());
%         end

        function [unit, lbLim, ubLim, usesLbUb, usesCelBody, usesRefSc] = getConstraintStaticDetails(obj)
            unit = 'kN';
            lbLim = 0;
            ubLim = Inf;
            usesLbUb = true;
            usesCelBody = false;
            usesRefSc = false;
        end

        function addConstraintTf = openEditConstraintUI(obj, lvdData)
%             addConstraintTf = lvd_EditGenericMAConstraintGUI(obj, lvdData);

            output = AppDesignerGUIOutput({false});
            lvd_EditGenericMAConstraintGUI_App(obj, lvdData, output);
            addConstraintTf = output.output{1};
        end
    end

    methods(Static)
        function totalThrust = getTotalThrust(stateLogEntry)
            ut = stateLogEntry.time;
            rVect = stateLogEntry.position;
            vVect = stateLogEntry.velocity;

            bodyInfo = stateLogEntry.centralBody;
            tankStates = stateLogEntry.getAllActiveTankStates();
            stageStates = stateLogEntry.stageStates;
            lvState = stateLogEntry.lvState;

            dryMass = stateLogEntry.getTotalVehicleDryMass();
            tankStatesMasses = [tankStates.tankMass]';

            throttleModel = stateLogEntry.throttleModel;
            steeringModel = stateLogEntry.steeringModel;

            attState = LaunchVehicleAttitudeState();
            attState.dcm = steeringModel.getBody2InertialDcmAtTime(ut, rVect, vVect, bodyInfo);

            altitude = norm(rVect) - bodyInfo.radius;
            pressure = getPressureAtAltitude(bodyInfo, altitude);

            powerStorageStates = stateLogEntry.getAllActivePwrStorageStates();
            storageSoCs = NaN(size(powerStorageStates));
            for(i=1:length(powerStorageStates)) %#ok<*NO4LP>
                storageSoCs(i) = powerStorageStates(i).getStateOfCharge();
            end

            throttle = throttleModel.getThrottleAtTime(ut, rVect, vVect, tankStatesMasses, dryMass, stageStates, lvState, tankStates, bodyInfo, storageSoCs, powerStorageStates);

            [~, totalThrust, ~] = LaunchVehicleStateLogEntry.getTankMassFlowRatesDueToEngines(tankStates, tankStatesMasses, stageStates, throttle, lvState, pressure, ut, rVect, vVect, bodyInfo, steeringModel, storageSoCs, powerStorageStates, attState);
        end
    end

    methods(Static)
        function constraint = getDefaultConstraint(~, ~)
            constraint = TotalThrustConstraint(LaunchVehicleEvent.empty(1,0),0,0);
        end
    end
end


%RNA Expression Analysis
%
% Author: Jonathan Karr, jkarr@stanford.edu
% Affiliation: Covert Lab, Department of Bioengineering, Stanford University
% Last Updated: 12/22/2011
classdef RNAExpression
    methods (Static = true)
        function run(sim, fileName)
            %import classes
            import edu.stanford.covert.cell.sim.util.PlotUtil;
            import edu.stanford.covert.cell.sim.util.PrintUtil;
            import edu.stanford.covert.util.ComputationUtil;

            %load simulation
            g = sim.gene;
            r = sim.state('Rna');

            %get data
            rnaExp = r.expectedGeneExpression(:, 1);

            exp_mRNAWt = 0.041;
            exp_rRNAWt = [0.017; 0.271; 0.525];
            exp_sRNAWt = 0;
            exp_tRNAWt = 0.146;
            assertEqual(1, exp_mRNAWt + sum(exp_rRNAWt) + exp_sRNAWt + exp_tRNAWt);

            %calculate gene molecular weights approximately
            geneMWs = (r.matureRNAGeneComposition * (r.molecularWeights(r.aminoacylatedIndexs) ./ (r.matureRNAGeneComposition' * g.lengths))) ...
                .* g.lengths;

            %check RNA MWs computed correctly
            monocistronicIdxs = find(sum(r.matureRNAGeneComposition(g.mRNAIndexs, :), 1) == 1);
            monocistronicmRNAGeneIdxs = g.mRNAIndexs(any(r.matureRNAGeneComposition(g.mRNAIndexs, monocistronicIdxs), 2));
            assertElementsAlmostEqual(geneMWs(monocistronicmRNAGeneIdxs), r.molecularWeights(r.aminoacylatedIndexs(monocistronicIdxs)), 'relative', 1e-12);
            assertElementsAlmostEqual(geneMWs(g.rRNAIndexs), r.molecularWeights(r.aminoacylatedIndexs(r.matureRRNAIndexs)), 'relative', 1e-12);
            assertElementsAlmostEqual(geneMWs(g.sRNAIndexs), r.molecularWeights(r.aminoacylatedIndexs(r.matureSRNAIndexs)), 'relative', 1e-12);
            assertElementsAlmostEqual(geneMWs(g.tRNAIndexs), r.molecularWeights(r.aminoacylatedIndexs(r.matureTRNAIndexs)), 'relative', 1e-12);
            assertElementsAlmostEqual(r.molecularWeights(r.aminoacylatedIndexs), r.matureRNAGeneComposition' * geneMWs, 'relative', 1e-12);

            %reconstruct gene expression
            mRNAWt = rnaExp(g.mRNAIndexs)' * geneMWs(g.mRNAIndexs);
            rRNAWt = rnaExp(g.ribosomalRRNAIndexs) .* geneMWs(g.ribosomalRRNAIndexs);
            sRNAWt = rnaExp(g.sRNAIndexs)' * geneMWs(g.sRNAIndexs);
            tRNAWt = rnaExp(g.tRNAIndexs)' * geneMWs(g.tRNAIndexs);

            rnaExp(g.mRNAIndexs) = rnaExp(g.mRNAIndexs) * exp_mRNAWt / mRNAWt;
            rnaExp(g.ribosomalRRNAIndexs) = rnaExp(g.ribosomalRRNAIndexs) .* exp_rRNAWt ./ rRNAWt;
            rnaExp(g.sRNAIndexs) = rnaExp(g.sRNAIndexs) * exp_sRNAWt / sRNAWt;
            rnaExp(g.tRNAIndexs) = rnaExp(g.tRNAIndexs) * exp_tRNAWt / tRNAWt;

            rnaExp = rnaExp / sum(rnaExp);

            exp_RNAWt = [exp_mRNAWt; exp_rRNAWt; exp_sRNAWt; exp_tRNAWt];
            RNAwt = [mRNAWt; rRNAWt; sRNAWt; tRNAWt];
            exp_RNAWt = exp_RNAWt / sum(exp_RNAWt);
            RNAwt = RNAwt / sum(RNAwt);

            %plot RNA weight fractions
            [axesHandle, figHandle] = PlotUtil.newAxesHandle();

            cla(axesHandle);
            hold(axesHandle, 'on');
            h = [
                plot(axesHandle, RNAwt(1), exp_RNAWt(1), 'r.')
                plot(axesHandle, RNAwt(2:4), exp_RNAWt(2:4), 'g.')
                plot(axesHandle, RNAwt(5), exp_RNAWt(5), 'b.')
                plot(axesHandle, RNAwt(6), exp_RNAWt(6), 'c.')
                ];
            legend(h, {'mRNA', 'rRNA', 'sRNA', 'tRNA'}, 'Location', 'NorthWest');
            xlabel(axesHandle, 'Reconstruction - Earliest Stage', 'FontSize', 12)
            ylabel(axesHandle, 'Reconstruction - Later Stage', 'FontSize', 12)
            set(axesHandle, 'xscale', 'log', 'yscale', 'log', 'xlimmode', 'auto',  'ylimmode', 'auto', 'xminortick', 'off', 'yminortick', 'off')
            axis(axesHandle, 'equal');
            xlim(axesHandle, [min([xlim(axesHandle) ylim(axesHandle)]) max([xlim(axesHandle) ylim(axesHandle)])]);
            ylim(axesHandle, xlim(axesHandle));
            line(xlim(axesHandle), ylim(axesHandle), 'Parent', axesHandle, 'LineStyle', ':', 'Color', [0.5 0.5 0.5])

            saveas(figHandle, [fileName '-EarlyVsLaterPhaseReconstruction-WeightFractions.pdf']);
            close(figHandle);

            %plot all RNA
            [axesHandle, figHandle] = PlotUtil.newAxesHandle();

            cla(axesHandle);
            hold(axesHandle, 'on');
            h = [
                plot(axesHandle, rnaExp(g.mRNAIndexs), r.expectedGeneExpression(g.mRNAIndexs, 1), 'r.')
                plot(axesHandle, rnaExp(g.rRNAIndexs), r.expectedGeneExpression(g.rRNAIndexs, 1), 'g.')
                plot(axesHandle, rnaExp(g.sRNAIndexs), r.expectedGeneExpression(g.sRNAIndexs, 1), 'b.')
                plot(axesHandle, rnaExp(g.tRNAIndexs), r.expectedGeneExpression(g.tRNAIndexs, 1), 'c.')
                ];
            legend(h, {'mRNA', 'rRNA', 'sRNA', 'tRNA'}, 'Location', 'NorthWest');
            xlabel(axesHandle, 'Reconstruction - Earliest Stage', 'FontSize', 12)
            ylabel(axesHandle, 'Reconstruction - Later Stage', 'FontSize', 12)
            set(axesHandle, 'xscale', 'log', 'yscale', 'log', 'xlimmode', 'auto',  'ylimmode', 'auto', 'xminortick', 'off', 'yminortick', 'off')
            axis(axesHandle, 'equal');
            xlim(axesHandle, [min([xlim(axesHandle) ylim(axesHandle)]) max([xlim(axesHandle) ylim(axesHandle)])]);
            ylim(axesHandle, xlim(axesHandle));
            line(xlim(axesHandle), ylim(axesHandle), 'Parent', axesHandle, 'LineStyle', ':', 'Color', [0.5 0.5 0.5])

            saveas(figHandle, [fileName '-EarlyVsLaterPhaseReconstruction.pdf']);
            close(figHandle);

            %save to excel sheet
            content = [g.wholeCellModelIDs num2cell(rnaExp) num2cell(r.expectedGeneExpression(:, 1))];
            colLabels = {'Gene', 'Expression-Early Reconstruction', 'Expression-Later Reconstruction'};
            PrintUtil.printToFile(content, colLabels, [fileName '.xls'], 'RNA Expression');
        end
    end
end


function [P, resort] = sort_image_filenames(P)
% :Usage:
% ::
%
%     [P, indices] = sort_image_filenames(P)
%
% Not all image name listing functions return imgs in the correct numbered
% order!
%
% This function resorts a string matrix of image file names by image number,
% in ascending order
% At most, filename can have one number in it, or error is returned
%
% P can be a string matrix of a cell of string matrices
%
% ..
%    Tor Wager, April 2005
% ..

% if iscell(P) % if cell, call this function recursively
%     for i = 1:length(P)
%         fprintf(1,'%3.0f',i);
%         P{i} = sort_image_filenames(P{i});
%     end
%     fprintf(1,'\n')
%     return
% end

if size(P,1) == 1, return, end

nums = [];
for j = 1:size(P,1)

    if iscell(P)
        [dd,ff,ee]=fileparts(P{j, 1});
    else
        % str matrix
        [dd,ff,ee]=fileparts(P(j,:));
    end

    % find the last real number in the name
    tmp = nums_from_text(ff);
    tmp(tmp ~= real(tmp)) = [];
    nums(j) = tmp(end);
end

[n2,resort] = sort(nums);

if any(n2-nums)
    fprintf(1,'Resorting.')

    P = P(resort,:);
end

end


function imorse = ic_to_imorse ( ic )

%*****************************************************************************80
%
%% IC_TO_IMORSE converts an ASCII integer code to a Morse integer code.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 February 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer IC, the integer code for the ASCII character.
%
%    Output, integer IMORSE, the integer code for the Morse character,
%    or -1 if no corresponding Morse code is available.
%
  junk = [ ...
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, ...
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, ...
     1, -1, 45, -1, -1, -1, -1, 42, -1, -1, -1, -1, 39, 43, 38, 44, ...
    37, 28, 29, 30, 31, 32, 33, 34, 35, 36, 40, -1, -1, -1, -1, 41, ...
    -1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, ...
    17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, -1, -1, -1, -1, -1, ...
    -1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, ...
    17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, -1, -1, -1, -1, -1, ...
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, ...
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, ...
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, ...
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, ...
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, ...
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, ...
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, ...
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ];

  if ( 0 <= ic && ic <= 255 )
    imorse = junk(ic+1);
  else
    imorse = -1;
  end

  return
end


function [ objectIndex ] = GetScenario_randomUniform(varargin)

fprintf('[SCENARIO]\tGetting a normally distributed object scenario.\n');

% DEFAULT AGENT/OBSTACLE CONFIGURATION IN THIS EXAMPLE
defaultConfig = struct(...
    'file','scenario.mat',...
    'objects',[],...
    'waypointRadius',0.5,...
    'velocity',18,...
    'positionGain',10,...
    'velocityGain',1,...
    'poseGain',pi,...
    'noiseFactor',0,...
    'is3D',true,...
    'plot',false);

% Instanciate the scenario builder
SBinstance = scenarioBuilder();
% Parse user inputs
[inputConfig] = SBinstance.configurationParser(defaultConfig,varargin);

% Get the random object configuration
objectConfig = SBinstance.randomUniform(...
    'objects',numel(inputConfig.objects),...
    'positionGain',inputConfig.positionGain,...
    'velocityGain',inputConfig.velocityGain,...
    'poseGain',inputConfig.poseGain);

for index = 1:numel(inputConfig.objects)
    % Assign object
    objectIndex{index} = inputConfig.objects{index};
    % APPLY GLOBAL STATE VARIABLES
    if inputConfig.is3D
        objectIndex{index}.SetGLOBAL('position',objectConfig.positions(:,index) + inputConfig.noiseFactor*randn(3,1);
        objectIndex{index}.SetGLOBAL('velocity',objectConfig.velocities(:,index) + inputConfig.noiseFactor*randn(3,1);
        objectIndex{index}.SetGLOBAL('quaternion',objectConfig.quaternions(:,index));
    else
        objectIndex{index}.SetGLOBAL('position',[objectConfig.positions(1:2,index);0] + inputConfig.noiseFactor*[randn(2,1);0];
        objectIndex{index}.SetGLOBAL('velocity',[objectConfig.velocities(1:2,index);0] + inputConfig.noiseFactor*[randn(2,1);0];
        eta = OMAS_geometry.quaternionToEulers(objectConfig.quaternions(:,index));
        objectIndex{index}.SetGLOBAL('quaternion',OMAS_geometry.eulersToQuaternion([eta(3);0;0]));
    end
end
% Get the random object configuration
waypointConfig = SBinstance.randomUniform(...
    'objects',numel(inputConfig.objects),...
    'positionGain',inputConfig.positionGain,...
    'velocityGain',inputConfig.velocityGain,...
    'poseGain',inputConfig.poseGain);

fprintf('[SCENARIO]\tAssigning waypoints to agents.\n');
waypointSet = cell(size(inputConfig.objects));
for index = 1:numel(inputConfig.objects)
    % WAYPOINT SET A
    waypointSet{index} = waypoint('radius',inputConfig.waypointRadius,'priority',1,'name',sprintf('WP-%s',objectIndex{index}.name));
    % APPLY GLOBAL STATE VARIABLES
    if inputConfig.is3D
        waypointSet{index}.SetGLOBAL('position',waypointConfig.positions(:,index) + inputConfig.noiseFactor*randn(3,1));
        waypointSet{index}.SetGLOBAL('velocity',waypointConfig.velocities(:,index));
        waypointSet{index}.SetGLOBAL('quaternion',waypointConfig.quaternions(:,index));
    else
        waypointSet{index}.SetGLOBAL('position',[waypointConfig.positions(1:2,index);0] + inputConfig.noiseFactor*[randn(2,1);0]);
        waypointSet{index}.SetGLOBAL('velocity',[waypointConfig.velocities(1:2,index);0] + inputConfig.noiseFactor*[randn(2,1);0]);
        eta = OMAS_geometry.quaternionToEulers(waypointConfig.quaternions(:,index));
        waypointSet{index}.SetGLOBAL('quaternion',OMAS_geometry.eulersToQuaternion([eta(3);0;0]));
    end
    waypointSet{index} = waypointSet{index}.CreateAgentAssociation(objectIndex{index});  % Create waypoint with association to agent
end
% Concatinate the objects and way-points
objectIndex = [objectIndex;waypointSet];

% PLOT THE SCENE
if inputConfig.plot
    SBinstance.plotObjectIndex(objectIndex);
end
% CLEAR THE REMAINING VARIABLES
clearvars -except objectIndex
end