function bsplinePlot(t, n, knot_treatment)
% bsplinePlot: show the basis function set or its (numerical) derivative.
%
%   bsplinePlot(t, n, knot_treatment)
%
% Creates a bunch of subplots that show all the b-spline basis functions
% for a particular set of knots.
%
% Input Parameters:
%
%   t: Vector of knots.  There is no need to replicate the first and last
%   knots.  They will automatically be replicated so that they appear n+1
%   times.
% 
%   n: Scalar.  Degree of the b-spline basis set.
%
%   knot_treatment: String.  For degree > 1, we normally need additional
%   knots.  This input argument specifies what to do (default is
%   'replicate'):
%
%     'none': Use the knot vector as supplied.
%     'replicate': Replicate the knots at each end of the knot vector.
%     'dummy': Create dummy knots beyond the ends of the knot vector.
%
% Ian Mitchell for CPSC 303, 2/8/08.

  if(nargin < 3)
    knot_treatment = 'replicate';
  end
  
  figure;

  % To help choose the range of plotting.
  knot_range = max(t) - min(t);
  plot_range = [ min(t) - 0.1 * knot_range, max(t) + 0.1 * knot_range ];
  xs = linspace(plot_range(1), plot_range(2), 401)';
  max_y = 0;

  % Provide the extra knots.
  switch(lower(knot_treatment))
   case 'none'
    % do nothing.
   case 'replicate'
    t = [ t(1) * ones(n, 1); t; t(end) * ones(n,1) ];
   case 'dummy'
    t = [ 2 * t(1) - flipud(t(2:n+1)); t; ...
          2 * t(end) - flipud(t(end-n:end-1)) ];
   otherwise
    error('Unknown knot_treatment: %s', knot_treatment);
  end
  
  % Parameters.
  m = length(t) - 1;
  num_bases = m - n - 1;

  % Evaluate all of the basis functions and plot them.
  for j = 0 : num_bases

    subplot(num_bases+1, 1, j+1);
    ys = bsplineBasis(xs, t, j, n);

    % Keep track of the largest value we have seen, so that we can scale
    % all plots equally.
    max_y = max([ ys; max_y ]);

    % Show the results.
    plot(xs, ys, 'b.');

  end
  
  % Make the plots comparable.
  for j = 0 : num_bases
    
    subplot(num_bases+1, 1, j+1);
    axis([ plot_range, 0, max_y ]);
    ylabel([ 'j = ' num2str(j) ]);
    
  end
  
  % Make the plot pretty.
  subplot(num_bases+1, 1, num_bases + 1);
  xlabel('x');
  subplot(num_bases+1, 1, 1);
  title([ 'B-spline bases n = ' num2str(n) ', m = ' num2str(m) ...
          ', knot\_treatment = ' knot_treatment ]);
