package RSTT;

import gov.sandia.gnem.slbmjni.GridProfile;
import gov.sandia.gnem.slbmjni.SlbmInterface;
import gov.sandia.gnem.slbmjni.SLBMException;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
Copyright (c) 2012, Lawrence Livermore National Security, LLC.
Produced at the Lawrence Livermore National Laboratory
Written by Stephen Myers (myers30@llnl.gov).
LLNL-CODE-607696
All rights reserved.
This file is part of RSTT_NOGS.
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
• Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below.
• Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution.
• Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Additional
 */
public class SetNodes {
    BufferedReader in;
    SlbmInterface slbm;
    
    public SetNodes() {
            System.loadLibrary("slbmjni");
            slbm = new SlbmInterface();
    }
    
    public void makeActive (double latmin, double lonmin, double latmax, double lonmax) {
        slbm.initializeActiveNodes(latmin, lonmin, latmax, lonmax);
    }
    
     public void loadModel (String modelPath) {
        slbm.loadVelocityModelBinary(modelPath);
    }

     /*
      * Loads a velocity profile into a GridProfile object
      * The input file must be pointed at the first line of a node entry
      */
    public static GridProfile loadGridProfile(BufferedReader in) throws IOException {
	GridProfile profile = new GridProfile();
	profile.depth = new double[9];
	profile.velocity = new double[2][9];
	profile.gradient = new double[2];
	   String line = in.readLine();
	   StringTokenizer t = new StringTokenizer(line);
	   int Ntokens = t.countTokens();
	   String shouldBeNode = t.nextToken();
	   if (!shouldBeNode.equals("node")) {
		   System.err.println("Warning in SetNodes.loadGridProfile: First line should start with 'node', found "+line);
		   return(profile);
	   }
	   profile.nodeId = Integer.parseInt(t.nextToken());
	   if (Ntokens == 5) { int activeNodeId = Integer.parseInt(t.nextToken());}
	   profile.lat = Double.parseDouble(t.nextToken());
	   profile.lon = Double.parseDouble(t.nextToken());
	   for (int i=0;i<9;i++) {
		   line = in.readLine();
		   t = new StringTokenizer(line);
		   t.nextToken();  //dispense with layer number
		   profile.depth[i] = Double.parseDouble(t.nextToken());
		   profile.velocity[0][i] = Double.parseDouble(t.nextToken());
		   profile.velocity[1][i] = Double.parseDouble(t.nextToken());
		   if (i==8) {
		      profile.gradient[0] = Double.parseDouble(t.nextToken());
		      profile.gradient[1] = Double.parseDouble(t.nextToken());
		   }
	   }
	   
	   
	   return(profile); 
    }

    public static GridProfile[] loadGridProfiles(String fileName) {
	    ArrayList<GridProfile> gridprofilesA = new ArrayList();
	    GridProfile[] gridprofiles = null;
		try {
			BufferedReader in = IOUtilities.FileIO.openFile(fileName);
			in.mark(10000);
			String line;
			while ((line = in.readLine()) != null) {
				in.reset();
				GridProfile profile = loadGridProfile(in);
				gridprofilesA.add(profile);
			        in.mark(10000);
			}
			gridprofiles = new GridProfile[gridprofilesA.size()];
			for (int i=0;i<gridprofiles.length;i++) {
				gridprofiles[i] = gridprofilesA.get(i);
			}


		} catch (Exception ex) {
			Logger.getLogger(SetNodes.class.getName()).log(Level.SEVERE, null, ex);
		}
	     return(gridprofiles);
    }

    public void putProfilesInModel(GridProfile[] profiles) throws SLBMException {
	    for (int i=0;i<profiles.length;i++) {
		    slbm.setGridData(profiles[i]);
	    }
    }

    public void saveModel(String outDir) {
	    slbm.specifyOutputDirectory(outDir);
	    slbm.saveVelocityModelBinary();
    }


    public static void main (String args[]) {
	    if (args.length != 2 && args.length != 3) {
		     System.err.println("Usage: SetNodes <input model path> <node update file> <output model path>");
		     System.err.println("         <input model path> is the full path to the file containing the input model.");
		     System.err.println("         <output model path> is the full path to the file containing the output model. The output model file is created if it doesn't exist.");
		     System.err.println("         <node update file> (Use GetNodes for an example) is an ascii file containing the node update information. Multiple nodes can be updated.");
		     System.err.println("            The first line of a node entry is 'node nodeID activeNodeID lat lon'. nodeID must be taken from the input model. activeNodeID is optional and is not currently used.");
		     System.err.println("            9 lines specifying layer depths and velocites follow each node line.");
		     System.err.println("            Lines 1-8 have entries 'layer# depth (km) Vp (km/s) Vs (km/s)' layer# starts with 0.");
		     System.err.println("            Line 9 is similar to lines 1-8 with  additional entries that specify mantle velocity gradient for Vp and Vs. Units for gradient are km/s/km or 1/s.");
		     System.exit(0);

	     }
	    SetNodes model = new SetNodes();
	    String profileFileName = null;
	    String outModelDir = null;
	    if (args.length == 2) {
   	       model.loadModel("/Users/Myers30/Documents/Location/SLBMWorkingGroup/Codes/SLBM_Root_2.8.2/models/na1010pn");
	       profileFileName = args[0];
	       outModelDir = args[1];

	    } else {
   	       model.loadModel(args[0]);
	       profileFileName = args[1];
	       outModelDir = args[2];
	    }
	    GridProfile[] profiles = loadGridProfiles(profileFileName);
		try {
			model.putProfilesInModel(profiles);
			model.saveModel(outModelDir);
		} catch (SLBMException ex) {
			Logger.getLogger(SetNodes.class.getName()).log(Level.SEVERE, null, ex);
		}
    }

    
	
}

