%LBLHIST - Function that plots the reply instance distribution for the
%    channels of the LBL navigation transceiver
%
%        [n,x] = lblhist( data, m_lbl_ping_time, channels );
%
%    B. A. Moran, 22-Mar-1996

%    Copyright (C) 1996-1998
%    Massachussetts Institute of Technology
%    Sea Grant AUV Laboratory
%    $Id: lblhist.m,v 1.1 2000/01/10 19:08:04 rob Exp $	

function [n,x] = lblhist( data, ping, channels, pos )

				% position of window
if nargin > 3, winpos( pos ); end

				% find pings (pre/post Haro styles)
if finite(mean(data(:,ping)))
    tp = find( data(:,ping) > 0 );
else
    tp = find( finite(data(:,ping)) );
end

if isempty( tp )
   text( 0.5, 0.5, 'No data available', ...
        'Units', 'normal', 'HorizontalAlignment', 'Center' );
else
				% initialize reply count per channel
    rcnt = zeros( length(tp), 1 );
				% append with last cycle in order to
				% span all possible reply periods
    tp = [tp; length(data)];

				% count replies per channel
    for i=1:length(tp)-1
        rows = tp(i):tp(i+1)-1;
        rcnt(i) = sum(any( data(rows,channels) > 0.02 ));
    end
				% generate histogram
    [n,x] = hist( rcnt, 0:length(channels) );
				% normalize rates by 100%
    n = 100*n/sum(n);
				% display bar graph
    bar( x, n, 'r' );
    set( gca, 'XGrid', 'off', 'YGrid', 'on' );
				% label the bars with value, make text
				% fall within borders of plot
    for i=1:length(n)
        h = text( x(i), n(i), sprintf('%.1f', n(i)) );
        if n(i)/max(n) > 0.9
            set( h, 'Horizontal', 'center', 'Vertical', 'top' );
        else
            set( h, 'Horizontal', 'center', 'Vertical', 'bottom' );
        end
    end
end
				% basic formatting
set( gca, 'Box', 'on', 'XLim', [-1 length(channels)+1], ...
    'XTick', 0:length(channels) );

title( 'Distribution of Reply Counts' )
xlabel( 'detected replies' )
ylabel( 'frequency (%)' )

