% clean up for report
clc;

% determine y-length of secondary 'all' plots (match vox or all)
secplot_voxorall    =   1;

% define limits (show.fixedy)
lims.w.train.all    =   [-0.6,  1.0];
lims.w.train.vox    =   [-0.1,  0.8];

lims.w.test.all     =   [-0.6,  0.6];
lims.w.test.vox     =   [-0.1, 0.12];

lims.f.shape.all    =   [-0.6,  0.6];
lims.f.shape.vox    =   [-0.04, 0.13];

lims.f.size.all     =   [-0.6,  0.6];
lims.f.size.vox     =   [-0.04, 0.13];

lims.b.shape.all    =   [-1.0,  1.0];
lims.b.shape.vox    =   [-0.16, 0.3];

lims.b.size.all     =   [-1.0,  1.0];
lims.b.size.vox     =   [-0.16, 0.3];

if secplot_voxorall
    lims.w.train.all2   =   lims.w.train.vox;
    lims.w.test.all2    =   lims.w.test.vox;
    lims.f.shape.all2   =   lims.f.shape.vox;
    lims.f.size.all2    =   lims.f.size.vox;
    lims.b.shape.all2   =   lims.b.shape.vox;
    lims.b.size.all2    =   lims.b.size.vox;
else
    lims.w.train.all2   =   lims.w.train.all;
    lims.w.test.all2    =   lims.w.test.all;
    lims.f.shape.all2   =   lims.f.shape.all;
    lims.f.size.all2    =   lims.f.size.all;
    lims.b.shape.all2   =   lims.b.shape.all;
    lims.b.size.all2    =   lims.b.size.all;
end

% save figure?
savefig     =   show.saveit;
figpath     =   fullfile( paths.local, 'images');

if savefig && ~exist( figpath, 'dir')
    mkdir( figpath);
end

% retrieve some handy variables
sided       =   RS.(show.rois{1}).info.stats.sided;
cutoff      =   RS.(show.rois{1}).info.stats.cutoff;
mytest      =   RS.(show.rois{1}).info.mytest;
ctype       =   RS.(show.rois{1}).info.stats.corr;

all_cons    =   fields( RS.(show.rois{1}).data.vox.(show.metric));
nsubs       =   size( RS.(show.rois{1}).data.all.(show.metric).(all_cons{show.plot(1)}), 1);
conditions  =   all_cons( show.plot);

% default plot settings
transp      =   .2;     % opacity of error region
transp_i    =   .5;     % opacity of individual data

nsigs       =   3;      % number of significance levels (factor 10)
sig_spac    =   8;      % space used by significance reports (fraction of graph height)
sig_dist    =   40;     % distance between  (~size of) significance reports (fraction of graph height)

jitsize     =   0.5;    % jitter width of individual data points

a_size      =   12;     % text size of asterisks (across ROIs)
a_size_a    =   20;     % text size of asterisks (across ROIs)

marksize    =   6;      % marker size (condition averages)
capsize     =   10;     % cap size (condition averages)
ind_frac    =   0.3;    % size of individual data wrt condition averages

