function [ v_num, v, v_p ] = polyomino_periodic_variants ( r_m, r_n, r, ...
  p_num, p, d )

%*****************************************************************************80
%
%% polyomino_periodic_variants finds periodic variants of polyominoes.
%
%  Discussion:
%
%    We are supplied with an array P of polyominoes.  We wish to "tile" a
%    periodic region R, using, for each I, D(I) copies of polyomino P(I).
%    We are asked to return an array containing all the variants of these 
%    polynomials that can be generated by rotation and reflection.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    11 December 2018
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    integer R_M, R_N, the number of rows and columns in the representation
%    of the region R.
%
%    integer R(R_M,R_N), the binary representation of the region.
%
%    integer P_NUM, the number of polyominoes.
%
%    integer P(R_M,R_N,P_NUM), for each value K, P(:,:,K) is a matrix of 
%    0's and 1's representing the K-th polyomino.  Each matrix should be 
%    "top-left tight", that is, there should be a 1 in row 1, and a 1 in 
%    column 1.  However, there may be trailing rows and columns of zeros.
%
%    integer D(P_NUM), the number of copies of each polyomino that
%    may be used.  If D(I) <= 0, no variants of polyomino I will be generated.
%
%  Output:
%
%    integer V_NUM, the number of variants found.
%
%    integer V(R_M,R_N,V_NUM), the variants.
%
%    integer V_P(V_NUM); if V(:,:,I) is a variant of the polyomino
%    P(:,:,L), then V_P(I) is set to L.
%
  v_num = 0;
  v = [];
  v_p = [];

  for l = 1 : p_num
%
%  Only use polyominoes for which the user has set D to at least 1.
%
    if ( 1 <= d(l) )
%
%  Make a condensed version of the polyomino called "Q".
%
      [ q_m, q_n, q ] = polyomino_condense ( r_m, r_n, p(1:r_m,1:r_n,l) );
%
%  Generate all variants of Q.
%
      for reflect = 0 : 1
        for rotate = 0 : 4

          [ s_m, s_n, s ] = polyomino_transform ( q_m, q_n, q, rotate, reflect );
%
%  Apply periodicity to the variant, making a subset of R.
%
          t = polyomino_periodicity_apply ( r_m, r_n, r, s_m, s_n, s );
%
%  Reject this variant if any entry of T is greater than 1.
%
          acceptable = true;

          if ( 1 < max ( max ( t ) ) )

            acceptable = false;
%
%  Reject this variant if it has already been generated.
%
          else

            for k = 1 : v_num
              if ( t(1:r_m,1:r_n) == v(1:r_m,1:r_n,k) )
                acceptable = false;
                break;
              end
            end

          end
%
%  If variant is legal and new, add it to the catalog.
%
          if ( acceptable )
            v_num = v_num + 1;
            v(1:r_m,1:r_n,v_num) = t(1:r_m,1:r_n);
            v_p(v_num) = l;
          end

        end
      end

    end

  end

  return
end
