#!/usr/bin/env python
import os,re,subprocess
import sys, shutil, stat
Exe= "Exe"
b = []
#c1 = "cp vector.par ../../modelcase/"
#c2 = "cp flow.par ../../modelcase/"
#cmds = [c1,c2] 
#extract list of blocking factors from param.lst
#open('param.lst')
#for line in open('param.lst'):
#	print line.split()
#        b= line.split[2].split[',']
#        print b
param_file = open("param.lst", "r")
param_list = param_file.read()
param_file.close()

Blocking_factor = re.findall(r"Blk_factor.*$", param_list,re.MULTILINE)
for x in Blocking_factor:
	blocking_temp = re.split(r"=", x)
	b = re.split(r"\s", blocking_temp[1])
	print b

#for line in open('param.lst').readlines():
#     if re.match(r'^Blk_factor', line):
#       m = re.search("(\d) (\d{1,2}) (\d{1,4})", line)
#       b= m.group(1,2,3)
#       print 'Blocking_Factors: ', b


#path = os.stat()
#print path
if not os.path.isdir(Exe):
    print "Error: Cannot find Exe folder"
    sys.exit(-1)

#print current directory
#pathname = os.getcwd()
#print 'Current Dirctory =',pathname


#make directory for input files#
if not os.path.exists("modelcase"):
	os.mkdir("modelcase")

for blocking in b:
	print os.path.abspath(".")
	if not os.path.exists("data/" + blocking):
		os.mkdir("data/" + blocking)
        
	parfiles = os.listdir("modelcase/")
        for file in parfiles:
 		shutil.copy("modelcase/" + file, "data/" + blocking)

	preproc = open("data/" + blocking + "/preproc.par","w")
	preproc.write("&PREPINP\n")
	preproc.write(" LX    = 200                   ,\n")
	preproc.write(" LY    = 50                     ,\n") 
	preproc.write(" LZ    = 50                    ,\n") 
	preproc.write(" P_XY  = T                     ,\n")
	preproc.write(" P_XZ  = T                     ,\n")
	preproc.write(" P_YZ  = T                     ,\n")
	preproc.write(" X_OFF = 0                     ,\n")
	preproc.write(" Y_OFF = 0                     ,\n")
	preproc.write(" Z_OFF = 0                     ,\n")
	preproc.write(" CASENME = \"#sample#cylindr#\" ,\n")
	preproc.write(" IS_FLUID = F                  ,\n")
	preproc.write(" COMPRESS_PRP = F              ,\n")
	preproc.write(" BLOCKINGFACTOR = " + blocking + "  ,\n")
	preproc.write("/")
	preproc.close()




	os.chdir("data/" + blocking)
 
#        count=0
#        for cmd in cmds:
#              	count+=1
#		subprocess.call(cmd,shell=True)
	subprocess.call("./../../preproc.x86_64-em64t-mpi", shell=True )
	os.chdir("../..")


	pathname = os.getcwd()
        print 'Current Dirctory =',pathname



