#!/usr/bin/env perl
#
# Read a triangle .poly file and create an input file for fea.
# Albert Danial August 25 2003
#
use lib "$ENV{TOPS_HOME}/apps/fea/util"; # for module TopsFEA
use TopsFEA ( load_csv_file, write_csv_file, build_empty_db, 
              dump_db, file_extension );
use Data::Dumper;
use Getopt::Std;
use vars qw ( $opt_a $opt_v $opt_c $opt_k );
use strict;
getopts('vka:c:');
# define a default csv schema if none was passed in
$opt_c = "$ENV{TOPS_HOME}/apps/fea/db/csv_schema.yaml" unless $opt_c;

my $TRIANGLE = "triangle"; # supply full path to the executable if not in path

die "$0 [-c_a_] <triangle_input>.poly

              Creates the file <triangle_input>.csv, a comma-separated value
              fea input file and/or <triangle_input>.db, an SQLite database
              file.  Schema files are defind in YAML.

             -a <max area>     Maximum area for any element.
             -c <csv schema>   Write .csv file using the provided schema.
             -v                Verbose output.
             -k                Keep triangle files xx.1.elem, xx.1.node, xx,1.poly

" unless @ARGV;
die "Must specify -c  <schema> option.\n" unless $opt_c;

# token material and shell properties
my %model_data = ();

@{$model_data{shell_prop}{'50_mil_alum'}} = ( { "material_id" => "aluminum"  }, 
                                              { "thick"       => 0.05        }
                                            );
@{$model_data{material}{aluminum}}      = ( {"E"          => 10.6e+6 },
                                            {"G"          => 4.0e+6  },
                                            {"nu"         => 0.33    },
                                            {"rho"        => 9.8e-2  },
                                            {"stress_max" => 20000   },
                                          );
# run triangle {{{1
my $poly_file = shift;
die "Cannot read $poly_file\n" unless -r $poly_file;

my ($extension, $root_name) = file_extension($poly_file);
die "Input file must have a .poly extension (got $poly_file).\n"
    unless $extension eq "poly";
my $triangle_node_file = "$root_name.1.node";
my $triangle_elem_file = "$root_name.1.ele";
$opt_a = "a$opt_a" if $opt_a;
my $command = "$TRIANGLE -pq$opt_a $poly_file";
print  $command, "\n";
system $command;
die "triangle did not produce output files\n"
    unless -r $triangle_node_file and -r $triangle_elem_file;
# 1}}} 
# load nodes from .1.node and remap ID's {{{1
#
srand 314159; # set random number seed for repeatability
my $nNode      = "";
my %nid_map    = (); #  $nid_map{ triangle ID  1..nNode  } = new ID
open(IN, $triangle_node_file) or die "Cannot open $triangle_node_file $!\n";
while (<IN>) {
    next unless /^\s*\d/;
    chomp;
    if (!$nNode) {
        $nNode = (split)[0];
        next;
    }
    die "No node count from $triangle_node_file" unless $nNode;
    my @node_data = split;   # ID, x, y, ?, ?
    # keep guessing until a random unused node ID is found
    while (!defined $nid_map{ $node_data[0] }) {
        $nid_map{ $node_data[0] } = int rand 1000000000;
    }
    @{$model_data{node}{$nid_map{ $node_data[0] } }} = ( 
               { "coord_in"  => 0             },
               { "x1"        => $node_data[1] },
               { "x2"        => $node_data[2] },
               { "x3"        => 0             },
               { "coord_out" => 0             },
                                                       );
}
close(IN);
# 1}}}
# load element connectivity data from .1.ele {{{1
#
my %element = ();      # element{eid}[1,2,3] = (node 1, node 2, node 3)
my $nElem   = "";
open(IN, $triangle_elem_file) or die "Cannot open $triangle_elem_file $!\n";
while (<IN>) {
    next unless /^\s*\d/;
    chomp;
    if (!$nElem) {
        $nElem = (split)[0];
        next;
    }
    die "No element count from $triangle_elem_file" unless $nElem;
    my $EID;
    # keep guessing until a random unused element ID is found
    do {
        $EID = int rand 1000000000;
    } while ( defined $element{$EID} );
    $element{$EID} = 1;
    my @ids = split; # triangle .1.ele file has elem ID, node 1, node 2, node3
    @{$model_data{tri3}{$EID}} = ( { "shell_prop" => "50_mil_alum"        },
                                   { "n1"         => $nid_map{ $ids[1] }  },
                                   { "n2"         => $nid_map{ $ids[2] }  },
                                   { "n3"         => $nid_map{ $ids[3] }  },
                                 );
        
        
        
}
close(IN);
# 1}}}
# delete .1.node  .1.ele  .1.poly files {{{1
if (!$opt_k) {
    foreach my $ext (qw( 1.node 1.ele 1.poly )) {
        unlink "$root_name.$ext" if -r "$root_name.$ext";
    }
}
# 1}}}

write_csv_file($root_name, $opt_c, \%model_data, $opt_v);
