function [] = plot_bands(hor,ver,opac,color)
%plot_bands    Places shaded vertical bands in 2D graphs
%   plot_bands(HOR,VER,OPAC,COLOR) creates shaded rectangles at regions 
%     specified by HOR and VER.
%   First run plot_bands, then type hold on, then plot data as usual.
%
%   HOR is Tx1 vector of zeros and ones that determines horizontal 
%     locations.  Rectangles are placed where HOR(t) = 1.  The graph must 
%     have T elements on horizontal axis. 
%   VER = [YMIN YMAX] determines height of rectangles.
%   OPAC is number between 0 and 1 that determines opacity of shading, 
%     where 0 is invisible and 1 is fully opaque.
%   COLOR determines color of shading using color codes from PLOT command,
%     except 'k' indicates gray.
%
%  Example
%     plot_bands(hor,[ymin ymax],.25,'g')
%     hold on
%     plot(x,y_1,'options_1',...,x,y_p,'options_p')
%
%Version 2   Fixes bug that occurred when last sample point is equal to 1

%==========================================================================
% Encode color parameter
if color == 'b';        cp = [0 0 1];
elseif color == 'g';    cp = [0 1 0];
elseif color == 'r';    cp = [1 0 0];
elseif color == 'c';    cp = [0 1 1];
elseif color == 'm';    cp = [1 0 1];
elseif color == 'y';    cp = [1 1 0];
elseif color == 'k';    cp = [.8 8 .8];
else                    error('Incorrect color parameter specified')
end

%==========================================================================
% Encode horizontal locations of bands
ymin = ver(1); ymax = ver(2);
T = size(hor,1);
start = [false; hor(2:T)-hor(1:T-1) == 1];
if hor(1) == 1
    start(1) = true;
end
finish = [false; hor(2:T)-hor(1:T-1) == -1];
time = (1:T)';
if hor(end) == 1
    finish(T,1) = true;
end

bands = [time(start) time(finish)-1];
if hor(end) == 1
    bands(end,2) = T;
end

%==========================================================================
% Create rectangles using fill command
hold on
N = size(bands,1);
b = gobjects(N,1);      %Defines vector of empty graphics objects
for i = 1:N
    b(i) = fill([bands(i,1) bands(i,1), bands(i,2) bands(i,2)], ...
        [ymin ymax ymax ymin],cp);
end
set(b,'FaceAlpha',opac,'EdgeColor','none'); %Sets opacity and removes edge line
set(gca, 'Layer', 'top')        %Draws axis lines on top of rectangles
hold off

%                                               G. Ramey - UCSD - 4/9/2019


