function varargout = unzip(zipFilename,varargin)
%UNZIP Extract the contents of a zip file.
%   UNZIP(ZIPFILENAME) extracts the archived contents of ZIPFILENAME into
%   the current directory.
%
%   ZIPFILENAME is a string specifying the name of the ZIP-file. The '.zip'
%   extension is appended to ZIPFILENAME if omitted. ZIPFILENAME may
%   include the directory name; otherwise, the file must be in the current
%   directory or in a directory on the MATLAB path.
%
%   UNZIP(ZIPFILENAME,OUTPUTDIR) extracts the contents of ZIPFILENAME into
%   the directory OUTPUTDIR.
%
%   UNZIP(URL, ...) extracts the zip contents from an Internet URL. The URL
%   must include the protocol type (e.g., "http://"). The URL is downloaded
%   to the temp directory and deleted.
%
%   FILENAMES = UNZIP(...) extracts the zip archive and returns the
%   relative path names of the extracted files into the string cell array,
%   FILENAMES.
%
%   Examples
%   --------
%   % Copy the demos html files to the directory 'archive'
%   % Zip the demos html files to demos.zip
%   zip('demos.zip','*.html',fullfile(matlabroot,'demos'))
%   % Unzip demos.zip to the directory archive
%   unzip('demos','archive')
%
%   % Unzip and list Cleve Moler's Numerical Computing with MATLAB examples
%   % to the output directory 'ncm'.
%   url ='http://www.mathworks.com/moler/ncm.zip';
%   ncmFiles = unzip(url,'ncm')
%
%   See also GZIP, GUNZIP, TAR, UNTAR, ZIP.

%   Copyright 1984-2004 The MathWorks, Inc.
%   $Revision: 1.4.2.3 $ $Date: 2004/11/23 20:40:04 $

error(nargchk(1,2,nargin,'struct'));
error(nargoutchk(0,1,nargout,'struct'));

% Argument parsing.
[zipFilename, outputDir, url, urlFilename] = parseUnArchiveInputs( ...
   mfilename, zipFilename, {'zip'}, 'ZIPFILENAME', varargin{:});

% Extract zip contents
try
  zipJavaFile  = java.io.File(zipFilename);
  % Validate the zipfile
  zipFile = java.util.zip.ZipFile(zipJavaFile);
  fileInStream = java.io.FileInputStream(zipJavaFile);
  zipInStream  = java.util.zip.ZipInputStream(fileInStream);
catch
  error('MATLAB:unzip:invalidZipFile','Invalid zip file "%s".',zipFilename);
end
try
  files = extractArchive(outputDir, zipInStream, mfilename);
catch
  cleanup;
  rethrow(lasterror)
end

cleanup;
if nargout == 1
   varargout{1} = files;
end

%--------------------------------------------------------------------------
   function cleanup
      fileInStream.close;
      zipInStream.close;
      zipFile.close;
      if url && ~isempty(urlFilename) && exist(urlFilename,'file')
         delete(urlFilename)
      end
   end
end

