#!/usr/bin/python

# A model that knows how to run a script when you call self.analyze. The script
# should
#	- somehow pick or generate gro files
#	- write the file list to a file called GROFILELIST to the 'path' attribute
# This object can then read GROFILELIST and pass it back to, eg, the FidoProject
# parent. 

from os import system

class RunScript :
	def __init__( self, scriptName, resultFileName = "GROFILELIST", debug = False ) : #  , data, nruns, nclones ):
		self.scriptName = scriptName
		self.resultFileName = resultFileName
		self.debug = debug

		# this gets set by the FidoProject parent
		self.path = ""

		## test to see if script exists? 

	def build( self ):
		if self.debug :
                        print "Model analysis: running '%s'" % self.scriptName

                self.newGroFiles = self.run()

	def update( self ):
		# same as build
		self.build()

	def analyze( self ):
		return self.newGroFiles 

	def run( self ):
		# run the script 'self.script'
		# path is first argument
		# GROFILELIST (where to write file names) is second argument
		cmd = "%s %s %s" % ( self.scriptName, self.path, self.resultFileName )
		
		if self.debug :
			print "Running '%s'" % cmd

		n = system( cmd )
		if n > 0 : 
			print "script failed ..."

		# now read the results
		FILE = open( "%s/%s" % ( self.path, self.resultFileName ) )
		results = FILE.readlines()
		FILE.close()

		# get rid of newlines, etc
		nres = []
		for file in results :
			nres.append( file.strip() )

		# pass back a list of gros!
		return nres 
