def checkFiles(param, i, option):
    """ Display slices of volumes created by previous steps (data preprocessing with SPM) and check if necessary files for next steps exist.

        Entries:
            - param     parameters dictionary, see main.py
            - i         data set numbering: data exploited are in param["examRep"][i]
            - option    "inter" ou "indep" (see main.py)

        This function return "yes" or "no", that indicates if next step (time series extraction) can be done.

        Local variables:
            - 

        Images (in functional space) displayed are:
            - grey matter (from file natc1*.nii in Processed/[exam name]/Anat/Segmented/)
            - mean time series (from file mean*.nii in Processed/[exam name]/Functional/Realigned/)
            - atlasing (from file natw[atlas name]_u_rc1*.nii in Processed/[exam name]/Anat/Atlased/).
        All three slices are surimposed in a new window (see class WinVolShow), for each atlasing file in list reg (local variable).
        
        This list is completed as follow:
             - if function "coregister" or "coregister,finergrid" has been chosen (function name is in list param["allProcess"]), atlas name is known and corresponding atlasing file is found and added to list reg
             - if no function "coregister" (in dartel or finergrid) has been chosen, list reg is composed by all files whose names are natw*[anatomical file base name].nii
             
        Images displaying is done even if some files are missing, except if reg is empty. Depending on user's choice for entry option, new window appears during a longer or shorter minimum time:
             - if option is "inter", window exist for at least 2 minutes
             - if option is "indep", window exist for at least 10 seconds.
        This parameter is set in local variable delay. See class WinVolShow for more information.

        This function creates repertory QC in Processed/[exam name]/ if not existing, where figures of window created by WinVolShow are saved.
        Figure name contains atlas name (part between 'natw' and 'u_rc1' in atlasing files) to distinguish possible atlased used during preprocessing step.

        It checks following files too:
            - grey matter segmentation in MNI space (file Processed/[exam name]/Anat/Segmented/rc1[anatomical file base name].nii)
            - realigned time series in functional space (files list Processed/[exam name]/Functional/Realigned/r[functional file base name]*.nii)
            - time series movement corrections (file Processed/[exam name]/Functional/Realigned/rp_[functional file base name]*.txt)
        If one of those files is missing, an error message is displayed and function returns "no" (variable nextStep), otherwise it returns "yes".
    """

    from loadAndCheck import checkData, checkDir
    [msg, files] = checkData(param["examRep"][i])
    index = param["examRep"][i].find("Original")
    patientDir = param["examRep"][i][0:index]
    examName = checkDir(param["examRep"][i])[index + 9:]
    anatDir = patientDir + "Processed/" + examName + "Anat/"
    functDir = patientDir + "Processed/" + examName + "Functional/"

    # loading files:
    #   grey matter
    MG = glob.glob(anatDir + "Segmented/natc1" + files["anatBaseName"] + "." +
                   files["anatExt"])
    #   mean time series
    mTS = glob.glob(functDir + "Realigned/mean" + files["functBaseName"] +
                    "*." + files["functExt"])
    #   atlasing into regions
    reg = list()
    if "coregister" in param["allPreprocess"]:
        reg += glob.glob(
            param["allPreprocessInfo"][i]["coregister"].endFile[1])
    if "coregister_finergrid" in param["allPreprocess"]:
        reg += glob.glob(
            param["allPreprocessInfo"][i]["coregister_finergrid"].endFile[1])
    if not ("coregister" in param["allPreprocess"]) and not (
            "coregister_finergrid" in param["allPreprocess"]):
        reg = glob.glob(anatDir + "Atlased/natw" + "*" +
                        files["anatBaseName"] + "." + files["anatExt"])

    # display slices for each atlas used
    for f in reg:
        l0 = f.split("natw")
        l1 = l0[-1].split("u_rc1")
        volList = mTS + MG + [f]
        QCDir = patientDir + "Processed/" + examName + "QC/"  # folder QC to save images
        if os.path.exists(QCDir) is False:
            os.mkdir(QCDir)

        # window maximum duration before closing
        if option == "inter":
            delay = 120
        else:
            delay = 10

        # window to show SPM processing results
        app = WinVolShow(None, i, QCDir, volList, l1[0], delay)
        app.mainloop()

    # check if necessary files exist to proceed processing
    nofiles = list()
    fct = list()
    nextStep = True

    MG_MNI = glob.glob(anatDir + "Segmented/rc1" + files["anatBaseName"] +
                       "." + files["anatExt"])
    rFunct = glob.glob(functDir + "Realigned/r" + files["functBaseName"] +
                       "*." + files["functExt"])
    rpFunct = glob.glob(functDir + "Realigned/rp_" + files["functBaseName"] +
                        "*.txt")

    if (len(rFunct) == 0) or (len(rpFunct) == 0):
        nofiles.append("no realigned time series")
        fct.append("\'realign\'")
    if len(MG_MNI) == 0:
        nofiles.append("no segmentation in grey matter")
        fct.append("\'segment\'")
    if len(reg) == 0:
        nofiles.append("no atlasing in functional space")
        fct.append("\'coregister\'")
    if nofiles != list():
        nextStep = False
        print "WARNING:  ", ("\n           ").join(nofiles)
        print "To do next processing step, SPM function(s)", (
            ", ").join(fct), "must be run."

    return nextStep
