/*
 * Copyright (c) 2005, Stanford University. All rights reserved. 
 * 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 following disclaimer. 
 *  - Redistributions in binary form must reproduce the above copyright 
 *    notice, this list of conditions and the following disclaimer in the 
 *    documentation and/or other materials provided with the distribution. 
 *  - Neither the name of the Stanford University 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 THE 
 * COPYRIGHT OWNER 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. 
 */

/*
 * Created on Aug 23, 2005
 * Original author: Christopher Bruns
 */
package org.simtk.isimsu;

import java.io.*;

// TODO Run an exe file from a jar
public class TestExe {
    public TestExe() {}
    public static void main(String[] args) {
        TestExe testExe = new TestExe();
        testExe.runAPBS();
    }
    
    // TODO - wrap running of APBS program
    void runAPBS() {
        System.out.println("user.home = "+System.getProperty("user.home"));
        // TODO - find apbs executable automatically
        try {

            // Create a working directory
            String workingDirectoryName = "APBS_TEST";
            File tempDir = File.createTempFile(workingDirectoryName, "");
            System.out.println("Creating directory " + tempDir.getCanonicalPath());
            // Turn the normal file into a directory
            if (!tempDir.delete())
                throw new IOException();
            if (!tempDir.mkdir())
                throw new IOException();
            
            // TODO Put pqr file in working directory
            String pdbID = "1GRZ";
            InputStream pdbStream = PDB.getWebPDBStream(pdbID);
            File pdbFile = new File(tempDir, pdbID + ".pdb");
            BufferedWriter pdbWriter = new BufferedWriter(new FileWriter(pdbFile));
            BufferedReader pdbReader = new BufferedReader(new InputStreamReader(pdbStream));
            String pdbLine;
            while (null != (pdbLine = pdbReader.readLine())) {
                pdbWriter.write(pdbLine);
            }
            pdbWriter.close();
            pdbReader.close();

            // TODO convert to PQR format
            String pqrFileName = pdbID + ".pqr";
            String[] pqrConvertCommand = {
                    "C:\\ProgramFiles\\Python24\\python",
                    "pdb2pqr.py",
                    "--ff=charm",
                    pdbFile.getName(),
                    pqrFileName
            };            
            
            // Process apbsProcess = Runtime.getRuntime().exec(apbsArgs, null, tempDir);
            ExternalProcessManager pqrConvertProcess = new ExternalProcessManager(pqrConvertCommand, tempDir);
            pqrConvertProcess.start();

            // Wait for process to end
            pqrConvertProcess.join();

            // Create an APBS input file
            String apbsInputString = 
                    "read \n" +
                    "    mol pqr " + pqrFileName + "\n" +
                    "end\n" +
                    "\n" +
                    "elec name mol1\n" +
                    "    mg-auto\n" +
                    "    dime  97 97 97\n" +
                    "    cglen 80 80 80\n" +
                    "    fglen 70 70 70\n" +
                    "    cgcent mol 1\n" +
                    "    fgcent mol 1\n" +
                    "    mol 1\n" +
                    "    lpbe\n" +
                    "    bcfl sdh\n" +
                    "    ion  1 0.000 2.0   # Zero ionic strength for initial run\n" +
                    "    ion -1 0.000 2.0\n" +
                    "    pdie 2.0\n" +
                    "    sdie 78.00\n" +
                    "    srfm smol\n" +
                    "    chgm spl0\n" +
                    "    srad 1.4\n" +
                    "    swin 0.3\n" +
                    "    temp 298.15\n" +
                    "    gamma 0.105\n" +
                    "    calcenergy no\n" +
                    "    calcforce no\n" +
                    "    write pot dx apbs_macromolecule_potential\n" +
                    "end\n" +
                    "\n" +
                    "quit\n";
            
            String apbsInputFileName = "apbs.in";
            File apbsInputFile = new File(tempDir, apbsInputFileName);
            BufferedWriter apbsInputFileWriter = new BufferedWriter(new FileWriter(apbsInputFile));
            apbsInputFileWriter.write(apbsInputString);
            
            // Run the APBS command
            String apbsCommand = "C:\\cygwin\\usr\\local\\bin\\apbs";
            String apbsArg1 = apbsInputFileName;
            String[] apbsArgs = {apbsCommand, apbsArg1};
            
            // Process apbsProcess = Runtime.getRuntime().exec(apbsArgs, null, tempDir);
            ExternalProcessManager apbsProcess = new ExternalProcessManager(apbsArgs, tempDir);
            apbsProcess.start();

            // Wait for process to end
            apbsProcess.join();

            // Clean up
            tempDir.delete();
        }
        catch (IOException exc) { System.out.println("Exception: " + exc); }
        catch (InterruptedException exc) { System.out.println("Exception: " + exc); }
    }
}

