function Viewer

%% Get file name
datafolder = 'data';
icdir = ['data' filesep];

files = dir(fullfile(icdir, '*st*.mat'));
files = {files.name};
for ii=length(files):-1:1
    if strcmp(files{ii}(end-6:end-4), 'csd')
        files(ii) = [];
    end;
end;
contents = cell(length(files),1);
for ii=1:length(files)
    cm = load(fullfile(icdir, files{ii}), 'contents');
    contents{ii} = cm.contents;
end;

list_order = [11 7 8 5 6 9 10 3 1 2 4];
contents(1:11) = contents(list_order);
files(1:11) = files(list_order);

[selection, ok] = listdlg('ListString', contents, ...
    'SelectionMode', 'single', 'Name', 'ICviewer', ...
    'PromptString', 'Please select data set', ...
    'ListSize', [480 300]);
if ok==0
    return
end;
fname = files{selection};
comment = contents{selection};

%% Load data file, preprocess
IC = load(fullfile(icdir, fname));
ica_on_csd = (fname(end-4)=='c');
ncomp = size(IC.S1,2);

for kk=1:ncomp
    if abs(max(IC.T1(:,kk)))<abs(min(IC.T1(:,kk)))
        IC.T1(:,kk) = -IC.T1(:,kk);
        IC.S1(:,kk) = -IC.S1(:,kk);
    end;
end;

tvec = 0.1*((1:size(IC.T1,1))-(IC.stimulus-IC.tstart+1));
ticks = tvec.*[1 diff(floor(tvec))];
ticks(ticks==0) = [];
ticks = sort([ticks 0]);

step = 0.0625;
n_colors = 2048;
nx=4;
nz=7;
VX = 1:step:nx;
VZ = 1:step:nz;
plot_csd = 1;
play = 0;

%% Load background images
movie_bgd_imgs = 1;
if exist(fullfile(datafolder, [IC.rat_name '_1.jpg']), 'file')
    tla = zeros(5,300,150);
    for i=1:5
        tla(i,:,:) = imread(fullfile(datafolder, [IC.rat_name '_' int2str(i) '.jpg']));
        tla(i,:,:) = 1.-tla(i,:,:)/255;
    end;
else
    %disp('  Background images not found.');
    movie_bgd_imgs=0;
end;

%% Load interpolated data
sigsn = []; %#ok<NASGU>
csd_all2 = []; % To prevent warnings from M-Lint
fpot_all2 = [];
if exist(fullfile(icdir, [IC.rat_name IC.dataset '_csd.mat']), 'file')
    load(fullfile(icdir, [IC.rat_name IC.dataset '_csd.mat']));
else
    error('CSD file not found. Run ''init_icviewer''');
end;
if exist(fullfile(icdir, [fname(1:end-4) '_csd.mat']), 'file')
    load(fullfile(icdir, [fname(1:end-4) '_csd.mat']));
else
    error('CSD file not found. Run ''init_icviewer''');
end;

csd_scale = max(abs(csd_all2(:)));
fpot_scale = max(abs(fpot_all2(:)));
csd_scale_factor = 4;
clims=[-csd_scale/csd_scale_factor, csd_scale/csd_scale_factor];
climspot = [-fpot_scale/csd_scale_factor, fpot_scale/csd_scale_factor];
%clims0=[-csd_scale/csd_scale_factor, csd_scale/csd_scale_factor];
tlims = [min(IC.T1(:)) max(IC.T1(:))];

%% Component sorting
imp_scores = max(abs(IC.T1)).*max(reshape(csd2,ncomp,[]).^2,[],2)';
[imp_scores_s, idxs] = sort(imp_scores,'descend');
f1 = figure;
movegui(f1, 'northeast');
temp = get(f1, 'Colormap');
bar(imp_scores_s/max(imp_scores_s))
cmap = colormap(colorcube(ncomp));
title('Strength of components (~ max amplitude), normalized');
xlabel('Component number')
set(f1, 'Colormap', temp);
cdats = cell(ncomp,1);
cc = 0.702; % gray
for ii=1:ncomp
    col = permute(reshape(repmat(cmap(ii,:),8,8),8,3,8), [1 3 2]);
    cdats{ii} = cat(2, cc(1)*ones(8,30,3), col);
end;
IC.T1 = IC.T1(:,idxs);
csd2 = csd2(idxs,:,:,:);
if not(ica_on_csd)
    fpot2 = fpot2(idxs,:,:,:);
end;

%% Prepare viewer GUI
base_size = 150;
tpos = [0.5, 0.96];
nyp = 5;

figg = figure('Position',[16 48 base_size*6.5 ...
    round(base_size*5.8)]);
movegui(figg, 'northwest');
wyk_tlo = axes('Position', [0 0 1 1], 'Visible', 'off');
przstr = {'Potentials', 'CSD'};
prz = uicontrol('style', 'toggle', ...
    'pos', [0.22*150 820 80 30], 'string', przstr(plot_csd+1), ...
    'Callback', @przcbk);
