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

import sys, os, string, commands, xreadlines , getopt




#make a lopp over an array
def main():

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

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

    dnamelist= ['nlcb-500-y6','nlcb-500-y8','nlcb-500-y10']
    loopenergy=['245','245','245']
    loopxoffset=['0','0','0']
    loopyoffset=['6','8','10']

    analonly = 0

    
    try:
        opts , args = getopt.getopt(sys.argv[1:], "n", "nogp")
    except getopt.GetoptError:         
        print "\n usage: rungp.py [-n or --nogp for analysis only] \n"                    
        sys.exit(2)    
    for opt , arg in opts:
        if opt in ("-n", "--nogp"):
            analonly = 1
            print "argument given: n \n"

    #print sys.argv[1]
    
    for i in range( len(dnamelist) ):

        if  analonly != 1 :
            
            #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 acc.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

        os.chdir(dpath+dnamelist[i]) #do that again, if running without gp

        print 'now running '+hpath+"gpanal/src/GPAnal_fz "+dpath+dnamelist[i]+" "+loopenergy[i]

        commands.getstatusoutput(hpath+"gpanal/src/GPAnal_fz "+dpath+dnamelist[i]+" "+loopenergy[i])
        print 'ran gpanal OK'
        commands.getstatusoutput("mv *.root "+hpath+"gpanal/run/")
        print "ran mv *.root "+hpath+"gpanal/run/ \n"

        ######

#done!

#just truncate the arguments as python echoes the name of the script as argv[0]
if __name__ == "__main__":
    main()