#!/usr/bin/env python
#********************************************************************************
#
#       Code by Olivier Mattelaer (olivier.mattelaer@uclouvain.be)
#       last modification 26/02/2010
#       License GNU
#********************************************************************************
#
#  In order to use this script you shoud define a valid MadWeight Card
#
#  On this one the relevant blok are:
#  Block MW_parameter (defining the set of MW_card)
#  Block EventSelection (defining event selection: detail at http://cp3wks05.fynu.ucl.ac.be/twiki/bin/view/Software/MadWeightAdvancedOpttion#Block_EventSelection)
#
#  All the other standard input of the MW card are irrelevant.
#  In the blok MW_run you need to add the line 
#  requested XXXX
#  this will indicated the number of LHCO events you need after cuts.
#
#******************************************************************************






#Extension
import string
import sys
import os
import re
import time
import stat
# patch if symbolic directory replace by real file
sys.path.append('./Source/MadWeight_File/Python')
sys.path.append('../Source/MadWeight_File/Python')
#end patch
import write_MadWeight,create_run,put_banner
import create_param
import Cards
from Cards import Card
import cluster_lib as Cluster
from create_run import update_cuts_status
from MW_param import MW_info,go_to_main_dir,check_for_help
from collect_result import Collect_dir,Collect_P_dir,Collect_MW_dir,Collect_All_dir,collect_schedular
import verif_event


class Lhco_filter(verif_event.Lhco_filter):
    
    #2 ###############################################################################################################
    def __init__(self, input_file,MWparam,auto=1):
        """ input is either a file containing particule number info or a SubProcesses directory """

        start=time.time()

        self.MWparam=MWparam
        #treat directory info
        self.directory='./SubProcesses/'+MWparam.P_listdir[0]
                
        self.lhco_file=input_file
        self.partdef=self.find_particle_number()        # find number of particle of each type
            
        #define internal variable
        self.write_mode = 1
        self.write_events=0
        print 'time  init Lhco_filter',time.time()-start
        #if input_file and auto:
        #    self.verif_event(input_file,self.partdef)

    def launch_verif(self,input_file=''):
        if input_file=='':
            input_file = self.lhco_file
        nb_event=self.verif_event(input_file,self.partdef)
        return nb_event
    
    def add_in_file(self,output_file):
        
	try:
		self.f_out.close()
	except:
		pass
        ff=open(output_file,'a')
        ff.writelines(open(self.directory+'/'+self.MWparam.name+'/verif.lhco','r').read())
        ff.close()
             
                    

def check_event(input_file,output_file,MWparam):

    select = Lhco_filter(input_file,MWparam)
    nb_select = select.launch_verif(input_file)
    print 'nb_select',nb_select,type(nb_select)
    select.add_in_file(output_file)

    return nb_select
                                                                
#####################################################################################"
##
##               LAUNCH PROGRAM
##
######################################################################################
if(__name__=='__main__'):

    go_to_main_dir()
    check_for_help(sys.argv)
    MWparam=MW_info('MadWeight_card.dat')
    MWparam.set_run_opt(sys.argv)
    create_param.Param_card(run_name=MWparam)
    MWparam.update_nb_card()

    os.system('rm Events/card_*')
    os.system('rm Events/valid_*')
    for i in range(1,MWparam.nb_card+1):
        pass_event=0
        os.system('cp Cards/param_card_%s.dat Cards/param_card.dat' % i)
        for j in range(0,100):
            os.system('./bin/generate_events 1 card_%s_run_%s  card_%s_run_%s' %(i,j,i,j))
            os.system('gunzip Events/card_%s_run_%s_pgs_events.lhco.gz' %(i,j))
            pass_event+=check_event('Events/card_%s_run_%s_pgs_events.lhco' %(i,j),'Events/valid_events_card_%s.lhco' % (i),MWparam)
            os.system('rm Events/card_%s_run_%s_*' %(i,j))
            print pass_event,MWparam['mw_run']['requested']
            if pass_event>int(MWparam['mw_run']['requested']):
                break
            
            
#            signal_2Hdm_1_pgs_uncleaned_events.lhco.gz

        
#    verif_event(MWparam)