przplay = uicontrol('style', 'push', 'string', 'Play',...
    'pos', [0.22*150+100 820 80 30], ...
    'Callback', @przplaycbk);
przquit = uicontrol('style', 'push', 'string', 'Quit',...
    'pos', [777 820 80 30], ...
    'Callback', @quitfig); %#ok<NASGU>
przhelp = uicontrol('style', 'push', 'string', 'Help',...
    'pos', [5.9*base_size 820 60 30], ...
    'Callback', @helpcbk); %#ok<NASGU>

for i = 1:nyp
    wyk(i) = axes('Units', 'pixels'); %#ok<AGROW>
    set(wyk(i), 'Position', ...
        [(i-1+0.12*i+0.1)*base_size 1.2*base_size ...
        base_size 2*base_size]);
    wyk_all(i) = axes('Units', 'pixels'); %#ok<AGROW>
    set(wyk_all(i), 'Position', ...
        [(i-1+0.12*i+0.1)*base_size 3.4*base_size ...
        base_size 2*base_size]);
end;
wyk(nyp+1) = axes('Units', 'pixels', 'Position', ...
    [(0.1+0.12)*base_size 0.5*base_size ...
    (5.6-0.12)*base_size 0.5*base_size], 'Visible', 'off');
set(figg, 'CurrentAxes', wyk_tlo);
title_h = text('Position', tpos, 'HorizontalAlignment', 'center', ...
    'String', '', 'FontSize', 12, 'FontWeight', 'Bold');

box_ctrl = zeros(ncomp,1);
for ii=1:ncomp
    box_ctrl(ii) = uicontrol('Style', 'toggle', ...
        'String', num2str(ii), 'pos',...
        [5.9*base_size 5.4*base_size-ii*25 ...
        60 25], 'Cdata', cdats{ii}, ...
        'Callback', @boxcbk);
end;

time_frame = find(tvec>=0, 1);
slider_h = uicontrol('Style', 'slider', ...
    'pos', [(0.1+0.12)*base_size 0.2*base_size ...
    (5.6-0.12)*base_size 20], 'Callback', @slider_Callback, ...
    'Min', tvec(1), 'Max', tvec(end), 'Value', tvec(time_frame), ...
    'SliderStep', 1/(length(tvec)-1)*[1 10]);
textbox_h = uicontrol('Style', 'Text', 'String', ...
    num2str(get(slider_h,'Value')), 'pos', ...
    [5.9*base_size 0.2*base_size 60 20]);
scale_h = uicontrol('Style', 'slider', ...
    'pos', [5.9*base_size+20 0.2*base_size+40  20 100], ...
    'Value', csd_scale_factor, 'Min', 1, 'Max', 10, ...
    'Callback', @scale_Callback, ...
    'SliderStep', [0.05 0.2]); %#ok<NASGU>

%% Start viewer
selected = zeros(ncomp,1);
tim = 0;
tim = timer('TimerFcn', @plotcomp, 'Period', 0.001,...
    'TasksToExecute', 1);

plotcomp

%% Title string
    function tit = title_string
        tit = comment;
        %         tit = [IC.rat_name ', neig = ' num2str(IC.neig) ', alpha = ' ...
        %             num2str(IC.alpha)];
    end % of function

%% Callbacks
    function przcbk(hObject, eventdata, handles) %#ok<INUSD>
        plot_csd = 1 -plot_csd;
        set(prz, 'String', przstr(plot_csd+1));
        if not(play)
            plotcomp
        end;
    end % of function

    function boxcbk(hObject, eventdata, handles) %#ok<INUSD>
        if not(play)
            plotcomp
        end;
    end % of function

    function przplaycbk(hObject, eventdata, handles) %#ok<INUSD>
        play = 1-play;
        switch play
            case 0
                set(przplay, 'String', 'Play');
            case 1
                set(przplay, 'String', 'Stop');
        end;
        plotcomp
    end % of function

    function slider_Callback(hObject, eventdata, handles) %#ok<INUSD>
        slider_value = get(hObject,'Value');
        time_frame = find(tvec>=slider_value, 1);
        set(textbox_h, 'String', num2str(tvec(time_frame)));
        if not(play)
            plotcomp
        end;
    end % of function

    function scale_Callback(hObject, eventdata, handles) %#ok<INUSD>
        csd_scale_factor = get(hObject,'Value');
        clims=[-csd_scale/csd_scale_factor, csd_scale/csd_scale_factor];
        climspot = [-fpot_scale/csd_scale_factor, fpot_scale/csd_scale_factor];
        if not(play)
            plotcomp
        end;
    end % of function

    function timecourse_Callback(hObject, eventdata, handles) %#ok<INUSD>
        cpoint = get(hObject,'CurrentPoint');
        set(slider_h, 'Value', cpoint(1,1));
        slider_Callback(slider_h);
    end % of function

    function quitfig(hObject, eventdata, handles) %#ok<INUSD>
        if ishandle(f1)
            close(f1);
        end;
        close(figg);
    end % of function

    

