function varargout = zip(zipFilename,files,varargin)
%ZIP Compress files into a ZIP-file.
%
%   ZIP(ZIPFILENAME, FILES) creates a ZIP-file with the name ZIPFILENAME
%   from the list of files and directories specified in FILES.
%
%   ZIPFILENAME is a string specifying the name of the ZIP-file. The '.zip'
%   extension is appended to ZIPFILENAME if omitted. 
%
%   FILES is a string or cell array of strings containing the list of files
%   or directories included in ZIPFILENAME. Paths specified in FILES must
%   be either relative to the current directory or absolute.  Relative
%   paths are stored in the ZIP-file, but absolute paths are not.
%   Directories recursively include all of their content. 
%
%   ZIP(ZIPFILENAME, FILES, ROOTDIR) allows the path for FILES to be
%   specified relative to ROOTDIR rather than the current directory.
%
%   ENTRYNAMES = ZIP(...) returns a string cell array of the relative path
%   entry names contained in ZIPFILENAME.
%
%   Example
%   -------
%   % Zip all *.m and *.mat files in the current directory 
%   % to the file backup.zip
%   zip('backup',{'*.m','*.mat'});
%
%   See also GZIP, GUNZIP, TAR, UNTAR, UNZIP.

%   Copyright 1984-2005 The MathWorks, Inc.
%   $Revision: 1.4.2.5.2.1 $ $Date: 2005/01/14 21:54:19 $

% Check number of arguments
error(nargchk(2,3,nargin,'struct'))
error(nargoutchk(0,1,nargout,'struct'));

% Parse arguments.
[files, rootDir, zipFilename] =  ...
   parseArchiveInputs(mfilename, zipFilename,  files, varargin{:});

% Open output stream.
try
   zipFile = java.io.File(zipFilename);
   fileOutputStream = java.io.FileOutputStream(zipFile);
   zipOutputStream  = java.util.zip.ZipOutputStream(fileOutputStream);
catch
   eid = sprintf('MATLAB:%s:openError',mfilename);
   error(eid,'Could not open "%s" for writing.',zipFilename);
end

% Create the archive
try
   archive = createArchive(zipFilename, files, rootDir, ...
      @createArchiveEntry, zipOutputStream, mfilename);
catch
   fileOutputStream.close;
   zipFile.delete;
   rethrow(lasterror);
end

% Close stream.
fileOutputStream.close;

if nargout == 1
   varargout{1} = archive;
end

%--------------------------------------------------------------------------
function zipEntry = createArchiveEntry(entry)

% Create a zip entry
zipEntry = java.util.zip.ZipEntry(entry.entry);

% Set timestamp.
file = java.io.File(entry.file);
lastModified = file.lastModified;
zipEntry.setTime(lastModified);
