function [v, x, y] = gasmotion(N, n, M, T, anim)

%Simulates the random 2D motion of a perfect gas.
%
% ==Inputs==
%
% N (optional, default 100) 
% is the number of steps (secs) in the simulation.
%
% n (optional, default 10) 
% is the number of gas molecules in the simulation.
%
% M (optional, default .18 for water vapor)
% is the molar mass of the gas in kg.
%
% T (optional, default 300)
% is the absolute temperature of the gas in degrees Kelvin.
% 
% anim (optional, default 1) 
% is the animation flag: 1 to animate, 0 not to animate.
% 
% ==Outputs==
% 
% v contains the speeds of the molecules during the simulation.
% 
% x and y contain the positions of the molecules during the simulation.

% Turn off warning regarding old version of fzero when calling Mxrnd:
warning off MATLAB:fzero:UndeterminedSyntax

% Set defaults:
if ~exist('N') | isempty(N)
    N = 100;
end
if ~exist('n') | isempty(n)
    n = 10;
end
if ~exist('M') | isempty(M)
    M = .18;
end
if ~exist('T') | isempty(T)
    T = 300;
end
if ~exist('anim') | isempty(anim)
    anim = 1;
end

% Run the simulation:
v = Mxrnd(N, n, M, T);    % Random number generator for speed distribution.
theta =2*pi*rand(N, n);    % Random number generator for angle distribution.
dx = v.*cos(theta);
dy = v.*sin(theta);
x  = cumsum(dx);
y  = cumsum(dy);

% Animate it:
if anim
     shg
     clf reset
     h = plot(x(1, :), y(1, :), '.b');
     axis([-1 1 -1 1]*10^5)  % Set axis limits here.     
     set(gcf,'doublebuffer', 'on', 'pos', [232 100 560 580], 'toolbar', 'none', ...
          'numbertitle', 'off', 'menubar', 'none', 'name', 'gasmotion')
     stop = uicontrol('units', 'norm', 'pos', [.02 .01 .10 .05], ...
                             'style', 'toggle', 'string', 'stop', 'value', 0);
                        
     i = 2;
     while (i < N) & (get(stop, 'value') == 0)
         pause(.2)
         set(h, 'Xdata', x(i, :), 'Ydata', y(i, :))
         drawnow
         i = i+1;
     end
     
     set(stop, 'style', 'push', 'string', 'close', 'callback', 'close(gcf)');
     
end

if nargout == 0
    clear
end