function [ w2, p2 ] = boundary_sort ( w, p )

%*****************************************************************************80
%
%% boundary_sort() sorts the boundary word of a polyiamond.
%
%  Discussion:
%
%    The boundary word describes how to trace the boundary by starting
%    at a base point (i,j), and taking a sequence of steps of unit length 
%    in one of 6 directions, as suggested by this diagram:
%
%          5-----0-----*
%      ^  / \   / \   /
%     /  /   \ /   \ /
%    J  4-----P-----1
%      / \   / \   /
%     /   \ /   \ /
%    *-----3-----2
%
%          I-->
%
%    If the current position P has parallelogram coordinates (I,J), then
%    the step of given index moves to
%
%      0  (I,  J+1)
%      1  (I+1,J  )
%      2  (I+1,J-1)
%      3  (I,  J-1)
%      4  (I-1,J  )
%      5  (I-1,J+1)
%
%    Sorting "rotates" the boundary word to produce the lexically smallest 
%    base point P.
%
%  Example:
%
%    w  = 432105, p = [5,10]
%
%    w2 = 321054, p2 = [4,9];
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    13 November 2020
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    string W: the boundary word.  
%
%    integer P(1,2): the boundary word starting point.
%
%  Output:
%
%    string W2: the boundary word for the sorted shape.  
%
%    integer P2(1,2): the boundary word starting point for the sorted shape.
%
  w2 = w;
  p2 = p;

  wn = length ( w2 );
  p3 = p;

  for in = 1 : wn

    c = w(in);

    if ( c == '0' )
      p3(2) = p3(2) + 1;
    elseif ( c == '1' )
      p3(1) = p3(1) + 1;
    elseif ( c == '2' )
      p3(1) = p3(1) + 1;
      p3(2) = p3(2) - 1;
    elseif ( c == '3' )
      p3(2) = p3(2) - 1;
    elseif ( c == '4' )
      p3(1) = p3(1) - 1;
    elseif ( c == '5' )
      p3(1) = p3(1) - 1;
      p3(2) = p3(2) + 1;
    end

    if ( ( p3(1) < p2(1) ) || ...
         ( p3(1) == p2(1) && p3(2) < p2(2) ) )
      p2 = p3;
      w2 = [ w(in:end), w(1:in-1) ];
    end

  end

  return
end

