function value = boundary_is_legal ( w, p )

%*****************************************************************************80
%
%% boundary_is_legal() determines if a polyiamond boundary word is legal.
%
%  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)
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    05 November 2020
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    string W: the boundary word.
%
%    integer P(1,2): the boundary word starting point.
%
%  Output:
%
%    boolean VALUE: is TRUE if the boundary word is legal.
%

%
%  Only the characters 0 through 5 can appear.
%
  l = sum ( w == '0' ) + sum ( w == '1' ) + sum ( w == '2' ) ...
    + sum ( w == '3' ) + sum ( w == '4' ) + sum ( w == '5' );

  if ( length ( w ) ~= l )
    value = false;
    return;
  end
%
%  The boundary must close, so right and left, and up and down, 
%  must match.
%
  r = sum ( w == '1' ) + sum ( w == '2' );
  l = sum ( w == '4' ) + sum ( w == '5' );
  u = sum ( w == '0' ) + sum ( w == '5' );
  d = sum ( w == '2' ) + sum ( w == '3' );

  value = ( ( r == l ) & ( u == d ) );

  return
end

