function export(targetObjectInstances, varargin)
%TARGET.EXPORT    Export.
%   TARGET.EXPORT(targetFeatureObject) exports the specified target data to
%   a MATLAB function, registerTargets.m. When you execute the generated
%   function, it adds the target data to MATLAB memory. Use the generated 
%   file to share definitions between sessions and machines.
%
%   TARGET.EXPORT(targetFeatureObject, 'FileName', fileName) exports the 
%   specified target data to a MATLAB function with the specified fileName.
%
%   TARGET.EXPORT(targetFeatureObject, 'Overwrite', overwriteFlag) 
%   overwrites the MATLAB function file if it already exists and 
%   overwriteFlag is true. If the function file exists and overwriteFlag is
%   false (default), an error is produced.
%
%   See also TARGET.ADD

%   Copyright 2019 The MathWorks, Inc.

    % Inputs should be an array, cell array or scalar value containing 1 or
    % more target.Object instances
    validateattributes(targetObjectInstances, {'target.Object', 'cell'}, {'vector'}, 'target.export');

    % Process cell
    if iscell(targetObjectInstances)
        invalidElements = cellfun(@(e) ~isa(e, 'target.Object') || ~isscalar(e), targetObjectInstances);
        if any(invalidElements)
            error(message('targetrepository:Command:CellArrayMustContainTargetObjects'));
        end

        targetObjectInstances = [targetObjectInstances{:}];
    end
    
    % Process varargin, these should be name - value pairs providing
    % options to the add call.
    parser = inputParser();
    parser.FunctionName = 'target.export';
    
    parser.addParameter('FileName', '');
    parser.addParameter('Overwrite', false);
    
    parser.parse(varargin{:});
    
    arguments = parser.Results;
    
    tr = targetrepository.create();    
    matlabExport = tr.getFileExport(targetrepository.FileExportType.Matlab);
    matlabExport.OverwriteOutput = arguments.Overwrite;
    
    if ~isempty(arguments.FileName)
        matlabExport.Path = arguments.FileName;
    end
    
    matlabExport.run(targetObjectInstances);
end

