"""The WaveBlocks Project

This file contains code some simple code to call a given
python script for a bunch of simulation result files.

@author: R. Bourquin
@copyright: Copyright (C) 2010, 2011, 2012, 2013 R. Bourquin
@license: Modified BSD License
"""

import argparse
from glob import glob
import subprocess as sp
import time

from WaveBlocksND.FileTools import get_result_dirs, get_results_file
from WaveBlocksND import GlobalDefaults


# Move files with these extensions back to the simulationpath
# NOTE: It is the responsability of the code in the
#       'scriptcode' script to produce filenames that
#       do not yield collisions. Otherwise the files
#       will beoverwritten without any warning!

save_extensions = [ GlobalDefaults.ext_resultdatafile ]

try:
    from GraphicsDefaults import output_format
    save_extensions.append(output_format)
except:
    save_extensions.append(".png")


def execute_for_all(resultspath, scriptcode, scriptargs):
    """Call a given python script with the simulation results data file as first
    command line argument. The script and the data file are specified by (relative)
    file system paths.

    :param resultspath: The path where to look for simulation data.
    :param scriptcode: The python script that gets called for all simulations.
    :param scriptargs: Optional (constant) arguments to the script.
    """
    # UNBUFFERED timelog file
    with open("logtime_forall", "w", 0) as timelog:

        for simulationpath in get_result_dirs(resultspath):
            starttime = time.time()
            timelog.writelines(["New script starting at: " + time.ctime(starttime) + "\n",
                                "Executing code for datafile in " + simulationpath + "\n"])
            print(" Executing code for datafile in " + simulationpath)

            # The file with the simulation data
            afile = get_results_file(simulationpath)

            # Call the given script
            sp.call(["python", scriptcode, afile] + scriptargs)

            endtime = time.time()
            timelog.writelines(["Script now finished at timestamp: " + time.ctime(endtime) + "\n",
                                "Script took " + str(endtime-starttime) + " second to run\n\n"])

            # Move newly created files back to the simulation path.
            # NOTE: It is the responsability of the code in the
            #       'scriptcode' script to produce filenames that
            #       do not yield collisions. Otherwise the files
            #       will beoverwritten without any warning!
            for ext in save_extensions:
                for afile in glob("*"+ext):
                    sp.call(["mv", afile, simulationpath])




if __name__ == "__main__":

    parser = argparse.ArgumentParser()

    parser.add_argument("scriptcode",
                        type = str,
                        help = "The script file to execute.")

    parser.add_argument("-r", "--results",
                        type = str,
                        help = "The script file to execute.",
                        default = GlobalDefaults.path_to_results)

    parser.add_argument("scriptargs",
                        nargs=argparse.REMAINDER)

    args = parser.parse_args()

    print("Will execute the code from '" + str(args.scriptcode) + "' for all files in '" + str(args.results) + "'")
    print("with optional arguments " + str(args.scriptargs))

    execute_for_all(args.results, args.scriptcode, args.scriptargs)

    print("Done")

@@ -201,16 +201,22 @@
 12, 2013
+, 2014
  R. Bour
@@ -321,20 +321,8 @@
 s sp
-%0Aimport time
 %0A%0Afr
@@ -658,32 +658,33 @@
 %0A#       will be
+ 
 overwritten with
@@ -1371,95 +1371,8 @@
 %22%22%22%0A
-    # UNBUFFERED timelog file%0A    with open(%22logtime_forall%22, %22w%22, 0) as timelog:%0A%0A    
     
@@ -1435,295 +1435,68 @@
     
-  
-  starttime = time.time()%0A            timelog.writelines(%5B%22New script starting at: %22 + time.ctime(starttime) + %22%5Cn%22,%0A                                %22Executing code for datafile in %22 + simulationpath + %22%5Cn%22%5D)%0A            print(%22 Executing code for datafile in %22 + simulationpath)%0A%0A    
+print(%22 Executing code for datafile in %22 + simulationpath)%0A%0A
     
@@ -1509,16 +1509,19 @@
 The file
+(s)
  with th
@@ -1550,17 +1550,16 @@
     
-   
- a
+res
 file
+s
  = g
@@ -1603,329 +1603,351 @@
     
-    # Call the given script%0A            sp.call(%5B%22python%22, scriptcode, afile%5D + scriptargs)%0A%0A            endtime = time.time()%0A            timelog.writelines(%5B%22Script now finished at timestamp: %22 + time.ctime(endtime) + %22%5Cn%22,%0A                                %22Script took %22 + str(endtime-starttime) + %22 second to run%5Cn%5Cn%22%5D
+# Handle case where multiple hdf5 files are found%0A        if type(resfiles) is list:%0A            print(%22  Warning: more than one results file found!%22)%0A        else:%0A            resfiles = %5Bresfiles%5D%0A%0A        # For each file call the given script%0A        for resfile in resfiles:%0A            sp.call(%5B%22python%22, scriptcode, resfile%5D + scriptargs
 )%0A%0A 
@@ -2235,16 +2235,17 @@
  will be
+ 
 overwrit
@@ -2736,33 +2736,33 @@
  = %22
-The script file to execut
+Path where the results ar
 e.%22,
@@ -2850,24 +2850,32 @@
 d_argument(%22
+-a%22, %22--
 scriptargs%22,
@@ -2871,24 +2871,139 @@
 criptargs%22,%0A
+                        help = %22Additional arguments passed to the script.%22,%0A                        default = %5B%5D,%0A
             

Fix the ForAll script