#!/usr/bin/perl
#
# file:         corr.pl
# purpose:      compute iterative correlations of a square matrix
# created:      pasha aug 15 2008
# modified:     pasha feb 17 2016
# modification: dieonwarn replaced by the code
#

use strict;
use warnings;
use Getopt::Long;
use CorrMatrix;

# turn warnings into errors
$SIG{__WARN__} = sub { die ($_[0]); };

# maximal number of iterations when checking for convergence
use constant MAX_NUM_ITER => 10039709;

############### process command line ###########################################
my ($num_iter, $print);
GetOptions (
	    'num=n'   => \$num_iter,
	    'print=n' => \$print,
	    'help'     => sub
	    {
	      print STDERR << "EOF"
Computes iterative corelation matrices.
Usage: corr.pl [--num=<n>] [--print=<m>] <matrix>
       corr.pl --help
where:
Writes to stdout.
--num    (optional) number of iterations; if not given, iterate until
         convergence;
--print  (optional) to print every <m> matrices; if not given, print only the 
         final result;
<matrix> matrix file in the text row-major format;
--help   this help.
EOF
  ;
	      exit (0);
	    },
	   );
if (scalar (@ARGV) != 1)
  {
    print (STDERR "wrong number of arguments; try --help\n");
    exit (-1);
  }
################################################################################


# read input file
my $matrix = new CorrMatrix();
open (F, '< ' . $ARGV[0]) || die ('error opening file ' . $ARGV[0]);
my ($n, $n_curr, @a, $j);
my $line = 0;
for (<F>)
  {
    $line++;
    s/^\s*//;  # trim starting and trailing white space in each line
    s/\s*$//;
    @a = split (/\s+/, $_);
    $n = scalar (@a);
    if ($line == 1)
      {
		$matrix->set_size ($n);
      }
    else
      {
		$n_curr = scalar (@a);
		if ($n_curr != $n)
		  {
			print
			  (STDERR 
			   "number of elements at line $line (${n_curr}) differs from the number of elements at the first line (${n})\n");
			close (F);
			exit (-1);
		  }
      }
    for ($j=0; $j < $n; $j++)
      {
		$matrix->set ($line, $j+1, $a[$j]);
      }
  } # end of loop thru input file 
if ($n != $line)
  {
    print(STDERR "matrix is not a square one (number of rows=${line}, number of columns=${n}\n");
  }
close (F);


# compute the given number of iterations of the correlation matrix
$matrix->iter ((defined ($num_iter) ? $num_iter : MAX_NUM_ITER),
			   (defined ($print)    ? $print    : 0));

exit (0);

__END__
