function A = constructA( Locations, support, bar )
% CONSTRUCTA,  constructs the truss stability matrix A in A^TCA. 
% 
%  Alex Townsend, April 2015. 

% Construct A one bar at a time. 
A = zeros( size(bar, 1),  2*size(Locations,1) ); 
for j = 1:size(bar, 1) 
    % Get coordinate locations: 
    pin1x = Locations(bar(j,1), 1);
    pin1y = Locations(bar(j,1), 2);
    pin2x = Locations(bar(j,2), 1); 
    pin2y = Locations(bar(j,2), 2);
    
    % Calculate angles: 
    dx = pin1x - pin2x;
    dy = pin1y - pin2y; 
    d2 = sqrt(dx^2 + dy^2);
    cost = dx/d2;
    sint = dy/d2; 
    
    % Workout the corresponding row of A: 
    A(j, [2*bar(j,1)-1 2*bar(j,1) 2*bar(j,2)-1 2*bar(j,2) ]) = ...
                    [cost sint -cost -sint] ; 
end

% If there are supports, then remove the columns.  No displacement 
% at that pin: 
for j = numel(support): -1 : 1
    A(:, [2*support(j)-1 2*support(j)]) = [ ];
end

end