function h = subplotExperiment(m, sim, t, varargin)
% subplotExperiment plots a simulation each output in its own subplot. 
%
% This function plots a simulation generated by simulate. If there are
% multiple outputs from the model then each output is displayed in its 
% own subplot.
%
% h = subplotExperiment(m, sim) plots the output of the simulation
%       generated by simulate.
%
% h = subplotExperiment(m, sim, t) plots the output of the simulation
%       generated by simulate at the given times. 
%
% h = subplotExperiment(m, sim, t, ...) additional arguments are passed to
%       the plot command. For example:
%           plotsimn(m, sim, t, 'd:');
%       will results in dotted lines with diamond markers at the time
%       points where the simution was evaluated 
%
% Arguments:
% m     The model that was simulated
% sim   The simution returned from simulate
% t     The time interval to be plotted
%       If t is a scalar then simution will be plotted from time 0 to t
%       If t is length > 1 then the simution will be ploted only at times t
% h     A column vector of handles to lineseries graphics objects,
%       one handle per line

% This work is licensed under the Creative Commons Attribution-Noncommercial-No Derivative 
% Works 3.0 United States License. To view a copy of this license, visit 
% http://creativecommons.org/licenses/by-nc-nd/3.0/us/ or send a letter to Creative Commons,
% 171 Second Street, Suite 300, San Francisco, California, 94105, USA.

% see also: simulate, plotExperiment, plot
error(nargchk(2, inf, nargin, 'struct'))

if(nargin == 2)
    tPlot = sim.t;
elseif(length(t) == 1)
    tPlot = [sim.t(sim.t<t), t];
else
    tPlot = t;
end
   
h = [];

rows = ceil(sqrt(m.nY));
cols = ceil(m.nY/rows);

yPlot = sim.y(tPlot);

for k=1:m.nY
    subplot(cols, rows, k);

    hi = plot(tPlot, yPlot(k,:), varargin{:});
    xlabel('Time');
    ylabel('Concentration');
    title(m.yNames{k});
    h  = [h; hi];
end
   