def setParamDict(param):
    """ Load and check parameters from text file param["paramFile"]. The aim is to return the same parameters than with GUI mode (see class mainWindow in GUIcodes).

        File is read by method loadParam, that returns dictionary paramStr of parameter names and values in string format.
        Then values are tested, converted or used to get variables in appropriate format, depending on parameter name. For parameters not found, default values may be loaded.
        
        First parameter search is "case":
            - if case is "diffusion", process will be done for diffusion MRI data
            - if case is "functional", process will be done for functional MRI data            
            
        Entry param is a  dictionary of parameters, which may already contains (see config.py, and loadParameter in loadAndCheck.py):
            - mode          "graph" or "script", choice to use GUI or to load parameter file
            - option        choice to interact or not with user
                            "inter" to interact with user in console
                            "indep" otherwise
            - repSPM        mandatory if mode is "script" and "repSPM" is not given in parameter file, and "data preprocessing" is in process list
                            directory to SPM8 functions
            - repR          mandatory if mode is "graph"
                                      if mode is "script" and "repR" is not given in parameter file, and "time series extraction" or "graph computing" are in process list
                            directory to R scripts and functions
            - repTools      mandatory if mode is "graph"
                                      if mode is "script" and "repTools" is not given in parameter file, and "data preprocessing" is in process list
                            directory to matlab functions for data preprocessing (pp_loadVolumes, matlabbatch, etc...)
            - paramFile     mandatory if mode is "script"
                            parameter file name
        
        This method returns dictionary param completed, whose new keys and values are listed below.
                    
        Two parameters are mandatory, otherwise the execution interrupts:
            - case          "functional" or "diffusion", data type
            - examRep       list of directory to medical exam folders
            
        Other parameters can be:
            - process           list of functions names (see module functionsInfo.py)
                                default value : [] (empty list)
            
            - preprocess        for case "functional"
                                if "data preprocessing" is in process
                                list of preprocessing, see module matlabFct.py for names
                                
            - overwrite         for case "functional"
                                if "data preprocessing" is in process
                                values are "y" or "n" (not case sensitive)
                                default value : "n"
                                
            - allPreprocess     for case "functional"
                                if "data preprocessing" is in process
                                detailled matlab functions names list
                                extracted from param['preprocess'] list by method functions
                                
            - allPreprocessInfo for case "functional"
                                if "data preprocessing" is in process
                                list of dictionary of matlab functions informations
                                each element of list param["allPreprocessInfo"] is related to a dataset path in param["examRep"]
                                keys of i-th dictionary param["allPreprocessInfo"][i] are functions names of list param["allPreprocess"]
                                value of param["allPreprocessInfo"][i][f] is the SMPfct class instance (see in module matlabFct), related to dataset in param["examRep"][i] and function f
                                
            - run               for case "functional"
                                if "data preprocessing" is in process
                                list of dictionary of boolean values, same structure as param["allPreprocessInfo"]
                                each element of list param["run"] is related to a dataset path in param["examRep"]
                                keys of i-th dictionary param["run"][i] are functions names of list param["allPreprocess"]
                                param["run"][i][f] is a boolean value, related to dataset in param["examRep"][i] and function f
                                param["run"][i][f] = TRUE  if function f have to be applied to this data in param["examRep"][i] (data never processed or overwriting on existing files)
                                                     FALSE if function won't be applied (data already processed and param["overwrite"] = "n")
                                                     
            - pb                for case "functional"
                                if "data preprocessing" is in process
                                list of dictionary of boolean values, same structure as param["allPreprocessInfo"]
                                each element of list param["pb"] is related to a dataset path in param["examRep"]
                                keys of i-th dictionary param["pb"][i] are functions names of list param["allPreprocess"]
                                param["pb"][i][f] is a boolean value, related to dataset in param["examRep"][i] and function f
                                param["pb"][i][f] = TRUE  if function f can't be applied to this data in param["examRep"][i] (input files are not available, functions choice and order have to be mofified)
                                                    FALSE if function can be applied
        Keys allPreprocessInfo, run and pb are not created if param["preprocess"] is empty


        When data preprocessing have to be done, some tests are done:
            - existence of repertories repSPM, repR or repTools
            - files existence for atlases and templates needed for matlab functions
            - absence of repetitions in functions list, by method reduceList (module loadAndCheck)
            - appropriate folder organization and existence of data, by method checkFolderTree (module loadAndCheck)
            - consistency of functions choice for preprocessing, order and available files, for each dataset, by method checkProcess (module loadAndCheck).
        If one of these tests fails, programm execution is interrupted and user is asked to correct parameter file.
        
        """

    from loadAndCheck import checkDir, checkFolderTree, checkProcess

    # Read parameter file and extract values
    paramStr = loadParam(param["paramFile"])

    # check content of dictionary paramStr
    if not ("case" in paramStr):
        sys.exit(
            "ERROR: no case! Choose between \'functional\' and \'diffusion\'.")
    elif (paramStr["case"] != "functional") and (paramStr["case"] !=
                                                 "diffusion"):
        sys.exit(
            "ERROR in case value! Choose between \'functional\' and \'diffusion\'."
        )
    else:
        param["case"] = paramStr["case"]

    if not "examRep" in paramStr:
        sys.exit(
            "ERROR: no data folder! Give at least one directory to dataset in parameter \'examRep\'."
        )

    # ----- loading values ---- #

    arg = dict()
    for pname in paramStr:

        # overwrite
        if pname == "overwrite":
            ans = (paramStr[pname]).lower()
            if ((ans == "y") or (ans == "n")) is False:
                print "WARNING: can\'t read value for parameter \"overwrite\", set \"n\"."
                param["overwrite"] = "n"
            else:
                param["overwrite"] = ans

        # functions names
        elif pname == "process":
            from functionsInfo import allFunctions
            fctInfo = allFunctions()
            param[pname] = list()
            for p in paramStr[pname].split(","):
                param[pname].append(fctInfo.fctName(p))
                if param[pname][-1] == "error":
                    sys.exit(
                        "ERROR: function \"" + p +
                        "\" not identified, correct \"process\" in parameter file."
                    )
                elif param[pname][-1] not in fctInfo.fctList(paramStr["case"]):
                    sys.exit("ERROR: function \"" + p +
                             "\" not defined for case \"" + paramStr["case"] +
                             "\".")
        elif pname == "preprocess":
            param[pname] = paramStr[pname].split(",")

        elif pname[0:6] == "templ_":
            arg[pname] = paramStr[pname].split(",")

        # files or folders
        else:
            # paths lists
            fList = paramStr[pname].split(",")

            # exam folder list (data list)
            if pname == "examRep":
                param[pname] = list()
                for f in fList:
                    param[pname].append(checkDir(f))
                if len(param[pname]) == 0:
                    sys.exit(
                        "ERROR: no data folder!\nGive at least one directory to dataset in parameter \'examRep\'."
                    )

            # SPM, matlab or R functions folders
            elif (pname == "repSPM") or (pname == "repTools") or (pname
                                                                  == "repR"):
                param[pname] = paramStr[pname]

    # ----- checking values and default setting ---- #

    # check directory to R functions folder, necessary for time series extraction and graph computing, if case is "functional"
    if "process" in param:
        if ("time series extraction"
                in param["process"]) or ("graph computing"
                                         in param["process"]):
            if "repR" in param:
                if param["repR"] == "":
                    sys.exit(
                        "ERROR: no directory to R functions folder in config.py or parameter file. Add parameter \'repR\'."
                    )
                else:
                    param["repR"] = checkDir(param["repR"])
            else:
                sys.exit(
                    "ERROR: no directory to R functions folder in config.py or in parameter file. Add parameter \'repR\'."
                )

    # atlases and templates
    if ("templ_iwarp_dartel" in arg) and ("templ_iwarp" in arg):
        print "WARNING: two atlases defined for function \'iwarp\' in Dartel, \'templ_iwarp\' value loaded only."

    # preprocessing
    param["allPreprocess"] = list()
    generalProcessInfo = dict()
    if "preprocess" in param:
        if "data preprocessing" not in param["process"]:
            print "WARNING: process \"data preprocessing\" not found, no function in \"preprocess\" will be run."
        else:
            i = 0
            from matlabFct import functions, SPMfct

            # check directory to SPM folder, necessary for preprocessing
            if "repSPM" in param:
                if param["repSPM"] == "":
                    sys.exit(
                        "ERROR: no directory to SPM folder in config.py or parameter file. Add parameter \'repSPM\'."
                    )
                else:
                    param["repSPM"] = checkDir(param["repSPM"])
            else:
                sys.exit(
                    "ERROR: no directory to SPM folder in config.py or in parameter file. Add parameter \'repSPM\'."
                )

            # check directory to matlab tools folder, necessary for preprocessing
            if "repTools" in param:
                if param["repTools"] == "":
                    sys.exit(
                        "ERROR: no directory to MATLAB tools folder in config.py or parameter file. Add parameter \'repTools\'."
                    )

                else:
                    param["repTools"] = checkDir(param["repTools"])
            else:
                sys.exit(
                    "ERROR: no directory to MATLAB tools folder in config.py or in parameter file. Add parameter \'repTools\'."
                )

            arg["repSPM"] = param["repSPM"]
            for p in param["preprocess"]:
                for f in functions(p):
                    # function information
                    param["allPreprocess"].append(f)
                    generalProcessInfo[f] = SPMfct(f, **arg)
                    generalProcessInfo[f].nb = i
                    generalProcessInfo[f].parent = p
                    # reference files existence
                    for t in generalProcessInfo[f].template["name"]:
                        if (t != "") and (not path.isfile(t)):
                            sys.exit("ERROR " + t + ": no such file, check " +
                                     generalProcessInfo[f].template["param"] +
                                     " in parameter file.")
                    i += 1

        # redondancy in processes list
        from loadAndCheck import reduceList
        msg = reduceList(param["allPreprocess"])
        if msg == "rep":
            sys.exit(
                "ERROR: redondancy in functions list, modify it in parameter process.\nNB: functions \"dartel\" and \"finergrid\" include several other functions."
            )

    else:
        param["preprocess"] = list()

    if not ("overwrite" in param):
        param["overwrite"] = "n"

    # Check data folders
    msg, dataInfo = checkFolderTree(param["examRep"])
    for i, m in enumerate(msg):
        if m[0:5] == "ERROR":
            sys.exit(m + "\n   -> check data or parameter file.")

    # Check functions consistency for data preprocessing
    param["run"], param["pb"], param["allPreprocessInfo"] = checkProcess(
        param["allPreprocess"], generalProcessInfo, param["examRep"], dataInfo,
        param["overwrite"])

    return param
