/*
 * 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 PURPOUSE. See the GNU
 * General Public License for more details.
 *
 * You should have recieved a copy of the GNU General Public License
 * along with this program; if not write to the Free Software
 * Foundation, inc., 59 Temple Place, Suite 330, Boston MA 02111-1307
 * USA
 */

package run;

/**
 * Insert the type's description here. Creation date: (2001-08-20 21:59:33)
 */
import java.util.*;
import java.io.*;

import run.readers.FembicReader;

import uka.karmi.rmi.RemoteException;
import jp.sync.*;
import jp.lang.*;


public class SmackCluster extends RemoteObject {
    private int number_of_elements;
    private int number_of_trackers;
    private int number_of_nodes;
    private int number_of_materials;
    private int number_of_controls;
    private int number_of_constraints;
    private int number_of_loads;
    private RplVector constraintlist;
    private RplVector loadlist;
    private RplVector nodelist;
    private RplVector elementlist;
    private RplVector trackerlist;
    private RplVector materiallist;
    private volatile double time,ttemp, exported_ttemp;
    private int i;
    private Controlset controlset;
    private Element temporary_element;
    private Tracker temporary_tracker;
    private Constraint temporary_constraint;
    private Node temporary_node;
    private Writer resultwriter;
    private TrackWriter trackwriter;
    private java.lang.String filename;
    private double timestep;
    private boolean failure_is_set = false;        
    private boolean autostep;
    private int nr_of_CPUs, client_nr;
    private SmackCluster[] cluster_nodes;
    private int[] nodeindicies, elementindicies;
    
    /**
     * Smack constructor comment.
     */
    public SmackCluster(int nr_of_CPUs, int client_nr) {
        super();
        this.nr_of_CPUs = nr_of_CPUs;
        this.client_nr = client_nr;
    }

