/*
    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"

void equal( void )

{
  long int iequal=0, max_equal=0, inol=0, inod=0, max_node=0, nnod=0, 
    iuknwn=0, found=0, length=0, ieq=0, swit=0, ldum=0, 
    equal[DATA_ITEM_SIZE], dof_label[MUKNWN], *equal_nodes=NULL;
  double rdum=0., ddum[MDIM], val[MUKNWN], *node_dof=NULL;

  db_max_index( DOF_EQUAL, max_equal, VERSION_NORMAL, GET );
  db_max_index( NODE, max_node, VERSION_NEW, GET );
  if ( max_equal>=0 ) {
    swit = set_swit(-1,-1,"equal");
    if ( swit ) pri( "In routine EQUAL" );
    equal_nodes = get_new_int( max_node+1 ); 
    db( DOF_LABEL, 0, dof_label, ddum, ldum, VERSION_NORMAL, GET );
    for ( iequal=0; iequal<=max_equal; iequal++ ) {
      if ( db_active_index( DOF_EQUAL, iequal, VERSION_NORMAL ) ) {
        db( DOF_EQUAL, iequal, equal, ddum, length, VERSION_NORMAL, GET );
        nnod = 0; array_set( val, 0., nuknwn );
        for ( inod=0; inod<=max_node; inod++ ) {
          if ( db_active_index( NODE, inod, VERSION_NEW ) ) {
            geometry( inod, ddum, equal, found, rdum, ddum, rdum,
              ddum, NODE_START_REFINED, PROJECT_EXACT, VERSION_NORMAL );
            if ( found ) {
              equal_nodes[nnod] = inod;
              nnod++; assert( nnod<=max_node+1 );
              node_dof = db_dbl( NODE_DOF, inod, VERSION_NEW );
              for ( iuknwn=0; iuknwn<nuknwn; iuknwn++ )
                val[iuknwn] += node_dof[iuknwn];
            }
          }
        }
        if ( nnod>1 ) {
          for ( inol=0; inol<nnod; inol++ ) {
            inod = equal_nodes[inol];
            for ( ieq=0; ieq<length-2; ieq++ ) {
              array_member( dof_label, equal[2+ieq], nuknwn, iuknwn );
              if ( iuknwn<0 || iuknwn>nuknwn ) db_error( DOF_EQUAL, iequal );
              node_dof = db_dbl( NODE_DOF, inod, VERSION_NEW );
              node_dof[iuknwn] = val[iuknwn]/nnod;
            }
          }
        }
      }
    }
    delete[] equal_nodes;
    if ( swit ) pri( "Out routine EQUAL" );
  }

}