def checkFiles(param, i, option):
    """ Display slices of volumes created by previous steps (data preprocessing with SPM) and check if necessary files for next steps exist.

        Entries:
            - param     parameters dictionary, see main.py
            - i         data set numbering: data exploited are in param["examRep"][i]
            - option    "inter" ou "indep" (see main.py)

        This function return "yes" or "no", that indicates if next step (time series extraction) can be done.

        Local variables:
            - 

        Images (in functional space) displayed are:
            - grey matter (from file natc1*.nii in Processed/[exam name]/Anat/Segmented/)
            - mean time series (from file mean*.nii in Processed/[exam name]/Functional/Realigned/)
            - atlasing (from file natw[atlas name]_u_rc1*.nii in Processed/[exam name]/Anat/Atlased/).
        All three slices are surimposed in a new window (see class WinVolShow), for each atlasing file in list reg (local variable).
        
        This list is completed as follow:
             - if function "coregister" or "coregister,finergrid" has been chosen (function name is in list param["allProcess"]), atlas name is known and corresponding atlasing file is found and added to list reg
             - if no function "coregister" (in dartel or finergrid) has been chosen, list reg is composed by all files whose names are natw*[anatomical file base name].nii
             
        Images displaying is done even if some files are missing, except if reg is empty. Depending on user's choice for entry option, new window appears during a longer or shorter minimum time:
             - if option is "inter", window exist for at least 2 minutes
             - if option is "indep", window exist for at least 10 seconds.
        This parameter is set in local variable delay. See class WinVolShow for more information.

        This function creates repertory QC in Processed/[exam name]/ if not existing, where figures of window created by WinVolShow are saved.
        Figure name contains atlas name (part between 'natw' and 'u_rc1' in atlasing files) to distinguish possible atlased used during preprocessing step.

        It checks following files too:
            - grey matter segmentation in MNI space (file Processed/[exam name]/Anat/Segmented/rc1[anatomical file base name].nii)
            - realigned time series in functional space (files list Processed/[exam name]/Functional/Realigned/r[functional file base name]*.nii)
            - time series movement corrections (file Processed/[exam name]/Functional/Realigned/rp_[functional file base name]*.txt)
        If one of those files is missing, an error message is displayed and function returns "no" (variable nextStep), otherwise it returns "yes".
    """

    from loadAndCheck import checkData, checkDir

    [msg, files] = checkData(param["examRep"][i])
    index = param["examRep"][i].find("Original")
    patientDir = param["examRep"][i][0:index]
    examName = checkDir(param["examRep"][i])[index + 9 :]
    anatDir = patientDir + "Processed/" + examName + "Anat/"
    functDir = patientDir + "Processed/" + examName + "Functional/"

    # loading files:
    #   grey matter
    MG = glob.glob(anatDir + "Segmented/natc1" + files["anatBaseName"] + "." + files["anatExt"])
    #   mean time series
    mTS = glob.glob(functDir + "Realigned/mean" + files["functBaseName"] + "*." + files["functExt"])
    #   atlasing into regions
    reg = list()
    if "coregister" in param["allPreprocess"]:
        reg += glob.glob(param["allPreprocessInfo"][i]["coregister"].endFile[1])
    if "coregister_finergrid" in param["allPreprocess"]:
        reg += glob.glob(param["allPreprocessInfo"][i]["coregister_finergrid"].endFile[1])
    if not ("coregister" in param["allPreprocess"]) and not ("coregister_finergrid" in param["allPreprocess"]):
        reg = glob.glob(anatDir + "Atlased/natw" + "*" + files["anatBaseName"] + "." + files["anatExt"])

    # display slices for each atlas used
    for f in reg:
        l0 = f.split("natw")
        l1 = l0[-1].split("u_rc1")
        volList = mTS + MG + [f]
        QCDir = patientDir + "Processed/" + examName + "QC/"  # folder QC to save images
        if os.path.exists(QCDir) is False:
            os.mkdir(QCDir)

        # window maximum duration before closing
        if option == "inter":
            delay = 120
        else:
            delay = 10

        # window to show SPM processing results
        app = WinVolShow(None, i, QCDir, volList, l1[0], delay)
        app.mainloop()

    # check if necessary files exist to proceed processing
    nofiles = list()
    fct = list()
    nextStep = True

    MG_MNI = glob.glob(anatDir + "Segmented/rc1" + files["anatBaseName"] + "." + files["anatExt"])
    rFunct = glob.glob(functDir + "Realigned/r" + files["functBaseName"] + "*." + files["functExt"])
    rpFunct = glob.glob(functDir + "Realigned/rp_" + files["functBaseName"] + "*.txt")

    if (len(rFunct) == 0) or (len(rpFunct) == 0):
        nofiles.append("no realigned time series")
        fct.append("'realign'")
    if len(MG_MNI) == 0:
        nofiles.append("no segmentation in grey matter")
        fct.append("'segment'")
    if len(reg) == 0:
        nofiles.append("no atlasing in functional space")
        fct.append("'coregister'")
    if nofiles != list():
        nextStep = False
        print "WARNING:  ", ("\n           ").join(nofiles)
        print "To do next processing step, SPM function(s)", (", ").join(fct), "must be run."

    return nextStep
