function [sys,x0]=vdlmintm(t,x,u,flag, lb, ub, xi, ts)
%VDLMINTM Vectored discrete limited integrator implementation.
%	This M-file is an example of a discrete 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-8-93

	flag = abs(flag);

	if (flag == 2)
		% Is it a sample hit (within a tolerance of 1e-8) ?
		if (abs(round(t/ts) - t/ts) < 1e-8)
			% compute the unlimitted discrete states
			sys = x + u * ts;

			% 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

			% now limit them
			z = find((x <= lb & u < 0) | (x >= ub & u > 0));
			sys(z) = x(z);
		else
			% not a sample hit, return the current states
			sys = x;
		end
  
	elseif (flag == 3)
		%
		% If this is a sample hit, compute the next output
		% if not, then return an empty matrix, SIMULINK, will
		% know that we don't want the output to change in that
		% case
		%
		if (abs(round(t/ts) - t/ts) < 1e-8)
			sys = x;
		else
			sys = [];
		end

	elseif (flag == 4) % Return next sample hit
		% ns stores the number of samples
		ns = t/ts;

		% This is the time of the next sample hit.
		sys = (1 + floor(ns + 1e-13 * (1 + ns))) * ts;
  
	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 = [0, llb, llb, llb, 0, 0]';

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

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

		elseif (lxi > 1)
			sys = [0, lxi, 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 = [0, -1, -1, -1, 0, 0]'; 
		end
		x0 = xi;
	else 
		sys = [];
	end
