from glob import glob
import os
from os import rmdir, system, unlink
from os.path import abspath
import tempfile

class Tempdir :
	def __init__( self, name, location="/tmp" ):
		self.tempdir = tempfile.mkdtemp( "", name, location )
		
	def __del__( self ):
		# remove all data in the temp directory
		files = glob( "%s/*" % self.tempdir )
		for file in files :
			unlink( file )
		rmdir( self.tempdir )

	def __repr__( self ):
		files = glob( "%s/*" % self.tempdir )
		s = ".\t"
		for file in files : s += "%s\t" % file
		return s[ :-1 ]

	def __str__( self ):
		return self.tempdir

class Tester :
	def __init__( self, grmsbin="g_rms", echo="echo 0 1 0" ): 
		self.grmsbin = grmsbin

		if os.access(self.grmsbin, os.F_OK | os.X_OK):
			raise GmxNoBinary

		self.echo = echo
		self.tempdir = Tempdir( "wutest" )

	def test( self, xtc, tpr ) :
		outfile = "%s/rmsd.xvg" % self.tempdir
		command = "%s | %s -s %s -f %s -o %s" % ( self.echo, self.grmsbin, tpr, xtc, outfile )
		
		# we negate because system returns 0 for success
		failed = system( "%s >& /dev/null" % command ) 
		if failed :
			print command
			raise GmxFailure

		# ok, it worked; what was the result?
		try:
			file = open( outfile )
	
		
			lines = file.readlines()
			for line in lines :
				if line[0] not in "@#" :
					result = float( line.split()[1] )
					break	
		except IOError :
			raise CouldNotReadXvg 

		return result

class GmxNoBinary( Exception ): pass
class GmxFailure( Exception ): pass
class CouldNotReadXvg( Exception ): pass