def setParamDict(param):
    """ Load and check parameters from text file param["paramFile"]. The aim is to return the same parameters than with GUI mode (see class mainWindow in GUIcodes).

        File is read by method loadParam, that returns dictionary paramStr of parameter names and values in string format.
        Then values are tested, converted or used to get variables in appropriate format, depending on parameter name. For parameters not found, default values may be loaded.
        
        First parameter search is "case":
            - if case is "diffusion", process will be done for diffusion MRI data
            - if case is "functional", process will be done for functional MRI data            
            
        Entry param is a  dictionary of parameters, which may already contains (see config.py, and loadParameter in loadAndCheck.py):
            - mode          "graph" or "script", choice to use GUI or to load parameter file
            - option        choice to interact or not with user
                            "inter" to interact with user in console
                            "indep" otherwise
            - repSPM        mandatory if mode is "script" and "repSPM" is not given in parameter file, and "data preprocessing" is in process list
                            directory to SPM8 functions
            - repR          mandatory if mode is "graph"
                                      if mode is "script" and "repR" is not given in parameter file, and "time series extraction" or "graph computing" are in process list
                            directory to R scripts and functions
            - repTools      mandatory if mode is "graph"
                                      if mode is "script" and "repTools" is not given in parameter file, and "data preprocessing" is in process list
                            directory to matlab functions for data preprocessing (pp_loadVolumes, matlabbatch, etc...)
            - paramFile     mandatory if mode is "script"
                            parameter file name
        
        This method returns dictionary param completed, whose new keys and values are listed below.
                    
        Two parameters are mandatory, otherwise the execution interrupts:
            - case          "functional" or "diffusion", data type
            - examRep       list of directory to medical exam folders
            
        Other parameters can be:
            - process           list of functions names (see module functionsInfo.py)
                                default value : [] (empty list)
            
            - preprocess        for case "functional"
                                if "data preprocessing" is in process
                                list of preprocessing, see module matlabFct.py for names
                                
            - overwrite         for case "functional"
                                if "data preprocessing" is in process
                                values are "y" or "n" (not case sensitive)
                                default value : "n"
                                
            - allPreprocess     for case "functional"
                                if "data preprocessing" is in process
                                detailled matlab functions names list
                                extracted from param['preprocess'] list by method functions
                                
            - allPreprocessInfo for case "functional"
                                if "data preprocessing" is in process
                                list of dictionary of matlab functions informations
                                each element of list param["allPreprocessInfo"] is related to a dataset path in param["examRep"]
                                keys of i-th dictionary param["allPreprocessInfo"][i] are functions names of list param["allPreprocess"]
                                value of param["allPreprocessInfo"][i][f] is the SMPfct class instance (see in module matlabFct), related to dataset in param["examRep"][i] and function f
                                
            - run               for case "functional"
                                if "data preprocessing" is in process
                                list of dictionary of boolean values, same structure as param["allPreprocessInfo"]
                                each element of list param["run"] is related to a dataset path in param["examRep"]
                                keys of i-th dictionary param["run"][i] are functions names of list param["allPreprocess"]
                                param["run"][i][f] is a boolean value, related to dataset in param["examRep"][i] and function f
                                param["run"][i][f] = TRUE  if function f have to be applied to this data in param["examRep"][i] (data never processed or overwriting on existing files)
                                                     FALSE if function won't be applied (data already processed and param["overwrite"] = "n")
                                                     
            - pb                for case "functional"
                                if "data preprocessing" is in process
                                list of dictionary of boolean values, same structure as param["allPreprocessInfo"]
                                each element of list param["pb"] is related to a dataset path in param["examRep"]
                                keys of i-th dictionary param["pb"][i] are functions names of list param["allPreprocess"]
                                param["pb"][i][f] is a boolean value, related to dataset in param["examRep"][i] and function f
                                param["pb"][i][f] = TRUE  if function f can't be applied to this data in param["examRep"][i] (input files are not available, functions choice and order have to be mofified)
                                                    FALSE if function can be applied
        Keys allPreprocessInfo, run and pb are not created if param["preprocess"] is empty


        When data preprocessing have to be done, some tests are done:
            - existence of repertories repSPM, repR or repTools
            - files existence for atlases and templates needed for matlab functions
            - absence of repetitions in functions list, by method reduceList (module loadAndCheck)
            - appropriate folder organization and existence of data, by method checkFolderTree (module loadAndCheck)
            - consistency of functions choice for preprocessing, order and available files, for each dataset, by method checkProcess (module loadAndCheck).
        If one of these tests fails, programm execution is interrupted and user is asked to correct parameter file.
        
        """

    from loadAndCheck import checkDir, checkFolderTree, checkProcess

    # Read parameter file and extract values
    paramStr = loadParam(param["paramFile"])

    # check content of dictionary paramStr
    if not ("case" in paramStr):
        sys.exit("ERROR: no case! Choose between \'functional\' and \'diffusion\'.")
    elif (paramStr["case"] != "functional") and (paramStr["case"] != "diffusion"):
        sys.exit("ERROR in case value! Choose between \'functional\' and \'diffusion\'.")
    else:
        param["case"] = paramStr["case"]
        
    if not "examRep" in paramStr:
        sys.exit("ERROR: no data folder! Give at least one directory to dataset in parameter \'examRep\'.")

    # ----- loading values ---- #
    
    arg = dict()
    for pname in paramStr:

        # overwrite
        if pname == "overwrite":
            ans = (paramStr[pname]).lower()
            if ((ans == "y") or (ans == "n")) is False:
                print "WARNING: can\'t read value for parameter \"overwrite\", set \"n\"."
                param["overwrite"] = "n"
            else:
                param["overwrite"] = ans

        # functions names
        elif pname == "process":
            from functionsInfo import allFunctions
            fctInfo = allFunctions()
            param[pname] = list()
            for p in paramStr[pname].split(","):
                param[pname].append(fctInfo.fctName(p))
                if param[pname][-1] == "error":
                    sys.exit("ERROR: function \"" + p + "\" not identified, correct \"process\" in parameter file.")
                elif param[pname][-1] not in fctInfo.fctList(paramStr["case"]):
                    sys.exit("ERROR: function \"" + p + "\" not defined for case \"" + paramStr["case"] + "\".")
        elif pname == "preprocess":
            param[pname] = paramStr[pname].split(",")
        
        elif pname[0:6] == "templ_":
            arg[pname] = paramStr[pname].split(",")
            
        # files or folders
        else:
            # paths lists
            fList = paramStr[pname].split(",")

	    # exam folder list (data list)
            if pname == "examRep":
                param[pname] = list()
                for f in fList:
                    param[pname].append(checkDir(f))
                if len(param[pname]) == 0:
                    sys.exit("ERROR: no data folder!\nGive at least one directory to dataset in parameter \'examRep\'.")                    
                        
            # SPM, matlab or R functions folders
            elif (pname == "repSPM") or (pname == "repTools") or (pname == "repR"):
                param[pname] = paramStr[pname]

    # ----- checking values and default setting ---- #

    # check directory to R functions folder, necessary for time series extraction and graph computing, if case is "functional"
    if "process"in param:
        if ("time series extraction" in param["process"]) or ("graph computing" in param["process"]):
            if "repR" in param:
                if param["repR"] == "":
                    sys.exit("ERROR: no directory to R functions folder in config.py or parameter file. Add parameter \'repR\'.")
                else:
                    param["repR"] = checkDir(param["repR"])
            else:
                sys.exit("ERROR: no directory to R functions folder in config.py or in parameter file. Add parameter \'repR\'.")

    # atlases and templates
    if ("templ_iwarp_dartel" in arg) and ("templ_iwarp" in arg):
        print "WARNING: two atlases defined for function \'iwarp\' in Dartel, \'templ_iwarp\' value loaded only."

    # preprocessing
    param["allPreprocess"] = list()
    generalProcessInfo = dict()
    if "preprocess" in param:
        if "data preprocessing" not in param["process"]:
            print "WARNING: process \"data preprocessing\" not found, no function in \"preprocess\" will be run."
        else:
            i = 0
            from matlabFct import functions, SPMfct
            
            # check directory to SPM folder, necessary for preprocessing
            if "repSPM" in param:
                if param["repSPM"] == "":
                    sys.exit("ERROR: no directory to SPM folder in config.py or parameter file. Add parameter \'repSPM\'.")
                else:
                    param["repSPM"] = checkDir(param["repSPM"])
            else:
                sys.exit("ERROR: no directory to SPM folder in config.py or in parameter file. Add parameter \'repSPM\'.")
                
             # check directory to matlab tools folder, necessary for preprocessing
            if "repTools" in param:
                if param["repTools"] == "":
                    sys.exit("ERROR: no directory to MATLAB tools folder in config.py or parameter file. Add parameter \'repTools\'.")

                else:
                    param["repTools"] = checkDir(param["repTools"])
            else:
                sys.exit("ERROR: no directory to MATLAB tools folder in config.py or in parameter file. Add parameter \'repTools\'.")        

            arg["repSPM"] = param["repSPM"]
            for p in param["preprocess"]:
                for f in functions(p):
                    # function information
                    param["allPreprocess"].append(f)
                    generalProcessInfo[f] = SPMfct(f, **arg)
                    generalProcessInfo[f].nb = i
                    generalProcessInfo[f].parent = p
                    # reference files existence
                    for t in generalProcessInfo[f].template["name"]:
                        if (t != "") and (not path.isfile(t)):
                            sys.exit("ERROR " + t + ": no such file, check " + generalProcessInfo[f].template["param"] + " in parameter file.")    
                    i += 1

        # redondancy in processes list
        from loadAndCheck import reduceList
        msg = reduceList(param["allPreprocess"])
        if msg == "rep":
            sys.exit("ERROR: redondancy in functions list, modify it in parameter process.\nNB: functions \"dartel\" and \"finergrid\" include several other functions.")
            
    else:
        param["preprocess"] = list()
    

    if not ("overwrite" in param):
        param["overwrite"] = "n"

    # Check data folders
    msg, dataInfo = checkFolderTree(param["examRep"])
    for i, m in enumerate(msg):
        if m[0:5] == "ERROR":
            sys.exit(m + "\n   -> check data or parameter file.")

    # Check functions consistency for data preprocessing
    param["run"], param["pb"], param["allPreprocessInfo"] = checkProcess(param["allPreprocess"], generalProcessInfo, param["examRep"], dataInfo, param["overwrite"])
        
    return param