#!/usr/bin/perl -w
#!/usr/local/bin/perl -w
#!/usr/bin/env perl
#
# Albert Danial Nov 16 2003
#
use lib "$ENV{TOPS_HOME}/apps/fea/util"; # for module TopsFEA
use TopsFEA qw ( %nNodes_in_element );
use Getopt::Std;
use vars qw ( $opt_s $opt_t );
use File::Basename;
use strict;
getopts('st:');

$opt_t = 1.0e-6 unless $opt_t;

my $script = basename $0;
getopts('ne');
die "$script [-st:] <.db file>
                  Merge nodes that are within a specified tolerance
		  in all three x,y,z directions.  The default
		  tolerance is 1.0e-6.

             -s        Show coincident nodes but don't merge them.
             -t <tol>  Change the tolerance to <tol>.

" unless @ARGV;


my $db_file = shift @ARGV;
die "Cannot read $db_file" unless -r $db_file;

my $dbh = DBI->connect("dbi:SQLite:dbname=$db_file","","");
my $st;
my $node_ref = $dbh->selectall_arrayref(
                       "select id,x1,x2,x3 from node order by x1,x2,x3");
my $TOL        = $opt_t;
my @coincident = ();
my $nNodes     =  scalar @{$node_ref};
for (my $i = 1; $i < $nNodes; $i++) {
    next unless abs($node_ref->[$i][1] - $node_ref->[$i-1][1]) < $TOL; # X1
    next unless abs($node_ref->[$i][2] - $node_ref->[$i-1][2]) < $TOL; # X2
    next unless abs($node_ref->[$i][3] - $node_ref->[$i-1][3]) < $TOL; # X2
    push @coincident, [ $node_ref->[$i-1][0], $node_ref->[$i][0] ];
    printf "%10s == %10s\n", $node_ref->[$i-1][0], $node_ref->[$i][0] if $opt_s;
}
if (@coincident) {
    foreach my $pair (@coincident) {
        printf "%10s == %10s\n", $pair->[0], $pair->[1];
    }
    printf "Found %d coincident pairs.\n", scalar @coincident;
} else {
    printf "All %d nodes are more than %.2e units apart.\n", $nNodes, $TOL;
}
