% find the Tee bar top
% assume that the Tee bar is the longest side in one set that has 3 other
% shorter segments that total about the same length
% also reorder the set to give the crossbar 1st, the 2 sidebars second
% and the foot last

function [fnd,head] = doheadset(lineset)

  fnd = 0;
  head = zeros(4,4);
  seglen = zeros(4,1);
  for i = 1 : 4
    seglen(i) = norm(lineset(i,1:2) - lineset(i,3:4));
  end
  sortlen = sort(seglen);

  % reject if 2nd longest segment is more than 80% of longest
  % or sum of shortest is more than 120% of longest
  
  if (sortlen(3) > 0.8*sortlen(4)) ...
        | (1.2*sortlen(4) < sortlen(1) + sortlen(2) + sortlen(3))
    return
  end

  ind1 = find(seglen == sortlen(4));
  head(1,:) = lineset(ind1,:);

  % foot is furthest from tee
  
  perp = [head(1,4)-head(1,2),head(1,1)-head(1,3)];
  perp = perp/norm(perp);       % perpendicular vector
  headist = zeros(4,1);
  for i = 1 : 4
    headist(i) = abs(perp*[lineset(i,1)-head(1,1),lineset(i,2)-head(1,2)]');
  end
  ind4 = find(headist == max(headist));
  head(4,:) = lineset(ind4,:);

  % get rest
  
  nextind = 2;
  for i = 1 : 4
    if i ~= ind1 & i ~= ind4
      head(nextind,:) = lineset(i,:);
      nextind = nextind + 1;
    end
  end
  fnd = 1;
