function zp = sample_limits ( limits, par_num, zp )

%*****************************************************************************80
%
%% sample_limits() enforces limits on a sample variable.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    24 January 2018
%
%  Author:
%
%    Original FORTRAN90 version by Guannan Zhang.
%    MATLAB version by John Burkardt.
%
%  Input:
%
%    real LIMITS(2,PAR_NUM), the parameter limits.
%
%    integer PAR_NUM, the total number of parameters.
%    1 <= PAR_NUM.
%
%    real ZP(PAR_NUM), a variable, whose entries,
%    if necessary, will be "folded" so that they lie within the limits.
%
%  Output:
%
%    real ZP(PAR_NUM), a variable, whose entries,
%    if necessary, will be "folded" so that they lie within the limits.
%
  for i = 1 : par_num

    w = limits(2,i) - limits(1,i);

    if ( w == 0.0 )

      zp(i) = limits(1,i);

    elseif ( w < 0.0 )

      fprintf ( 1, '\n' );
      fprintf ( 1, 'SAMPLE_LIMITS - Fatal error!\n' );
      fprintf ( 1, '  LIMITS(2,I) < LIMITS(1,I).\n' );
      error ( 'SAMPLE_LIMITS - Fatal error!\n' );

    else

      while ( zp(i) < limits(1,i) )
        zp(i) = zp(i) + w;
      end

      while ( limits(2,i) < zp(i) )
        zp(i) = zp(i) - w;
      end

    end

  end

  return
end
