function newbridge = findtensions(bridge)
% find the tensions in a bridge given a bridge structure

N = length(bridge.beamlist);
M = length(bridge.nodelist);
% N+3 should equal 2M for a truss with no redundance
if N+3 ~= 2*M
   error('findtensions: inconsistent truss design.');
end

H = zeros(M,N);
V = zeros(M,N);
SH = zeros(M,3);
SV = zeros(M,3);

% set up the forces matrix
for k=1:N
   a = bridge.beamnode1(k);
   b = bridge.beamnode2(k);
   xa = bridge.nodex(a);
   ya = bridge.nodey(a);
   xb = bridge.nodex(b);
   yb = bridge.nodey(b);
   ang = atan2(yb-ya, xb-xa);
   H(a,k) = cos(ang);
   H(b,k) = cos(ang+pi);
   V(a,k) = sin(ang);
   V(b,k) = sin(ang+pi);
end
% set up the support matrices
for k=1:3
   if bridge.supportdir(k) == 0
      SV(bridge.supports(k),k) = 1;
   else
      SH(bridge.supports(k),k) = 1;
   end
end

%assemble the overall matrix
mat = [[H;V] [SH; SV]];
% the loads on the bridge; the - sign reflects positive forces being up and to the right
loads = -[bridge.loadsx; bridge.loadsy];
% find the solution
tensions = mat\loads;
newbridge = bridge;
newbridge.tensions = tensions;
