function makeicns(fileName, varargin)
%MAKEICNS  Create a MAC OSX ICNS file out of the list of PNG files provided.
%
%   Usage:
%       makeicns [output file] [PNG icon files ...]
%
%   Description:
%   
%       filename - The name of the output ICNS file
%       varargin - Names of the PNG image files to combine into an ICNS file
%
%   Example:
%       makeicns('out.icns','image1.png','image2.png')
%
%   For more information on the ICNS file format and header description, see:
%   https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/iconutil.1.html
%
% Copyright 2013 The MathWorks, Inc.

if ~ismac
    return
end

tempIconDir = fullfile(tempdir,'deploytool.iconset');

% Copy the images to a temporary directory ending with .imageset
if exist(tempIconDir, 'file')
    delete(fullfile(tempIconDir,'*'));
    rmdir(tempIconDir);
end
mkdir(tempIconDir);    
tempLocations = cellfun(@(x) buildTempName(tempIconDir,x), varargin, 'UniformOutput', false);
cellfun(@copyfile, varargin, tempLocations);

% Create the ICNS file filename - if this command fails we fail quietly
% and have a non-zero return status
[~, ~] = system(['iconutil --convert icns --output "' fileName '" "' tempIconDir '"']);

% Remove the tempdir
delete(fullfile(tempIconDir,'*'));
rmdir(tempIconDir);
end

function fullname = buildTempName(tempFileDir, f)
    [~,name,ext] = fileparts(f);
    fullname = fullfile(tempFileDir,[name ext]);
end