"""
PySCeS - Python Simulator for Cellular Systems (http://pysces.sourceforge.net)

Copyright (C) 2004-2014 B.G. Olivier, J.M. Rohwer, J.-H.S Hofmeyr all rights reserved,

Johann Rohwer (jrohwer@users.sourceforge.net)
Triple-J Group for Molecular Cell Physiology
Stellenbosch University, South Africa.

Permission to use, modify, and distribute this software is given under the
terms of the PySceS (BSD style) license. See LICENSE.txt that came with
this distribution for specifics.

NO WARRANTY IS EXPRESSED OR IMPLIED.  USE AT YOUR OWN RISK.
Johann M. Rohwer
"""

import sys, cPickle
import multiprocessing
from pysces.PyscesParScan import Analyze, setModValue
from pysces.PyscesUtils import TimerBox
from time import sleep


if __name__ == '__main__':
    print "\nmultiprocessing script command line:"
    print sys.argv
    # called with
    # subprocess.call(['python', MULTISCANFILE, self._MODE_, fN])
    MODE = sys.argv[1]
    pool = multiprocessing.Pool()

    # load stuff from the pickle
    F = file(sys.argv[2],'rb')
    mod, scanpartition, seqpartition, genorder, useroutputlist = cPickle.load(F)
    F.close()

    mod.SetQuiet()  # kill verbose output during scan
    # append tasks to asynchronous results list
    arl = []
    for i in range(len(scanpartition)):
        arl.append(pool.apply_async(Analyze, (scanpartition[i], seqpartition[i], genorder, MODE, useroutputlist, mod)))

    print "Submitted tasks:", len(arl)
    print "\nPARALLEL COMPUTATION\n--------------------"

    while arl[-1].ready() != True:
        sleep(5)
        print 'Tasks to go... ', [r.ready() for r in arl].count(False)
        # wait until all tasks are completed
    arl[-1].wait()

    # get results
    print "\nGATHER RESULT\n-------------"
    res_list = []
    for ar in arl:
        res_list.append(ar.get())
    # pickle results_list
    F = file(sys.argv[2], 'wb')
    cPickle.dump(res_list, F, protocol=-1)
    F.flush()
    F.close()
