/*
    Copyright (C) 1998  Dennis Roddeman
    email: dennis.roddeman@uibk.ac.at

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software Foundation 
    59 Temple Place, Suite 330, Boston, MA, 02111-1307, USA
*/

#include "tochnog.h"

#define MAX_NODE_NODE 300

void nod_nod( long int version )

{
  long int inol=0, inod=0, jnol=0, jnod=0, nnol=0, indx=0,
    element=0, max_element=0, max_node=0, length=0, 
    max_length_node_node=0, swit=0, ldum=0, 
    el[1+MNOL], nodes[MNOL], *node_node=NULL, *nnode=NULL;
  double ddum[1];

  swit = set_swit(-1,-1,"nod_nod");
  if ( swit ) pri( "In routine NOD_NOD" );

  db_max_index( NODE, max_node, version, GET );
  db_max_index( ELEMENT, max_element, version, GET );
  length = (1+max_node)*MAX_NODE_NODE;
  node_node = get_new_int( length );
  array_set( node_node, 0, length );
  length = 1+max_node;
  nnode = get_new_int( length );
  array_set( nnode, 0, length );
  for ( element=0; element<=max_element; element++ ) {
    if ( db_active_index( ELEMENT, element, version ) ) {
      db( ELEMENT, element, el, ddum, length, version, GET );
      nnol = length - 1; array_move( &el[1], nodes, nnol );
      for ( inol=0; inol<nnol; inol++ ) {
        inod = nodes[inol];
        for ( jnol=0; jnol<nnol; jnol++ ) {
          jnod = nodes[jnol];
          if ( inod!=jnod &&
               !array_member(&node_node[inod*MAX_NODE_NODE],jnod,nnode[inod],ldum) ) {
            if ( nnode[inod]>MAX_NODE_NODE-1 ) {
              pri( "Error detected in routine nod_nod." );
              pri( "The mesh seems to be not correct." );
              exit(TN_EXIT_STATUS);
            }
            indx = inod*MAX_NODE_NODE+nnode[inod];
            node_node[indx] = jnod;
            nnode[inod]++;
            if ( nnode[inod]>max_length_node_node ) max_length_node_node = nnode[inod];
          }
        }
      }
    }
  }
  db_data_length_put( NODE_NODE, max_length_node_node );
  for ( inod=0; inod<=max_node; inod++ ) {
    if ( db_active_index( NODE, inod, version ) ) {
      if ( nnode[inod]==0 ) 
        delete_node( inod, version );
      else {
        length = nnode[inod];
        db( NODE_NODE, inod, &node_node[inod*MAX_NODE_NODE], ddum, 
          nnode[inod], version, PUT );
      }
    }
  }
  delete[] node_node;
  delete[] nnode;

  if ( swit ) pri( "Out routine NOD_NOD" );
}
