#! /bin/sh
# This script tests: pgmnoise
# Also requires:

# These tests are for examining the integrity of the random number
# generator.  There is some overlap between the tests here and tests
# in pgmnoise.test, but the tests here are better focused for
# diagnosing problems with the random number generator.
#
# Test 1 is for determining the kind of random number generator in
# use.
#
# Test 2 prints random numbers in an output format close to what the
# test in the original Mersenne Twister code produces.
#
# If these tests fail, subsequent tests which depend on random numbers
# will fail too.  There is no provision (beyond remarks in the script
# files) for generators other than the Mersenne Twister in those
# tests.

echo "Test 1: Should produce:"

echo "P2"
echo "12 1"
echo "1023"
echo "720 296 192 858 101 57 298 629 804 1019 64 617"
echo "Above output is for Mersenne Twister"

pgmnoise -maxval=1023 -randomseed=3791 -plain 12 1

echo
echo "Test 2: Mersenne Twister random number generator"
echo "Should produce:"

echo "3499211612  581869302 3890346734 3586334585  545404204"
echo "4161255391 3922919429  949333985 2715962298 1323567403"
echo " ... "
echo " 297480282 1101405687 1473439254 2634793792 1341017984"
echo " Total 1000 integers, 200 lines"
echo

# Use perl to avoid mawk limitation
# (cannot convert 32 bit integers)

perlPgmProcessorProgram='
  if (($#F+1) == 10) {
    for (my $i = 0; $i <= 9; $i += 2) {
      my $r = $F[$i + 1] * 65536 + $F[$i];
      printf "%10u ", $r;
    }
    print "";
  }
'

pgmnoise -randomseed=5489 -plain -maxval=65535 10 200 | \
  perl -walne "$perlPgmProcessorProgram"

# The above outputs (10 * 200 / 2) = 1000 samples.

#    Method to generate output for Test 2 from original
#    Mersenne Twister source code
#
# Download Mersenne Twister code.  See lib/util/randmersenne.c for URL.
# Edit mt19937ar.c:
#   In function main() at bottom of file, replace
#     init_by_array(init, length);
#   with
#     init_genrand(5489UL);
#
# We need only the output of genrand_int32().
# Remove the second loop which produces double-precision floating point
# random numbers with genrand_real2().
#
# Compile: gcc mt19937ar.c -o mt1000
# Execute: ./mt1000

# 1000 may seem like a large number of samples but there is a reason
# for this.  The generator produces random integers in batches of 624.
# The number of samples must be larger than 624 to ensure proper
# generation in batches after the first.

# If you encounter problems, adjust the 200 (rows) above and tweak
# the code in mt19937ar.c accordingly to produce more random numbers.
