function varargout = tar(tarFilename,files,varargin)
%TAR Compress files into a TAR-file.
%   TAR(TARFILENAME,FILES) creates a TAR-file with the name TARFILENAME
%   from the list of files and directories specified in FILES. 
%   
%   TARFILENAME is a string specifying the name of the TAR-file. The '.tar'
%   extension is appended to TARFILENAME if omitted. TARFILENAME's
%   extension may end in '.tgz' or '.gz'. In this case, TARFILENAME is
%   gzipped. 
%
%   FILES is a string or cell array of strings containing the list of files
%   or directories included in TARFILENAME. Paths specified in FILES must
%   be either relative to the current directory or absolute.  Relative
%   paths are stored in the TAR-file, but absolute paths are not.
%   Directories recursively include all of their content. 
%
%   TAR(TARFILENAME,FILES,ROOTDIR) allows the path for FILES to be
%   specified relative to ROOTDIR rather than the current directory.
%
%   ENTRYNAMES = TAR(...) returns a string cell array of the relative path
%   entry names contained in TARFILENAME.
%
%   Example
%   -------
%   % Tar all files in the current directory to the file backup.tgz
%   tar('backup.tgz','.');
% 
%   See also GZIP, GUNZIP, UNTAR, UNZIP, ZIP.

%   Copyright 2004-2005 The MathWorks, Inc.
%   $Revision: 1.1.6.1.2.1 $ $Date: 2005/01/14 21:54:18 $

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

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

% Open output stream.
try
   if isempty(compressFcn)
     tarFile = java.io.File(tarFilename);
     fileOutputStream = java.io.FileOutputStream(tarFile);
     tarOutputStream  = com.ice.tar.TarOutputStream(fileOutputStream);
   else
     tarFile = java.io.File(tarFilename);
     fileOutputStream = java.io.FileOutputStream(tarFile);
     tarOutputStream  = com.ice.tar.TarGzOutputStream(fileOutputStream);
   end
catch
   eid = sprintf('MATLAB:%s:openError',mfilename);
   error(eid,'Could not open "%s" for writing.',tarFilename);
end

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

% Close stream.
fileOutputStream.close;

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

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

% Create a Tar entry
file = java.io.File(entry.file);
archiveEntry = com.ice.tar.TarEntry(file);
archiveEntry.setName(entry.entry);
archiveEntry.setUnixTarFormat();

% Set timestamp.
lastModified = file.lastModified;
archiveEntry.setModTime(lastModified)
