function freeserial(obj)
%FREESERIAL Release MATLAB's hold on serial port.
%
%   FREESERIAL releases MATLAB's hold on all serial ports. 
%
%   FREESERIAL('PORT') releases MATLAB's hold on the specified port,
%   PORT. PORT can be a cell array of strings.  
%
%   FREESERIAL(OBJ) releases MATLAB's hold on the port associated with
%   serial port object, OBJ. OBJ can be an array of serial port objects.
%   
%   An error will be returned if a serial port object is connected 
%   to the port that is being freed. The FCLOSE command can be used 
%   to disconnect the serial port object from the serial port.
%
%   The serial port object uses the javax.comm package for communicating
%   with the serial port. Due to a memory leak in the javax.comm package,
%   the serial port object is not released from memory until you exit 
%   from MATLAB or the FREESERIAL function is called. The FREESERIAL 
%   function should be used only if you need to connect to the serial port
%   from another application after a MATLAB serial port object has been 
%   connected to that port and you do not want to exit MATLAB.
%
%   Note: this function is necessary only on the Windows platform.
%
%   See also INSTRUMENT/FCLOSE.
%

%    MP 4-11-00
%    Copyright 2000 The MathWorks, Inc. 
%    $Revision: 1.3 $  $Date: 2000/08/29 23:47:54 $

% Error checking.
if ~isa(obj, 'instrument')
    error('OBJ must be a string or a serial port object.');
end

if ~all(isvalid(obj))
    error('OBJ must contain valid serial port objects.');
end

% Verify that all objects are serial objects.
constructor = igetfield(obj, 'constructor');
if ~iscell(constructor)
    constructor = {constructor};
end

num = length(strmatch('serial', constructor));
if (num ~= length(constructor))
    error('OBJ must contain only serial port objects.');
end

% Store the warning state.
warnState = warning;
if ~strcmp(warnState, 'off')
    warning('on');
end

% Call freeSerial java method.
port = get(obj, {'Port'});
try
	com.mathworks.toolbox.instrument.SerialComm.freeSerial(port);
catch
    error(lasterr);
end

% Restore the warning state.
warning(warnState);