import os, sys, shutil
from subprocess import call

maxJob = 20;
outputName = ["pvfunction_result_step1.mat", "pvfunction_result_step2.mat"];

HelpMessage = """
    The first argument is the number of job to be created;
    The secound argument is the name of output file.
"""


if len(sys.argv) == 1:
    print(HelpMessage);

if len(sys.argv) == 2:
    maxJob = int(sys.argv[1]);



LoadString = """
load TGCT_MET_all.mat cMI MI


siz = size(cMI, 1);

"""
# #1
fs = open("combine_step1.m", 'w');
fs.write("MID = [];\n")
for i in range(1,maxJob+1):
   
    
    line = """
count = 1;
for i = floor(siz*({1}-1)/{0}+1):floor(siz*{1}/{0})
    pValue(count,:) = arrayfun(@pvalue_step1, MI(i, :), cMI(i, :));
    count = count + 1;
end
""".format(str(maxJob),str(i));
    saveString = """
save('mid{0}of{1}_step1.mat', 'pValue')
""".format(str(i),str(maxJob))
    with open("script{0}of{1}_step1.m".format(str(i), str(maxJob)), 'w') as f:
        f.write(LoadString)
        f.write(line)
        f.write(saveString)
        
    os.system("bsub -n 1 -o o{0}.txt -e e{0}.txt \"matlab < script{0}of{1}_step1.m\"".format(str(i),str(maxJob)));
    fs.write("load('mid{0}of{1}_step1.mat');\n".format(str(i),str(maxJob)))
    fs.write("MID = [MID; pValue];")

fs.write("pValue = MID;\n")
fs.write("save('{0}','pValue');\n".format(outputName[0]))

# #2

fs = open("combine_step2.m", 'w');
fs.write("MID = [];\n")
for i in range(1,maxJob+1):
   
    
    line = """
count = 1;
for i = floor(siz*({1}-1)/{0}+1):floor(siz*{1}/{0})
    pValue(count,:) = arrayfun(@pvalue_step1, MI(i, :), cMI(i, :));
    count = count + 1;
end
""".format(str(maxJob),str(i));
    saveString = """
save('mid{0}of{1}_step2.mat', 'pValue')
""".format(str(i),str(maxJob))
    with open("script{0}of{1}_step2.m".format(str(i), str(maxJob)), 'w') as f:
        f.write(LoadString)
        f.write(line)
        f.write(saveString)
        
    os.system("bsub -n 1 -o o{0}.txt -e e{0}.txt \"matlab < script{0}of{1}_step2.m\"".format(str(i),str(maxJob)));
    fs.write("load('mid{0}of{1}_step2.mat');\n".format(str(i),str(maxJob)))
    fs.write("MID = [MID; pValue];")

fs.write("pValue = MID;\n")
fs.write("save('{0}','pValue');\n".format(outputName[1]))

    

