#!/home/fz/div/Python-2.2.2/python

import sys, os, string, commands,xreadlines


gpaccname="TESLA" # or NLC-B-500
dpath="/home/fz/gp/run/"
hpath="/home/fz/"
gpaccstring="standard" #just part of the filename: acc.gpaccstring.dat
gpaccparam="fast1" #or standard

#below can have a for loop and append for many steps--otherwise do manual arrays

dnamelist= ['tesla-test-stdparams']
loopenergy=['250']
loopxoffset=['0']
loopyoffset=['0']

#make a lopp over an array

for i in range( len(dnamelist) ):

    ######
    #do the accelerator config and run gp and GPAnal
    
    os.mkdir(dpath+dnamelist[i])
    os.chdir(dpath+dnamelist[i])

    stdacc=open(dpath+"acc."+gpaccstring+".dat" , 'r')    

    newacc=open(dpath+"acc"+dnamelist[i]+".dat",'w')

    #not very elegant loop, but does the job to replace tags
    #can be done better with a dictionary http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52250
    for s in xreadlines.xreadlines(stdacc):
        s=s.replace( "<ENERGY>", loopenergy[i])
        s=s.replace( "<XOFFSET>", loopxoffset[i])
        s=s.replace( "<YOFFSET>", loopyoffset[i])
        newacc.write(s)
                
    stdacc.close()
    newacc.close()    
    print 'wrote accelerator file \n'
    
##     #make a symlink to the active sub-directory
##     commands.getstatusoutput("ln -s "+dpath+"acc"+dnamelist[i]+".dat main.dat")

##     #run gp
##     print 'running '+dpath+"guinea "+gpaccname+' '+gpaccparam+' main.dat '
##     commands.getstatusoutput(dpath+"guinea "+gpaccname+" "+gpaccparam+" main.dat")

##     print 'ran gp OK, \n'

##     #run GPAnal
##     print 'now running '+hpath+"gpanal/src/GPAnal_fz "+dpath+dnamelist[i]
    
##     commands.getoutput(hpath+"gpanal/src/GPAnal_fz "+dpath+dnamelist[i])
##     print 'ran gpanal OK'
##     commands.getoutput("mv *.root ../../gpanal/run/")
##     print 'moved files OK'
    
    ######
    
#done!