function    plot_echogram(fname,rmax)
%
%    plot_echogram(fname,rmax)
%	  Plot an echogram display from signal envelope and click time data in an nc-format file.
%		fname is the name of the file.
%		rmax is the optional maximum range extent of the display in metres. Default is 10 m.
%
%    markjohnson@bios.au.dk
%    Creative Commons (CC BY 4.0)
%	  July 2021

if nargin<2,
   rmax = 10 ;
end

tst = -0.2e-3 ;		% start time of the image relative to click time
load_nc(fname) ;
fs = X.sampling_rate ;
[E cl] = extractcues(X.data,CL.data*fs,round(fs*[tst rmax/750]));
E = 20*log10(E) ;		% convert to Decibels
NL = prctile(E(:),1)	;	% estimate the noise floor

if exist('A','var'),	% if there is an acceleration variable, create two plots
	ax(1)=subplot(2,1,1)
end

imageirreg(cl/fs,(1:size(E(:,2)))'*750/fs+tst*750,E'-NL,1)
axis xy
caxis([0 60])	% set the colour axis to show a 60dB spread in echo-to-noise level
ylabel 'Distance (m)'
h=colorbar(ax(1),'East','color','w'); ylabel(h,'SNR (dB)');

if exist('R','var'),	% if there is a response time/distance variable, plot it
	hold on
	h=plot(R.data(:,1),R.data(:,2),'wo');
	set(h,'MarkerSize',10,'LineWidth',1) ;
end

if exist('A','var'),	% if there is an acceleration variable, create two plots
	xl = get(gca,'XLim') ;
	ax(2)=subplot(2,1,2)
	plot(((0:size(A.data,1)-1)/A.sampling_rate)+A.start_offset,A.data) ;
	set(gca,'XLim',xl) ; 
    linkaxes(ax,'x');
    ylabel 'Target acceleration (m/s^2)'
    xlabel 'Time relative to start of trial (s)'
    legend('x-axis','y-axis');
    
end
	