function count = addDestination(name, destinations, distances)
% addDestination Add a new destination to the graph. 
% Must specify distances from new destination to all other destinations in
% the graph. Returns count of destinations in the graph (number of nodes).
%
%   name: character vector name of the new destination.
%   destinations: names of the other destinations in the graph. Cell array
%        of character vectors.
%   distances: numeric vector of distances to other destinations.
%
% Note: distances{n} is the distance from name to destinations{n}.  

% Copyright 1984-2019 The MathWorks, Inc.
% All Rights Reserved. 
   
    count = 0;
    c = mps.cache.connect('TravelingSalesman','Connection','ScratchPad');
    
    % If we can't load the distance data, we can't do any work.
    if loadDistanceData('ScratchPad','TravelingSalesman') == false
        error('Failed to load distance data. Cannot continue.');
    end
    
    % Changing global data, so we need to acquire a lock on it.
    lk = mps.sync.mutex('DistanceData','Connection','ScratchPad');
    if acquire(lk,10)
        g = c.Distances;
        
        % Make sure the graph hasn't changed since we last read it. (If it
        % has new destinations, then our destinations and distances arrays
        % are no longer valid and we must fail.)
        newDestinations = setdiff(g.Nodes.Name, destinations);
        if ~isempty(newDestinations)
            error('MPS:Example:TSP:MissingDestinations', ...
                  'Add distances for missing destinations: %s', ...
                strjoin(newDestinations,', '));
        end
        
        src = repmat({name},1,numel(destinations));
        g = addedge(g, src, destinations, distances);
        c.Distances = g;
        release(lk);
        count = numnodes(g);
    end
    
end
