function [sys, x0] = vlimintm(t, x, u, flag, lb, ub, xi)
%VLIMINTM Vectored limited integrator implementation.
%	This M-file is an example of a limited integrator S-Function.
%	This illustrates how to use the size entry of -1 to build
%	a S-Function that can accomodate a dynamic input/state width.
%
%	Copyright (c) 1990-94 by The MathWorks, Inc.
%	Rick Spada 9-3-93

	flag = abs(flag);

	if (flag == 1)
		% compute the unlimitted derivatives
	  	sys = u;

		% if a scalar is given for a bound, it needs to be
		% expanded to the proper size vector
	  	if (length(lb) == 1),
			lb = lb * ones(size(u));
	  	end
		if (length(ub) == 1),
	    	ub = ub * ones(size(u));
		end

		% limit the derivatives
	  	z = find((x <= lb & u < 0) | (x >= ub & u > 0));
	  	sys(z) = zeros(size(z));
  
	elseif (flag == 3)
		% the output equals the current states
		sys = x;
  
	elseif (flag == 0)
  	  	llb = length(lb);
		lub = length(ub);
		lxi = length(xi);

		if (llb > 1)
			if (lxi ~= llb)
				xi = xi * ones(llb, 1);
			end
			sys = [llb, 0, llb, llb, 0, 0]';

		elseif (lub > 1)
			if (lxi ~= lub)
				xi = xi * ones(lub, 1);
			end
			sys = [lub, 0, lub, lub, 0, 0]';

		elseif ((llb == 0) | (lub == 0))
			error('Empty matrices not allowed')

		elseif (lxi > 1)
			sys = [lxi, 0, lxi, lxi, 0, 0]';

		else
			% set the number of inputs, outputs, and states to -1
			% to indicate vectorization, i.e. that the appropriate
			% number will be determined at run time
			sys = [-1, 0, -1, -1, 0, 0]'; 
		end
		x0 = xi;  
	else 
		sys = [];
	end