% additional settings for hemifield graphs
bandw       =   0.05;               % kernel size of density plot (#SD in classification metric)
scalef      =   10;                 % horizontal (down)scaling of density plot
pdist       =   0.1;                % horizontal separation of density plot
transp3     =   transp;             % transparency of density plot
lwidth      =   1;                  % linewidth of 95%-CI per hemifield
jits        =   rand( nsubs, 1);    % ensure same jitter for all participants

% legend
if contains( mytest, {'test', 'train'})
    
    cols    =   {'b',   'm',   'k'};
    cdir    =   'w';
    
    if strcmp( mytest, 'test')
        %typs    =   repmat( {'d'}, 1, length( cols));
        typs    =   {'d', 'o','s'};
        
    elseif strcmp( mytest, 'train')
        %typs    =   repmat( {'d'}, 1, length( cols));
        typs    =   {'d', 'o','s'};
    end
    typs    =   strcat( typs, '-');
    
elseif contains( mytest, {'shape', 'size'})
    
    cdir    =   RS.(show.rois{1}).info.direction;
    if strcmp( mytest, 'shape')
        cols    =   {'g',    'r',     'k',     'b'};
        typs    =   repmat( {'d'}, 1, length( cols));
    elseif strcmp( mytest, 'size')
        cols    =   {'g',    'r',     'k',     'm'};
        typs    =   repmat( {'o'}, 1, length( cols));
    end
    if strcmp( cdir, 'f')
        typs    =   strcat( typs, '-');
    elseif strcmp( cdir, 'b')
        typs    =   strcat( typs, '-');
    end
end

legends =   [conditions; '95% CIs'];
if ~any( contains(legends,'\'))
    legends =   strrep( legends, '_', '\_');
end

% datatypes
switch show.metric
    case {'acc', 'mfc', 'pfc'}
        metric_label = 'Classification accuracy (%)';
    case {'zdb', 'rdb'}
        metric_label = 'Classifier information (a.u.)';
end

% check max differences
if contains( mytest, {'size', 'shape'}) && all( contains( {'matching', 'mismatch'}, conditions))
    md = NaN( length( show.rois), 2);
    for nrt = 1:length( show.rois)
        
        % Open figure for current ROI
        gen_roi     =   show.rois{nrt};
        
        % find max differences
        y  =   RS.(gen_roi).data.all.(show.metric).difference(:,:,1);
        md(nrt,:)   =   [min(y/std(y)) max(y/std(y))];
    end
    
    [mroi,minmax]   =   find( abs(md) == max( abs( md(:))));
    maxnum          =   abs( md( mroi, minmax));
    difcols         =   [maxnum, -maxnum];
end

% start plotting (per ROI category)
for nrt = 1:length( show.rois)
    
    % Open figure for current ROI
    gen_roi     =   show.rois{nrt};
    figure('Name', gen_roi, 'NumberTitle', 'off')
    hold on
    
    % retrieve handy variables (plotting)
    vcount          =   RS.(gen_roi).info.voxels;
    X               =   1 : length( vcount);
    
    % retrieve stats and data
    voxstat =   RS.(gen_roi).stats.vox.(show.metric);
    voxdata =   RS.(gen_roi).data.vox.(show.metric);
    
    % plot confidence intervals
    for nplot = show.bars
        Y = [ voxstat.(all_cons{nplot}).ci(2,:), fliplr( voxstat.(all_cons{nplot}).ci(1,:))];
        h =   fill( [X fliplr(X)], Y, cols{nplot});
        set( h, 'facealpha', transp, 'EdgeColor', 'none')
    end
    
    % plot individual data
    jit     =   repmat( jitsize*(jits-0.5), 1, length( vcount));
    for nplot = show.indiv
        for np = 1:nsubs
            h2                  =   scatter( X+jit(np,:), voxdata.(all_cons{nplot})(np,:,1), [cols{nplot} typs{nplot}(1)], 'MarkerFaceColor', cols{nplot});
            h2.MarkerFaceAlpha  =   transp_i;
            h2.MarkerEdgeAlpha  =   0;
            h2.SizeData         =   6*marksize*ind_frac;
        end
    end
    
    % plot chance line
    plot( [0 length(X)+1], [0 0], 'k.:');
    
    % plot means
    for nplot = show.plot
        
        % plot means
        hl(nplot) = plot( X, voxstat.(all_cons{nplot}).mean, [cols{nplot} typs{nplot}], 'MarkerFaceColor', cols{nplot}, 'MarkerEdgeColor', 'k', 'MarkerSize', marksize); %#ok<SAGROW>
    end
    
    % retrieve some variables reflecting graph size
    if show.fixedy
        ylim( lims.(cdir).(mytest).vox);
    end
    theselims   =   ylim;
    
    % plot significance (using requested statistical method and null)
    for nplot = show.signi
        
        % retrieve y locations for signifance plots
        yloc = theselims(1) + diff(theselims)/sig_spac - diff(theselims)/sig_dist * find( show.signi==nplot);
        
        switch show.multi
            
            % choose method
            case {'tfce','none'}
                
                % get requested p values
                if strcmp( show.multi, 'tfce')
                    pvals   =   voxstat.(all_cons{nplot}).tfce.(show.null) / (3-sided);
                elseif strcmp( show.stats, 'ttype')
                    pvals   =   voxstat.(all_cons{nplot}).pvals;
                elseif strcmp( show.stats, 'prob')
                    pvals   =   RS.(gen_roi).null.vox.(show.metric).(all_cons{nplot}).pvals;
                end
                
                % plot asterisks
                for nsig = 1:nsigs
                    if nsig < nsigs
                        wsigs   =   pvals < (cutoff / 10^(nsig-1)) & pvals >= (cutoff / 10^(nsig));
                    else
                        wsigs   =   pvals < (cutoff / 10^(nsig-1));
                    end
                    sigsX   =   X( wsigs);
                    sigsY   =   ones(1, length( sigsX)) * yloc;
                    text( sigsX, sigsY, repmat('\ast',1,nsig), 'FontSize', a_size, 'Color', cols{nplot}, 'HorizontalAlignment', 'left');
                end
                
                
                % cluster-based corrected significance
            case 'clus'
                
                % retrieve significant clusters
                ks = voxstat.(all_cons{nplot}).clus.(show.null).sig_k;
                maxclus = max( ks);
                if maxclus > 0
                    
                    % plot significant clusters
                    for nclus = 1:maxclus
                        xloc = find( ks==nclus);
                        plot( xloc, ones(1, length( xloc))*yloc, [cols{nplot} '.-'], 'LineWidth', 4)
                    end
                end
        end
    end % end of plot significance loop
    
    % add legend
    [~, h_l] = legend( [hl(show.plot) h], legends, 'Location', 'east');
    lpatch   = findobj(h_l, 'type', 'patch');
    set( lpatch, 'FaceAlpha', transp);
    set( lpatch, 'FaceColor', [0 0 0]);
    
    % add ticks and labels
    xticks( X)
    xticklabels( vcount)
    ylabel( metric_label);
    xlabel( 'Voxel count');
    
    % final touch
    title( sprintf( 'Decoding per %s ROI size (%s data)', gen_roi, mytest));
    pbaspect([3 1 1]);
    hold off
    
    % save figure
    if savefig
        set( gcf, 'Renderer', 'painters')
        figname = sprintf( '%s_%s_%s_%s_%s', cdir, mytest, gen_roi, show.multi, show.metric);
        print( gcf, fullfile( figpath, figname), '-depsc');
    end
    
    % Report cluster significance of different conditions
    if strcmp( show.multi, 'clus')
        
        % printf info
        fprintf( '\n%s - cluster-level signifcance per condition (2-sided):\n\n', gen_roi);
        
        % iterate over conditions
        for nc = 1:length( conditions)
            
            % retrieve cluster indices for current condition/metric
            con_clus    =   voxstat.(conditions{nc}).clus.(show.null).sig_k;
            clus_sig    =   voxstat.(conditions{nc}).clus.(show.null).k_prob;
            nsigni      =   max( con_clus);
            
            if nsigni
                for ncl = 1:nsigni
                    c_size = sum( con_clus==ncl);
                end
                fprintf( '%s [%s] cluster %g/%g: \tp = %1.3f\n', gen_roi, conditions{nc}, ncl, nsigni, clus_sig(c_size));
            end
        end
        fprintf('\n==================================================\n')
    end
    
    % Create Figure for "all" ROI
    figure('Name', sprintf( '%s_2', gen_roi), 'NumberTitle', 'off')
    hold on
    
    % print info
    fprintf( '\n%s - Significance test for full ROI (%g-sided):\n\n', gen_roi, sided);
    
    % retrieve data
    allstat =   RS.(gen_roi).stats.all.(show.metric);
    alldata =   RS.(gen_roi).data.all.(show.metric);
    
    % plot individual data
    jit     =   repmat( jitsize*(jits-0.5), 1, length( conditions));
    for wplot = 1:length( conditions)
        
        % get data
        nplot   =   show.plot(wplot);
        mydata  =   alldata.(all_cons{nplot})(:,1,1)';
        
        % plot
        h                   =   scatter( wplot+jit(:,wplot), mydata, [cols{nplot} typs{nplot}(1)], 'MarkerFaceColor', cols{nplot});
        h.MarkerFaceAlpha   =   transp_i;
        h.MarkerEdgeAlpha   =   0;
        h.SizeData          =   6*marksize*ind_frac;
        
        % plot mean and CI
        ymean   =   allstat.(all_cons{nplot}).mean(1,1);
        ynegs   =   ymean - allstat.(all_cons{nplot}).ci(1);
        yposs   =   allstat.(all_cons{nplot}).ci(2) - ymean;
        errorbar( wplot, ymean, ynegs, yposs, [cols{nplot} typs{nplot}], 'MarkerFaceColor', cols{nplot}, 'MarkerEdgeColor', 'k', 'Color', 'k', 'MarkerSize', marksize, 'Capsize', capsize);
        
        % retrieve requested p-values
        if strcmp( show.stats, 'ttype')
            pvals   =   allstat.(all_cons{nplot}).pvals;
        elseif strcmp( show.stats, 'prob')
            pvals   =   RS.(gen_roi).null.all.(show.metric).(all_cons{nplot}).pvals;
        end
        
        % plot asterisks
        for nsig = 1:nsigs
            if nsig < nsigs
                wsigs   =   pvals < (cutoff / 10^(nsig-1)) & pvals >= (cutoff / 10^(nsig));
            else
                wsigs   =   pvals < (cutoff / 10^(nsig-1));
            end
            if wsigs
                sigsX   =   wplot;
                sigsY   =   theselims(1) + diff(theselims)/sig_spac - diff(theselims)/sig_dist;
                text( sigsX, sigsY, repmat('\ast',1,nsig), 'FontSize', a_size_a, 'Color', cols{nplot}, 'HorizontalAlignment', 'center');
            end
        end
        
        % report significance of large ROI
        fprintf( '%s [%s] condition: \tp = %1.3f\n', gen_roi, all_cons{nplot}, pvals);
    end
    
    % plot chance line
    xlims = [0.5 length( conditions)+0.5];
    plot( xlims, [0 0], 'k.:');
    
    % set y-limits
    if show.fixedy
        ylim( lims.(cdir).(mytest).all2);
    end
    theselims   =   ylim;
    
    % add ticks and labels
    xticks( 1:length( conditions))
    xticklabels( conditions)
    ylabel( metric_label);
    xlabel( 'Condition');
    xlim( xlims);
    
    % final touch
    title( sprintf( 'Full %s-ROI: %s', gen_roi, mytest));
    pbaspect([3 4 1]);
    hold off
    
    % save figure
    if savefig
        set( gcf, 'Renderer', 'painters');
        figname = sprintf( '%s_%s_%s_avg_%s', cdir, mytest, gen_roi, show.metric);
        print( gcf, fullfile( figpath, figname), '-depsc');
        pause(0.5);
    end
    
    fprintf('\n==================================================\n')
    
    % show contrasts
    if contains( mytest, {'size', 'shape'}) && all( contains( {'matching', 'mismatch'}, conditions))
        
        % get roi name
        m_roi   =   gen_roi;
        nplots  =   [1 2];
        
        % Create Figure for "all" ROI
        figure('Name', sprintf( '%s_contrast', m_roi), 'NumberTitle', 'off')
        hold on
        
        % prepare to save min max values (for determing y & color scaling)
        mm  =   NaN( 2,2);
                
        % get data
        yM(:,1) =   RS.(m_roi).data.all.(show.metric).matching(:,:,1);
        mM(:,1) =   RS.(m_roi).stats.all.(show.metric).matching.mean;
        cM(1,:) =   RS.(m_roi).stats.all.(show.metric).matching.ci;
        
        yM(:,2) =   RS.(m_roi).data.all.(show.metric).mismatch(:,:,1);
        mM(:,2) =   RS.(m_roi).stats.all.(show.metric).mismatch.mean;
        cM(2,:) =   RS.(m_roi).stats.all.(show.metric).mismatch.ci;
               
        yD      =   RS.(m_roi).data.all.(show.metric).difference(:,:,1);
        mD      =   RS.(m_roi).stats.all.(show.metric).difference.mean;
        cD      =   RS.(m_roi).stats.all.(show.metric).difference.ci;
        
        % get min max
        mm(wplot, :)    =   [ min( yM(:)), max( yM(:)) ];
        
        % retrieve requested p-values
        if strcmp( show.stats, 'ttype')
            pvals(1,:)   =   RS.(m_roi).stats.all.(show.metric).matching.pvals;
            pvals(2,:)   =   RS.(m_roi).stats.all.(show.metric).mismatch.pvals;
            pvals_d      =   RS.(m_roi).stats.all.(show.metric).difference.pvals;
        elseif strcmp( show.stats, 'prob')
            pvals(1,:)   =   RS.(m_roi).null.all.(show.metric).matching.pvals;
            pvals(2,:)   =   RS.(m_roi).null.all.(show.metric).mismatch.pvals;
            pvals_d      =   RS.(m_roi).null.all.(show.metric).difference.pvals;
        end
        
        % set bandwith
        bandw2 = bandw;
        
        % compute density
        [F2,XI2] = ksdensity( yM(:,2), 'Bandwidth', bandw2);
        [F1,XI1] = ksdensity( yM(:,1), 'Bandwidth', bandw2);
        
        % cutoff low value
        F2(F2<bandw2/10) = 0;
        F1(F1<bandw2/10) = 0;
        
        % scale and position
        F2 = F2/scalef;
        F1 = F1/scalef;
        b2 = 2+pdist;
        b1 = 1-pdist;
        b2b = 2-pdist;
        b1b = 1+pdist;
                
        % draw half violin plot
        patch( [ F2+b2, fliplr(  F2+b2)], [zeros( size( XI2)), fliplr( XI2)      ], cols{nplots(2)}, 'EdgeAlpha', 0', 'FaceAlpha', transp3);
        patch( [-F1+b1, fliplr( -F1+b1)], [XI1,                zeros( size( XI1))], cols{nplots(1)}, 'EdgeAlpha', 0', 'FaceAlpha', transp3);
  
        % get subject colors
        difcols     =   [maxnum, -maxnum];
        colpos      =   interp1( difcols, [0 1], yD/ std(yD), 'pchip');
        
        % draw individua subject data
        for np = 1:nsubs
            xxx = plot( [b1b b2b], yM(np,:), 'Color', [colpos(np) 1-colpos(np) 0]);
        end
        
        for wplot = 1:2  
            
            % draw error bar of full ROI
            hl(wplot) = errorbar( wplot, mM(wplot), mM(wplot)-cM(wplot,1), cM(wplot,2)-mM(wplot), 'ko', 'MarkerFaceColor', cols{nplots(wplot)}, 'CapSize', capsize, 'MarkerSize', marksize, 'Marker', typs{nplots(wplot)}(1));
            
            % plot asterisks
            for nsig = 1:nsigs
                if nsig < nsigs
                    wsigs   =   pvals < (cutoff / 10^(nsig-1)) & pvals >= (cutoff / 10^(nsig));
                else
                    wsigs   =   pvals < (cutoff / 10^(nsig-1));
                end
                if wsigs
                    sigsX   =   wplot;
                    sigsY   =   theselims(1) + diff(theselims)/sig_spac - diff(theselims)/sig_dist;
                    text( sigsX, sigsY, repmat('\ast',1,nsig), 'FontSize', a_size_a, 'Color', cols{nplots(wplot)}, 'HorizontalAlignment', 'center');
                end
            end
        end
        
        
        % plot chance line
        xlims = [0.5 2+0.5];
        plot( xlims, [0 0], 'k.:');
        
        % set y-limits
        if show.fixedy
            theselims = lims.(cdir).(mytest).all;
        else
            minmax      =   [min( mm(:,1)), max( mm(:,2))];
            theselims   =   [minmax(1)-diff( minmax)*0.1, minmax(2)+diff( minmax)*0.1];
        end
        ylim( theselims);
        
        % add ticks and labels
        xticks( 1:2)
        xticklabels( conditions(1:2))
        ylabel( metric_label);
        xlabel( 'Condition');
        xlim( xlims);
        
        % final touch
        title( sprintf( 'Full %s-ROI contrast (%s)', m_roi, mytest));
        pbaspect([1 2 1]);
        hold off
        
        % save figure
        if savefig
            set( gcf, 'Renderer', 'painters');
            figname = sprintf( '%s_%s_%s_con_%s', cdir, mytest, m_roi, show.metric);
            print( gcf, fullfile( figpath, figname), '-depsc');
            pause(0.5);
        end
        
    end  % end of show contrasts
    
    % correlate behavior
    if show.cor
        
        % determine correlation type
        switch ctype
            case 'Kendall'
                cname = 'T';
            case 'Pearson'
                cname = 'R';
            case 'Spearman'
                cname = 'Rho';
        end
        
        % select what to display
        if show.cor == 1
            wbehs = 1:size( RS.behav.b_data, 2);
        elseif show.cor == 2
            wbehs = 1:3;
        end
        
        % show info
        fprintf( '\n%s - correlations with behavior (%g-sided):\n\n', gen_roi, sided);
        colms = sprintf( '%s \t\t\t\t\t', RS.behav.labels{wbehs});
        fprintf( 'Columns: \t%s\n', colms(1:end-2))
        
        % iterate over conditions
        for nc = show.plot
            
            % retrieve neural data
            switch show.cdata
                case 'clus'
                    ppmeans = RS.(gen_roi).stats.vox.(show.metric).(all_cons{nc}).clus.(show.null).k_mean;
                case 'tfce'
                    wdata = RS.(gen_roi).stats.vox.(show.metric).(all_cons{nc}).tfce.(show.null)<cutoff/(3-sided);
                    ppmeans = mean( RS.(gen_roi).data.vox.(show.metric).(all_cons{nc})(:,wdata,1), 2);
                case 'all'
                    ppmeans = RS.(gen_roi).data.all.(show.metric).(all_cons{nc})(:,:,1);
            end
            
            % iterate over behavioral variables
            fprintf('%s:', all_cons{nc})
            for nbev = wbehs
                
                % skip if no data (e.g. if no significant cluster)
                if any( isnan( ppmeans))
                    continue
                end
                
                % compute and report correlation
                [r,p] = corr( ppmeans , RS.behav.b_data(:,nbev), 'Type', ctype);
                
                fprintf('\t%s = %1.2f, p = %1.3f\t\t', cname, r, p/(3-sided))
                
            end
            fprintf( '%s', newline);
        end
        fprintf('\n==================================================\n\n')
        
    end % end of correlations
end % end of ROI loop


% hemi-field plots
if isfield( show, 'hemi') && ~isempty( show.hemi)
    
    % iterate over requested ROIs
    for nroi = 1 : length( show.hemi)
        
        % define average and compound ROIs
        m_roi = show.hemi{nroi};
        l_roi = [m_roi(1:2) 'L'];
        r_roi = [m_roi(1:2) 'R'];
        
        % Create Figure for "all" ROI
        figure('Name', sprintf( '%s_hemi', m_roi), 'NumberTitle', 'off')
        hold on
        
        % print info
        fprintf( '\n%s - Significance test for full ROI (%g-sided):\n\n', m_roi, sided);
        
        % prepare to save min max values (for determing y length)
        mm  =   NaN( length( conditions),2);
        
        % plot individual data
        for wplot = 1:length( conditions)
            
            % get data
            nplot   =   show.plot(wplot);
            yM      =   RS.(m_roi).data.all.(show.metric).(all_cons{nplot})(:,:,1);
            yR      =   RS.(r_roi).data.all.(show.metric).(all_cons{nplot})(:,:,1);
            yL      =   RS.(l_roi).data.all.(show.metric).(all_cons{nplot})(:,:,1);
            
            mM      =   RS.(m_roi).stats.all.(show.metric).(all_cons{nplot}).mean;
            cM      =   RS.(m_roi).stats.all.(show.metric).(all_cons{nplot}).ci;
            mR      =   RS.(r_roi).stats.all.(show.metric).(all_cons{nplot}).mean;
            cR      =   RS.(r_roi).stats.all.(show.metric).(all_cons{nplot}).ci;
            mL      =   RS.(l_roi).stats.all.(show.metric).(all_cons{nplot}).mean;
            cL      =   RS.(l_roi).stats.all.(show.metric).(all_cons{nplot}).ci;
            
            % get min max
            mm(wplot, :)    =   [ min( [yR;yL]), max( [yR;yL])];
            
            % retrieve requested p-values
            if strcmp( show.stats, 'ttype')
                pvals   =   RS.(m_roi).stats.all.(show.metric).(all_cons{nplot}).pvals;
                pvals_l =   RS.(l_roi).stats.all.(show.metric).(all_cons{nplot}).pvals;
                pvals_r =   RS.(r_roi).stats.all.(show.metric).(all_cons{nplot}).pvals;
                
            elseif strcmp( show.stats, 'prob')
                pvals   =   RS.(m_roi).null.all.(show.metric).(all_cons{nplot}).pvals;
                pvals_l =   RS.(l_roi).null.all.(show.metric).(all_cons{nplot}).pvals;
                pvals_r =   RS.(r_roi).null.all.(show.metric).(all_cons{nplot}).pvals;
            end
            
            % compute density
            [FR,XIR] = ksdensity( yR, 'Bandwidth', bandw);
            [FL,XIL] = ksdensity( yL, 'Bandwidth', bandw);
            
            % cutoff low value
            FR(FR<bandw/10) = 0;
            FL(FL<bandw/10) = 0;
            
            % scale and position
            FR = FR/scalef;
            FL = FL/scalef;
            bR = wplot+pdist;
            bL = wplot-pdist;
            
            % determine jitter position of dots (within density plots)
            xRs =   interp1( XIR, FR, yR, 'pchip') *0.9;
            xLs =   interp1( XIL, FL, yL, 'pchip') *0.9;
            xR  =    xRs.*jits + bR;
            xL  =   -xLs.*jits + bL;
            
            % draw half violin plot
            patch( [ FR+bR, fliplr(  FR+bR)], [zeros( size( XIR)), fliplr( XIR)      ], cols{nplot}, 'EdgeAlpha', 0', 'FaceAlpha', transp3);
            patch( [-FL+bL, fliplr( -FL+bL)], [XIL,                zeros( size( XIL))], cols{nplot}, 'EdgeAlpha', 0', 'FaceAlpha', transp3);
            
            % draw conf intervals
            ycR =   round( interp1( XIR, 1:length(XIR), cR, 'pchip'));
            ycL =   round( interp1( XIL, 1:length(XIL), cL, 'pchip'));
            cFR =   FR(ycR(1):ycR(2));
            cFL =   FL(ycL(1):ycL(2));
            cXR =   XIR(ycR(1):ycR(2));
            cXL =   XIL(ycL(1):ycL(2));
            
            patch( [ cFR+bR, bR*ones(1, length( cXR))], [cXR, fliplr( cXR)], cols{nplot}, 'EdgeAlpha', 0', 'FaceAlpha', transp3);
            patch( [-cFL+bL, bL*ones(1, length( cXL))], [cXL, fliplr( cXL)], cols{nplot}, 'EdgeAlpha', 0', 'FaceAlpha', transp3);
            
            % draw scattered dots (within density plots)
            scatter( xR, yR, cols{nplot}, 'MarkerFaceColor', cols{nplot}, 'Marker', typs{nplot}(1), 'SizeData', round( marksize*ind_frac), 'MarkerFaceAlpha', transp_i, 'MarkerEdgeAlpha', transp_i);
            scatter( xL, yL, cols{nplot}, 'MarkerFaceColor', cols{nplot}, 'Marker', typs{nplot}(1), 'SizeData', round( marksize*ind_frac), 'MarkerFaceAlpha', transp_i, 'MarkerEdgeAlpha', transp_i);
                       
            % draw error bar of full ROI
            hl(wplot) = errorbar( wplot, mM, mM-cM(1), cM(2)-mM, 'ko', 'MarkerFaceColor', cols{nplot}, 'CapSize', capsize, 'MarkerSize', marksize, 'Marker', typs{nplot}(1));
            
            % plot asterisks
            for nsig = 1:nsigs
                if nsig < nsigs
                    wsigs   =   pvals < (cutoff / 10^(nsig-1)) & pvals >= (cutoff / 10^(nsig));
                else
                    wsigs   =   pvals < (cutoff / 10^(nsig-1));
                end
                if wsigs
                    sigsX   =   wplot;
                    sigsY   =   theselims(1) + diff(theselims)/sig_spac - diff(theselims)/sig_dist;
                    text( sigsX, sigsY, repmat('\ast',1,nsig), 'FontSize', a_size_a, 'Color', cols{nplot}, 'HorizontalAlignment', 'center');
                end
            end
            
            % report significance of hemi ROI
            fprintf( '%s-%s [%s] condition: \tp = %1.3f\n', l_roi(1:2), l_roi(3), all_cons{nplot}, pvals_l);
            fprintf( '%s-%s [%s] condition: \tp = %1.3f\n', r_roi(1:2), r_roi(3), all_cons{nplot}, pvals_r);
        end
        
        fprintf('\n==================================================\n')
        
        % plot chance line
        xlims = [0.5 length( conditions)+0.5];
        plot( xlims, [0 0], 'k.:');
        
        % set y-limits
        if show.fixedy
            theselims = lims.(cdir).(mytest).all;
        else
            minmax      =   [min( mm(:,1)), max( mm(:,2))];
            theselims   =   [minmax(1)-diff( minmax)*0.1, minmax(2)+diff( minmax)*0.1];
        end
        ylim( theselims);
        
        % add ticks and labels
        xticks( 1:length( conditions))
        xticklabels( conditions)
        ylabel( metric_label);
        xlabel( 'Condition');
        xlim( xlims);
        
        % final touch
        title( sprintf( 'Full %s-ROI per hemi (%s)', m_roi, mytest));
        pbaspect([3 4 1]);
        hold off
        
        % save figure
        if savefig
            set( gcf, 'Renderer', 'painters');
            figname = sprintf( '%s_%s_%s_hemi_%s', cdir, mytest, m_roi, show.metric);
            print( gcf, fullfile( figpath, figname), '-depsc');
            pause(0.5);
        end
        
    end % end of hemi-ROI loop
end % end of hemi if-statement