function [] = figure5;

%
% function [] = figure5;
%
% plots figure 5 of 
%
% Einhäuser, W., Thomassen, S., & Bendixen, A. (2017). Using binocular
% rivalry to tag foreground sounds: towards an objective visual
% measure for auditory multistability. Journal of Vision, 17:34,
% 1-19. 
%
%

% load data
load exp3_data gain ixLow ixHigh


figure(5);
clf;

% all audio-visual blocks
[dprime,signedGain] = computeFigureData([5:8,10:13],gain,ixLow,ixHigh);
subplot(2,2,1);
plot(1,dprime,'ko');
axis([.5 1.5 -.5 1.5]);
ylabel('d prime');
set(gca,'XTick',[]);

subplot(2,2,3);
plot(1,signedGain,'ko');
axis([.5 1.5 -1 1]);
ylabel('signed gain');
set(gca,'XTick',[]);


% compare first to second set of audio-visual blocks
[dprime1,signedGain1] = computeFigureData([5:8],gain,ixLow,ixHigh);
[dprime2,signedGain2] = computeFigureData([10:13],gain,ixLow,ixHigh);

subplot(2,2,2);
plot([1,2],[dprime1;dprime2],'k.-');
axis([.5 2.5 -.5 2.5]);
ylabel('d prime');
set(gca,'XTick',[1,2]);
set(gca,'XTickLabel',{'5-8','10-13'});


subplot(2,2,4);
plot([1,2],[signedGain1;signedGain2],'k.-');
axis([.5 2.5 -1 1]);
ylabel('signed gain');
set(gca,'XTick',[]);
set(gca,'XTickLabel',{'5-8','10-13'});


function [dprime,signedGain] = computeFigureData(blocks,gain,ixLow,ixHigh)

dprime = nan(1,8);
signedGain = nan(1,8);


for s = 1 : 8

  % variables for d'
  
  hit = 0;
  miss = 0;
  fA  = 0;
  corR = 0;
  
  % Hit: Low-pitch tone is reported in the foreground and the gain is positive.
  % Miss: Low-pitch tone is reported in the foreground and the gain is negative.
  % False alarm: High-pitch tone is reported in the foreground and the gain is positive.
  % Correct rejection: High-pitch tone is reported in the foreground and the gain is negative.
  

  % variables for signed gain
  sumGain   = 0;
  validData = 0;
  
  for b = blocks

	hit  = hit  + sum(gain{s,b,1}(ixLow{s,b})>0.0);
	miss = miss + sum(gain{s,b,1}(ixLow{s,b})<0.0);
	fA   = fA   + sum(gain{s,b,1}(ixHigh{s,b})>0.0);
	corR = corR  + sum(gain{s,b,1}(ixHigh{s,b})<0.0);
	
	sumGain = sumGain + ...
		nansum(gain{s,b,1}(ixLow{s,b}))-nansum(gain{s,b,1}(ixHigh{s,b}));
	validData = validData + ...
		sum(isfinite(gain{s,b,1}(ixLow{s,b})))+sum(isfinite(gain{s,b,1}(ixHigh{s,b})));
	
  end
  dprime(s) = norminv(hit/(hit+miss))-norminv(fA/(fA+corR));
  signedGain(s) = sumGain/validData;
end