    /**
     * Insert the method's description here. Creation date: (2001-08-20
     * 22:03:32)
     */
    public void assembleMassMatrix()
        throws Error
    {
        int i;
        Node temp_node;
        Element temp_element;
        Constraint temp_constraint;

        // Loop elements
        // Calculate element mass distribution and add to node
        // Calculate element intertia
        // Transform to global directions
        // Add to node inertia matrix
        // End loop
        try {
            System.out.println("Assembling Elements");

            for (i = 0; i < number_of_elements; i++) {
                temp_element = (Element) elementlist.elementAt(i);
                temp_element.assembleMassMatrix();
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            throw new Error(
                "\n* Error during Assembly phase - Terminating" + e
            );
        } catch (NullPointerException e) {
            throw new Error(
                "\n* Error during Assembly phase of Element\n* This error could be the result of a missing (or wrong) parameter in the indata file \n* " +
                e
            );
        } catch (Error e) {
            throw new Error(
                "\n* Error during Assembly phase of Element\n* This error could be the result of a missing (or wrong) parameter in the indata file \n* " +
                e
            );
        }

        // Loop nodes
        // Calculate main inertias
        // Keep largest I
        // End loop
        try {
            System.out.println("Assembling Nodes");

            for (i = 0; i < nodelist.size(); i++) {
                temp_node = (Node) nodelist.elementAt(i);
                temp_node.determineMassMatrix();
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            throw new Error(
                "\n* Error during Assembly phase - Terminating" + e
            );
        } catch (NullPointerException e) {
            throw new Error(
                "\n* Error during Assembly phase of Node \n* This error could be the result of a missing (or wrong) parameter in the indata file \n* " +
                e
            );
        } catch (Error e) {
            throw new Error(
                "\n* Error during Assembly phase of Node \n* This error could be the result of a missing (or wrong) parameter in the indata file \n* " +
                e
            );
        }
        
        try {
            System.out.println("Assembling Constraints");

            for (i = 0; i < number_of_constraints; i++) {
                temp_constraint = (Constraint) constraintlist.elementAt(i);
                temp_constraint.determineMassMatrix(nodelist);
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            throw new Error(
                "\n* Error during Assembly phase - Terminating" + e
            );
        } catch (NullPointerException e) {
            throw new Error(
                "\n* Error during Assembly phase of Constraint \n* This error could be the result of a missing (or wrong) parameter in the indata file \n* " +
                e
            );
        } catch (Error e) {
            throw new Error(
                "\n* Error during Assembly phase of Constraint \n* This error could be the result of a missing (or wrong) parameter in the indata file \n* " +
                e
            );
        }
    }

    /**
     * This method initializes the problem in the following steps: 1. Create a
     * file object so that the indata file can be read. 2. Question the file
     * object of all the variables etc that is required to set up all the
     * memory variables etc correctly. 3. Set up the variables 4. Finished
     * Creation date: (2001-08-20 22:01:54)
     *
     * @param filename java.lang.String
     */
    public void initialize(String fname, SmackCluster[] nodes)
        throws Error, Exception
    {
    	
        this.filename = new String(fname);
		this.cluster_nodes = nodes;

        // Create an indata file object that we can ask for the things we require
        Reader indatafile = new FembicReader(filename);

        // Set number of elements, materials and nodes
        try {
            number_of_elements = indatafile.numberOfElements();
            number_of_trackers = indatafile.numberOfTrackers();
            number_of_materials = indatafile.numberOfMaterials();
            number_of_nodes = indatafile.numberOfNodes();
            number_of_constraints = indatafile.numberOfConstraints();
            number_of_loads = indatafile.numberOfLoads();
            number_of_controls = indatafile.numberOfControls();
        } catch (java.text.ParseException e) {
            // If we end up here, something is wrong in the indata file
            throw new Error("Error in initialization phase \n" + e);
        }

        //Set up the arrays to handle the entries
			elementlist = new RplVector(nodes);
			trackerlist = new RplVector(nodes);
			materiallist = new RplVector(nodes);
			nodelist = new RplVector(nodes);
			constraintlist = new RplVector(nodes);
			loadlist = new RplVector(nodes);
			controlset = new Controlset(nodes);
      
        try {
            //Fill the constraintlist array
            System.out.println("Reading Constraints");
            indatafile.open();

            for (i = 0; i < number_of_constraints; i++) {
                constraintlist.addElement(
                    indatafile.getNextConstraint(nodelist)
                );
            }
            
            indatafile.close();
            System.out.println("Filled constraintlist");
            
            //Fill the loadlist array
            System.out.println("Reading Loads");
            indatafile.open();

            for (i = 0; i < number_of_loads; i++) {
                loadlist.addElement(indatafile.getNextLoad(nodelist));
            }

            indatafile.close();
            System.out.println("Filled loadlist");
            
            //Fill the nodelist array
				indatafile.open();
				System.out.println("Reading Nodes");

				for (i = 0; i < number_of_nodes; i++) {
					nodelist.addElement(indatafile.getNextNode(constraintlist,
							loadlist));
				}

				indatafile.close();
				System.out.println("Filled nodelist");

            //Fill the materials array
            indatafile.open();
            System.out.println("Reading Materials");

            Material m;

            for (i = 0; i < number_of_materials; i++) {
                m = indatafile.getNextMaterial();

                if (m.failure_strain_is_set || m.failure_stress_is_set) {
                    failure_is_set = true;
                }

                materiallist.addElement(m);
            }

            indatafile.close();
            System.out.println("Filled materiallist");

            //Fill the Elements array
				indatafile.open();
				System.out.println("Reading Elements");

				for (i = 0; i < number_of_elements; i++) {
					elementlist.addElement(indatafile.getNextElement(
							materiallist, nodelist, loadlist));
				}

				indatafile.close();
				System.out.println("Filled elementlist");
            
            //Fill the Trackers array
            indatafile.open();
            System.out.println("Reading Trackers");

            for (i = 0; i < number_of_trackers; i++) {
                trackerlist.addElement(
                    indatafile.getNextTracker(nodelist, elementlist)
                );
            }

            indatafile.close();
            System.out.println("Filled trackerlist");

            //Get the controlset
            indatafile.open();
            System.out.println("Reading Controls");

            for (i = 0; i < number_of_controls; i++) {
                indatafile.getControlSet(controlset);
            }

            indatafile.close();
            System.out.println("Filled controlset");

            // Create an outdata file that will print the results in the format we wish
            resultwriter = indatafile.getWriter(
                    nodelist, elementlist, controlset, nodes
                );

            // Create a trackwriter that will print all trackresults in right format
            trackwriter = indatafile.getTrackWriter(trackerlist, controlset, nodes);
        } catch (java.text.ParseException e) {
            // If we end up here, something is wrong in the indata file, reading the parameters
            throw new Error(
                "Parameter error in indata file \n" + e + " in line " +
                e.getErrorOffset()
            );
        } catch (Error e) {
            throw e;
        }

        //Initialize the writer
        try {
            resultwriter.initialize();
        } catch (Error e) {
            throw new Error("Initialization error of writer");
        }

        //Initialize the trackwriter
        try {
            trackwriter.initialize();
        } catch (Error e) {
            throw new Error("Initialization error of trackwriter");
        }
    }

    /**
     * Insert the method's description here. Creation date: (2001-08-20
     * 22:03:57)
     */
    public void post() {
    }

    /**
     * This method prints the requested state of the solution to a file The
     * file will be called the same name as the indatafile, but with an ending
     * of .res Creation date: (2001-10-17 01.51.01)
     */
    private void print() {
        System.out.println();
        System.out.println();
        System.out.println("time:" + time);
        try {
        resultwriter.write(filename, time);
        trackwriter.write(time);
        } catch (IOException ioe) {
            System.out.println(ioe);
            return;
        }

    }

    /**
     * Insert the method's description here. Creation date: (2001-08-20
     * 22:03:07)
     */
    public void setInitialConditions() {
        int i;
        int j;
        Node temp_node;
        Node neighbour_node;
        Element temp_element;
        Tracker temp_tracker;
        Constraint temp_constraint;
        double total_mass;

        // Initialize all the nodes
        System.out.println("Initializing nodes");

        for (i = 0; i < nodelist.size(); i++) {
            temp_node = (Node) nodelist.elementAt(i);
            temp_node.setInitialConditions();
        }

        /*
           Set up the neighbour pointers needed for contact algorithm
           Give each node a handle to it's neighbour
         */
        System.out.println("Setting up node neighbour handles");

        for (j = 0; j < nodelist.size(); j++) {
            temp_node = (Node) nodelist.elementAt(j);

            if (j < (nodelist.size() - 1)) {
                temp_node.setRight_neighbour((Node) nodelist.elementAt(j + 1));
            }

            if (j > 0) {
                temp_node.setLeft_neighbour((Node) nodelist.elementAt(j - 1));
            }
        }

        /*
           Use the node neighbour routine to sort the nodes in ascending x-coordinate order.
         */
        System.out.println("Sorting nodes");

        for (j = 0; j < nodelist.size(); j++) {
            for (i = 0; i < nodelist.size(); i++) {
                temp_node = (Node) nodelist.elementAt(i);
                temp_node.checkNeighbours();
            }
        }
       	
        // Initialize all the elements
        System.out.println("Initializing elements");

        for (i = 0; i < number_of_elements; i++) {
            temp_element = (Element) elementlist.elementAt(i);
            temp_element.setInitialConditions();
        }

        // Initialize all the trackers
        System.out.println("Initializing trackers");

        for (i = 0; i < number_of_trackers; i++) {
            temp_tracker = (Tracker) trackerlist.elementAt(i);
            temp_tracker.setInitialConditions();
        }

        // Initialize all the constraints
        System.out.println("Initializing constraints");

        for (i = 0; i < number_of_constraints; i++) {
            temp_constraint = (Constraint) constraintlist.elementAt(i);
            temp_constraint.setInitialConditions();
        }

        // Initialize the controlset
        controlset.setInitialConditions();

        // Now, if autostep is used, loop through all elements and determine the smallest timestep
        System.out.println("Determining smallest timestep size");
        
        if (controlset.getTimestep(0) == 0) {
            autostep = true;
            timestep = 1E10;
            for (i = 0; i < number_of_elements; i++) {
                timestep = ((Element) elementlist.elementAt(i)).checkTimestep(
                        timestep
                    );
            }
        } else {
            autostep = false;
            timestep = controlset.getTimestep(0);
        }

        System.out.println("Determined timestep:" + timestep);
        // Sum up total model mass and print
        System.out.println("Calculating total model mass");
        total_mass = 0;

        for (i = 0; i < nodelist.size(); i++) {
            temp_node = (Node) nodelist.elementAt(i);
            total_mass += temp_node.getMass();
        }

        System.out.println("Total model mass = " + total_mass);
        
    }

    /**
	 * This is the main loop of the program. Here, the solution is conducted.
	 * Creation date: (2001-08-20 22:03:47)
	 */
	public void solve(Barrier barrier) throws Exception {
		int j;
		long time_info;
		long time_info_tmp;
		long time_remained;
		int number_of_integration_points;
		int time_h;
		int time_m;
		int time_s;
		String time_str;
		long stime;

		time_info = new Date().getTime();
		ttemp = 1E10;

		// This is the main loop which will run in tandem with the other
		// threads;
		for (time = controlset.getStarttime(); time < controlset.getEndtime(); time += timestep) {

			barrier.sync();

// 	Loop elements
			for (i = 0; i < elementindicies.length; i++) {

				temporary_element = (Element) elementlist.elementAt(elementindicies[i]);

				// Determine the element local base vectors (local coordinate
				// system)
				temporary_element.updateLocalCoordinateSystem();

				// To reduce amount of memory in each element, loop these steps
				// for each integration point
				number_of_integration_points = temporary_element
						.getNumberOfIntegrationPoints();

				for (j = 0; j < number_of_integration_points; j++) {
					// Calculate element strain (strain velocity) matrix
					temporary_element.calculateStrain(timestep, j);

					// Calculate element stress (stress velocity) matrix
					temporary_element.calculateStress(j, timestep);
				}

				/*
				 * The strains and stresses are now calculated for all
				 * integration points. Continue with the forces. By knowing all
				 * the strains in advance, the thickness reduction of shells can
				 * be accurately determined
				 */

				for (j = 0; j < number_of_integration_points; j++) {
					//	Calculate internal forces
					temporary_element.calculateNodalForces(j);
				}

				// Calculate external forces (gravity etc)
				temporary_element.calculateExternalForces(time);

				// Calculate contact forces
				temporary_element.calculateContactForces();

				// Update timestep if needed
				if (autostep == true) {
					ttemp = temporary_element.checkTimestep(ttemp);
				}

				// End loop
			}

			exported_ttemp = ttemp;

			barrier.sync();

/*
// Remove failed elements
			if (failure_is_set) {
				for (i = 0; i < number_of_elements; i++) {
					temporary_element = (Element) elementlist.elementAt(i);

					if (temporary_element.hasFailed()) {
						number_of_elements--;
						elementlist.removeElementAt(i);
						System.out.println("Failed element: "
								+ temporary_element.getNumber());
						i--;

						Node internal_node = temporary_element
								.getInternalNode();
						if (internal_node != null) {
							nodelist.remove(internal_node);
						}

					}
				}
			}
*/

// Loop constraints
			for (i = 0; i < number_of_constraints; i++) {
				temporary_constraint = (Constraint) constraintlist.elementAt(i);
				temporary_constraint.update();
			}

			nodelist.collectiveUpdate();
			
			if (client_nr == 0) {
				
// Loop Nodes (not distributed due to contact algorithm)
				for (i = 0; i < nodelist.size(); i++) {
					// Get a node from the array
					temporary_node = (Node) nodelist.elementAt(i);
					
					// Update acceleration, velocity and position of node (supply
					// timestep because it is needed in the calculations)
					// Note, the update includes application of boundary conditions.
					// The update also includes addition of any external forces from
					// boundary conditions.
					temporary_node.calculateNewPosition(timestep, time);
					
					// Check for neighbours (needed for contact algorithm)
					temporary_node.checkNeighbours();
					// End loop
				}
				
// Loop Trackers
				for (i = 0; i < number_of_trackers; i++) {
					// Get a tracker from the array
					temporary_tracker = (Tracker) trackerlist.elementAt(i);
					
					// Collect the data
					temporary_tracker.collectData();
					
					// Perform needed calculations
					temporary_tracker.calculate();
				}
			}
			
// Update timestep
			if (controlset.getTimestep(time) == 0) {
				autostep = true;
				for (i = 0; i < nr_of_CPUs; i++) {
					if (i != client_nr)
						ttemp = Math.min(ttemp, cluster_nodes[i].getTtemp());
				}
				timestep = ttemp;
				ttemp = 1E10;
			} else {
				autostep = false;
				timestep = controlset.getTimestep(time);
			}
			
			
// Check if it is time to print something
			if (controlset.timeToPrint(time)) {
				
				elementlist.collectiveUpdate();
				
				if (client_nr == 0) {
					
					System.out.println();
					System.out.println();
					time_info_tmp = new Date().getTime();
					time_remained = (((time_info_tmp - time_info) * ((int) ((controlset
							.getEndtime() - time) / controlset.getPrintstep()))) / 1000);
					time_h = (int) (time_remained / 3600);
					time_m = (int) ((time_remained / 60) - (time_h * 60));
					time_s = (int) (time_remained - (((int) (time_remained / 60)) * 60));
					time_str = "";
					
					if (time_h < 10) {
						time_str += ("0" + time_h);
					} else {
						time_str += time_h;
					}
					
					if (time_m < 10) {
						time_str += (":0" + time_m);
					} else {
						time_str += (":" + time_m);
					}
					
					if (time_s < 10) {
						time_str += (":0" + time_s);
					} else {
						time_str += (":" + time_s);
					}
					
					System.out.println("time:" + time
							+ "\tRemaining time (hh:mm:ss) " + time_str);
					time_info = time_info_tmp;
					try {
						resultwriter.write(filename, time);
					} catch (IOException ioe) {
						System.out.println(ioe);
						return;
					}
				}	
			}
			
// Check if it is time to print something on the trackers
			if (controlset.timeToPrintTracker(time)) {

				// No need to sync if it is already done
				if (!controlset.timeToPrint(time)) elementlist.collectiveUpdate();
				
				if(client_nr == 0) {
					trackwriter.write(time);
				}
			}
			
			
			barrier.sync();
			
// Clear nodal forces
			for (i = 0; i < nodeindicies.length; i++) {
				
				temporary_node = (Node) nodelist.elementAt(nodeindicies[i]);
				
				temporary_node.clearNodalForces();
				
			}
			
			nodelist.collectiveUpdate();
			
		}

		// end this solution
		this.post();
	}

	/**
	 * This method passes the references of the replicated lists to be shared
	 * with the other processes. It is only used for the first node.
	 * 
	 * @param nodes
	 */
	public void passReferences() {
		
        // Now, distribute to the other processes
		for (int i=1; i<cluster_nodes.length; i++) {

			cluster_nodes[i].setReferences(constraintlist,
					nodelist, loadlist, elementlist,
					materiallist, trackerlist, controlset,
					resultwriter, trackwriter, cluster_nodes);
			
			cluster_nodes[i].setVariables(number_of_constraints,
					number_of_nodes, number_of_loads, 
					number_of_elements, number_of_materials,
					number_of_trackers, number_of_controls,
					timestep, autostep);
		}
		

		// Start by updating the shared objects
		try {
	    constraintlist.exclusiveUpdate();
	    loadlist.exclusiveUpdate();
	    nodelist.exclusiveUpdate();
		elementlist.exclusiveUpdate();
		materiallist.exclusiveUpdate();
		trackerlist.exclusiveUpdate();
		controlset.exclusiveUpdate();
		resultwriter.exclusiveUpdate();
		trackwriter.exclusiveUpdate();
		
		} catch (java.io.IOException ioe) {
            System.out.println(ioe);
        } catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
	/**
	 * @param elementlist
	 *            The elementlist to set.
	 */
	public void setReferences(RplVector cl, RplVector nl, RplVector ll, RplVector el, RplVector ml, RplVector tl, Controlset cs, Writer rw, TrackWriter tw, SmackCluster[] nod) {
		this.constraintlist = cl;
		this.nodelist = nl;
		this.loadlist = ll;
		this.elementlist = el;
		this.materiallist = ml;
		this.trackerlist = tl;
		this.controlset = cs;
		this.resultwriter = rw;
		this.trackwriter = tw;
		this.cluster_nodes = nod;
	}

	/**
	 * @param 
	 *            The elementlist to set.
	 */
	public void setVariables(int noc, int non, int nol, int noe, int nom, int not, int noctrl, double timestep, boolean autostep) {
		this.number_of_constraints = noc;
		this.number_of_nodes = non;
		this.number_of_loads = nol;
		this.number_of_elements = noe;
		this.number_of_materials = nom;
		this.number_of_trackers = not;
		this.number_of_controls = noctrl;
		this.timestep = timestep;
		this.autostep = autostep;
	}
	
	/**
	 * @return Returns the ttemp.
	 */
	public double getTtemp() {
		return exported_ttemp;
	}
	
	/**
	 * This method calculates which objects are to be 
	 * calculated in this client process. Note that this 
	 * is calculated in parallel on all clients and should not
	 * give overlapping results is maximum efficiency is to be
	 * gained
	 */
	public void determineDistribution() {
		Vector node = new Vector();
		Vector element = new Vector();
		Node tempnode;
		Element tempelement;
		int index;

		index = 0;
		
		// First get leftmost node
       	tempnode = (Node) nodelist.firstElement();
        
       	while (tempnode.getLeft_neighbour() != null)
       		tempnode = tempnode.getLeft_neighbour();

       	// Now, assign in increasing x-coordinate to CPU
       	for (i = 0; i < nodelist.size(); i++) {
            tempnode.setCpu_number(i*nr_of_CPUs/nodelist.size());
       		tempnode = tempnode.getRight_neighbour();
            if(i*nr_of_CPUs/nodelist.size() == client_nr) index++;
       	}

		nodeindicies = new int[index];
		index = 0;
		for (int i=0; i<nodelist.size(); i++) {
			tempnode = (Node)nodelist.elementAt(i);
			if (tempnode.getCpu_number() == client_nr) nodeindicies[index++] = i;
		}


		index = 0;
		for (int i=0; i<elementlist.size(); i++) {
			tempelement = (Element)elementlist.elementAt(i);
			if (tempelement.getCpu_number() == client_nr) index++;
		}
		
		elementindicies = new int[index];
		index = 0;
		for (int i=0; i<elementlist.size(); i++) {
			tempelement = (Element)elementlist.elementAt(i);
			if (tempelement.getCpu_number() == client_nr) elementindicies[index++] = i;
		}

	}
	
	
}