%% Plotting
    function plotcomp(source, eventdata) %#ok<INUSD>
        for mm=1:ncomp
            selected(mm) = get(box_ctrl(mm),'Value');
        end;
        if plot_csd||ica_on_csd
            csd_now = zeros(size(csd2,2), size(csd2,3), size(csd2,4));
            for ll=1:ncomp
                if selected(ll)==1
                    csd_now = csd_now+squeeze(csd2(ll,:,:,:)*...
                        squeeze(IC.T1(time_frame,ll)));
                end;
            end;
        else
            fpot_now = zeros(size(csd2,2), size(csd2,3), size(csd2,4));
            for ll=1:ncomp
                if selected(ll)==1
                    fpot_now = fpot_now+squeeze(fpot2(ll,:,:,:)*...
                        squeeze(IC.T1(time_frame,ll)));
                end;
            end;
        end;
        for l = 1:nyp
            set(figg, 'CurrentAxes', wyk(l));
            if movie_bgd_imgs
                if plot_csd||ica_on_csd
                    img = imagesc([1,nx],[1,nz], ...
                        interp2(squeeze(csd_now(:,l,:))', ...
                        1:(length(VX)-1)/(base_size-1):length(VX), ...
                        (1:(length(VZ)-1)/(2*base_size-1):length(VZ))' , ...
                        'nearest'),clims);
                else
                    img = imagesc([1,nx],[1,nz], ...
                        interp2(squeeze(fpot_now(:,l,:))', ...
                        1:(length(VX)-1)/(base_size-1):length(VX), ...
                        (1:(length(VZ)-1)/(2*base_size-1):length(VZ))' , ...
                        'nearest'),climspot);
                end;
                set(img, 'AlphaData', squeeze(tla(l,:,:)));
                set(gca, 'Color', [0 0 0]);
                colormap(flipud(jet(n_colors)));
            else
                if plot_csd||ica_on_csd
                    imagesc([1,nx],[1,nz], ...
                        squeeze(csd_now(:,l,:))',clims);
                else
                    imagesc([1,nx],[1,nz], ...
                        squeeze(fpot_now(:,l,:))',climspot);
                end;
                colormap(flipud(jet(n_colors)));
            end;
            if l>1
                set(gca, 'YTickLabel', '');
            end;
            set(title_h, 'String', title_string);

            set(figg, 'CurrentAxes', wyk_all(l));
            if movie_bgd_imgs
                if plot_csd
                    img = imagesc([1,nx],[1,nz], ...
                        interp2(squeeze(csd_all2(time_frame,:,l,:))', ...
                        1:(length(VX)-1)/(base_size-1):length(VX), ...
                        (1:(length(VZ)-1)/(2*base_size-1):length(VZ))' , ...
                        'nearest'),clims);
                else
                    img = imagesc([1,nx],[1,nz], ...
                        interp2(squeeze(fpot_all2(time_frame,:,l,:))', ...
                        1:(length(VX)-1)/(base_size-1):length(VX), ...
                        (1:(length(VZ)-1)/(2*base_size-1):length(VZ))' , ...
                        'nearest'),climspot);
                end;
                set(img, 'AlphaData', squeeze(tla(l,:,:)));
                set(gca, 'Color', [0 0 0]);
                colormap(flipud(jet(n_colors)));
            else
                if plot_csd
                    imagesc([1,nx],[1,nz], ...
                        squeeze(csd_all2(time_frame,:,l,:))',clims);
                else
                    imagesc([1,nx],[1,nz], ...
                        squeeze(fpot_all2(time_frame,:,l,:))',climspot);
                end;
                colormap(flipud(jet(n_colors)));
            end;
            if l>1
                set(gca, 'YTickLabel', '');
            end;
        end;
        set(figg, 'CurrentAxes', wyk(nyp+1));
        pp = zeros(ncomp,1);
        if sum(selected)>0
            pp(selected==1,:) = plot(tvec, IC.T1(:,selected==1));
            for mm=1:ncomp
                if selected(mm)
                    set(pp(mm), 'Color', cmap(mm,:), 'LineWidth', 2)
                end;
            end;
            hold on
            plot(tvec, 0*tvec, 'b--');
            hold off
        else
            plot(tvec, 0*tvec, 'b--');
        end;
        ylim(tlims);
        xlim([tvec(1)-1e-3 tvec(end)+1e-3]);
        set(wyk(nyp+1), 'Xtick', ticks, ...
            'Yticklabel', [], 'Ytick', [], 'Color', 'none');
        hold on
        plot([1 1]*tvec(time_frame), tlims, 'k')
        hold off
        set(wyk(nyp+1), 'ButtonDownFcn', @timecourse_Callback);
        if play
            drawnow;
            if time_frame+1 > length(tvec)
                przplaycbk
            else
                time_frame = time_frame+1;
            end;
            set(textbox_h, 'String', num2str(tvec(time_frame)));
            set(slider_h, 'Value', tvec(time_frame));
            stop(tim);
            delete(timerfind);
            tim = timer('TimerFcn', @plotcomp, 'Period', 0.001,...
                'TasksToExecute', 1);
            start(tim);
            % plotcomp;
        end;
    end % of function
end