From cdce491b7c6d384b0a580760795ae10bdb473d7b Mon Sep 17 00:00:00 2001
From: imcovangent <I.vanGent@tudelft.nl>
Date: Wed, 5 Sep 2018 11:29:01 +0200
Subject: [PATCH] Finished update of local VISTOMS including session handling.

Former-commit-id: 8068f4e149cab262977ed8da53d97bfbf0bd7673
---
 kadmos/vistoms/templates/VISTOMS.html |  68 ++--
 kadmos/vistoms/vistoms.py             | 481 +++++++++++++++++---------
 2 files changed, 347 insertions(+), 202 deletions(-)

diff --git a/kadmos/vistoms/templates/VISTOMS.html b/kadmos/vistoms/templates/VISTOMS.html
index 450a650cf..f446edae8 100644
--- a/kadmos/vistoms/templates/VISTOMS.html
+++ b/kadmos/vistoms/templates/VISTOMS.html
@@ -150,6 +150,7 @@
                 $.ajax({
                     type: 'POST', 
                     url: '/kadmos_remove_obsolete_files',
+                    data: {'sessionId': sessionId},
                     success: function(result){},
                     error: function(result)
                     {
@@ -453,6 +454,7 @@
                     var xhr = $.ajax({
                         type: 'POST',
                         url: '/kadmos_find_temp_graphs',
+                        data: {'sessionId': sessionId},
                         success: function(result)
                         {
                             if (result.includes("ERROR:"))
@@ -958,7 +960,7 @@
                                     var files = result
                                     files.forEach(function(file)
                                     {
-                                        download_from_kadmos(file,"/kadmos_download/"+file)
+                                        download_from_kadmos(file,"/kadmos_download/"+file+"/"+sessionId)
                                     })
                                     
                                     
@@ -19062,7 +19064,7 @@
 							data: {
 							'graphID':graphID, 
 							'variableData_str':variableData_str,
-							'currentOrder':nodeOrder
+							'currentOrder':nodeOrder, 'sessionId': sessionId
 						},
 						success: function(result)
 						{
@@ -19112,7 +19114,7 @@
 							data: {
 							'graphID':graphID, 
 							'xPath':xPath, 
-							'currentOrder':nodeOrder
+							'currentOrder':nodeOrder, 'sessionId': sessionId
 						},
 						success: function(result)
 						{
@@ -19631,7 +19633,7 @@
                                         var xhr = $.ajax({
                                             type: 'POST',
                                             url: '/kadmos_change_node_pos',
-                                            data: {'graphID':graphID, 'nodeName':aNode.uID, 'newPos':newPos, 'currentOrder':nodeOrder},
+                                            data: {'graphID':graphID, 'nodeName':aNode.uID, 'newPos':newPos, 'currentOrder':nodeOrder, 'sessionId': sessionId},
                                             success: function(result)
                                             {
                                                 if (result.includes("ERROR:"))
@@ -19685,7 +19687,7 @@
                             var xhr = $.ajax({
                                 type: 'POST',
                                 url: '/kadmos_delete_node',
-                                data: {'graphID':graphID, 'nodeName':aNode.uID, 'currentOrder':nodeOrder},
+                                data: {'graphID':graphID, 'nodeName':aNode.uID, 'currentOrder':nodeOrder, 'sessionId': sessionId},
                                 success: function(result)
                                 {
                                     if (result.includes("ERROR:"))
@@ -19809,7 +19811,7 @@
                                 var xhr = $.ajax({
                                     type: 'POST',
                                     url: '/kadmos_add_mathematical_function',
-                                    data: {'graphID':graphID, 'currentOrder':nodeOrder, 'form_data':JSON.stringify(form_data)},
+                                    data: {'graphID':graphID, 'currentOrder':nodeOrder, 'form_data':JSON.stringify(form_data), 'sessionId': sessionId},
                                     success: function(result)
                                     {
                                         if (result.includes("ERROR:"))
@@ -20040,14 +20042,15 @@
                     var xhr = $.ajax(
                     {
                         type: 'POST',
-                        data: {'fileName':currentGraph.name, 'fileType': fileType, 'graphID': graphID},
+                        data: {'fileName':currentGraph.name, 'fileType': fileType, 'graphID': graphID,
+                            'sessionId': sessionId},
                         url: '/kadmos_export_graph',
                         success: function(result)
                         {                
                             var files = result
                             files.forEach(function(file)
                             {
-                                download_from_kadmos(file,"/kadmos_download/"+file)
+                                download_from_kadmos(file,"/kadmos_download/"+file+"/"+sessionId)
                             })
                             
                             if (result.includes("ERROR:"))
@@ -20134,7 +20137,7 @@
                                                 var xhr = $.ajax(
                                                 {
                                                     type: 'POST',
-                                                    data: {'graphID': graphID, 'newGraphID': newGraphID, 'newGraphName': newGraphName, 'currentOrder':nodeOrder},
+                                                    data: {'graphID': graphID, 'newGraphID': newGraphID, 'newGraphName': newGraphName, 'currentOrder':nodeOrder, 'sessionId': sessionId},
                                                     url: '/kadmos_save_vistoms_graph',
                                                     success: function(result)
                                                     {
@@ -20213,7 +20216,7 @@
                             {
                                 type: 'POST',
                                 url: '/kadmos_delete_graph',
-                                data: {'graphID':graphID},
+                                data: {'graphID':graphID, 'sessionId': sessionId},
                                 success: function(result)
                                 {
                                     if (result.includes("ERROR:"))
@@ -20281,7 +20284,7 @@
                             {
                                 type: 'POST',
                                 url: '/kadmos_revert_step',
-                                data: {'graphID':graphID},
+                                data: {'graphID':graphID, 'sessionId': sessionId},
                                 success: function(result)
                                 {
                                     if (result.includes("ERROR:"))
@@ -20420,6 +20423,7 @@
                         formData.append('graphID', graphID);
                         formData.append('currentOrder',nodeOrder);
                         formData.append('function_node', $('form #function_node').val());
+                        formData.append('sessionId', sessionId);
                        
                         var bootboxContent = {title: "Add design competence", message: '<p>Please be patient...</p>'};
                         var xhr = $.ajax({
@@ -20702,7 +20706,7 @@
                                 {
                                     type: 'POST',
                                     url: '/kadmos_add_DC_metadata',
-                                    data: {'graphID':graphID, 'currentOrder':nodeOrder, 'nodeName':metadata.uID, 'metadata_str':metadata_str},
+                                    data: {'graphID':graphID, 'currentOrder':nodeOrder, 'nodeName':metadata.uID, 'metadata_str':metadata_str, 'sessionId': sessionId},
                                     success: function(result)
                                     {
                                         if (result.includes("ERROR:"))
@@ -20890,7 +20894,7 @@
                                 var bootboxContent = {title: "Update contact information", message: '<p>Please be patient...</p>'};
                                 var xhr = $.ajax({
                                     type: 'POST',
-                                    data: {'graphID': graphID, 'currentOrder': nodeOrder, 'organization': JSON.stringify(currentGraph.organization)},
+                                    data: {'graphID': graphID, 'currentOrder': nodeOrder, 'organization': JSON.stringify(currentGraph.organization), 'sessionId': sessionId},
                                     url: '/kadmos_edit_contact_infos',
                                     success: function(result)
                                     {
@@ -21312,7 +21316,8 @@
                                            'attr_include':JSON.stringify(attr_include),
                                            'attr_exclude':JSON.stringify(attr_exclude),
                                            'xPath_include':xPath_include,
-                                           'xPath_exclude':xPath_exclude,},
+                                           'xPath_exclude':xPath_exclude,
+                                           'sessionId': sessionId,},
                                     success: function(result)
                                     {
                                         if (result.includes("ERROR:"))
@@ -21485,7 +21490,7 @@
                         var bootboxContent = {title: "L1 check: graph", message: '<p>Please be patient...</p>'};
                         var xhr = $.ajax({
                             type: 'POST',
-                            data: {'graphID': graphID},
+                            data: {'graphID': graphID, 'sessionId': sessionId},
                             url: '/kadmos_L1_check',
                             success: function(result)
                             {
@@ -21517,7 +21522,7 @@
                         var bootboxContent = {title: "L2 check: problem formulation", message: '<p>Please be patient...</p>'};
                         var xhr = $.ajax({
                             type: 'POST',
-                            data: {'graphID': graphID},
+                            data: {'graphID': graphID, 'sessionId': sessionId},
                             url: '/kadmos_L2_check',
                             success: function(result)
                             {
@@ -21549,7 +21554,7 @@
                         var bootboxContent = {title: "L3 check: graph & problem formulation", message: '<p>Please be patient...</p>'};
                         var xhr = $.ajax({
                             type: 'POST',
-                            data: {'graphID': graphID},
+                            data: {'graphID': graphID, 'sessionId': sessionId},
                             url: '/kadmos_L3_check',
                             success: function(result)
                             {
@@ -21617,7 +21622,7 @@
                                     var xhr = $.ajax({
                                         type: 'POST',
                                         url: '/kadmos_start_defining_MDO_problem',
-                                        data: {'graphID':graphID, 'currentOrder': nodeOrder, 'newGraphName':newGraphName, 'newGraphID':newGraphID},
+                                        data: {'graphID':graphID, 'currentOrder': nodeOrder, 'newGraphName':newGraphName, 'newGraphID':newGraphID, 'sessionId': sessionId},
                                         success: function(result)
                                         {
                                             if (result.includes("ERROR:"))
@@ -21693,7 +21698,7 @@
                                             var xhr = $.ajax({
                                                 type: 'POST',
                                                 url: '/kadmos_exclude_DCs',
-                                                data: {'graphID':graphID, 'nodeList':nodeStr, 'currentOrder':nodeOrder},
+                                                data: {'graphID':graphID, 'nodeList':nodeStr, 'currentOrder':nodeOrder, 'sessionId': sessionId},
                                                 success: function(result)
                                                 {
                                                     if (result.includes("ERROR:"))
@@ -21767,7 +21772,7 @@
                                             var xhr = $.ajax({
                                                 type: 'POST',
                                                 url: '/kadmos_merge_seq_DCs',
-                                                data: {'graphID':graphID, 'nodeList':nodeStr, 'currentOrder':nodeOrder},
+                                                data: {'graphID':graphID, 'nodeList':nodeStr, 'currentOrder':nodeOrder, 'sessionId': sessionId},
                                                 success: function(result)
                                                 {
                                                     if (result.includes("ERROR:"))
@@ -21842,7 +21847,7 @@
                                             var xhr = $.ajax({
                                                 type: 'POST',
                                                 url: '/kadmos_merge_parallel_DCs',
-                                                data: {'graphID':graphID, 'nodeList':nodeStr, 'currentOrder':nodeOrder},
+                                                data: {'graphID':graphID, 'nodeList':nodeStr, 'currentOrder':nodeOrder, 'sessionId': sessionId},
                                                 success: function(result)
                                                 {
                                                     if (result.includes("ERROR:"))
@@ -21917,7 +21922,7 @@
                                             var xhr = $.ajax({
                                                 type: 'POST',
                                                 url: '/kadmos_merge_func_mod_DCs',
-                                                data: {'graphID':graphID, 'nodeList':nodeStr, 'currentOrder':nodeOrder},
+                                                data: {'graphID':graphID, 'nodeList':nodeStr, 'currentOrder':nodeOrder, 'sessionId': sessionId},
                                                 success: function(result)
                                                 {
                                                     if (result.includes("ERROR:"))
@@ -21992,7 +21997,7 @@
                                             var xhr = $.ajax({
                                                 type: 'POST',
                                                 url: '/kadmos_remove_collision',
-                                                data: {'graphID':graphID, 'nodeList':nodeStr, 'currentOrder':nodeOrder},
+                                                data: {'graphID':graphID, 'nodeList':nodeStr, 'currentOrder':nodeOrder, 'sessionId': sessionId},
                                                 success: function(result)
                                                 {
                                                     if (result.includes("ERROR:"))
@@ -22051,7 +22056,7 @@
                                 var xhr = $.ajax({
                                     type: 'POST',
                                     url: '/kadmos_make_all_variables_valid',
-                                    data: {'graphID':graphID, 'currentOrder':nodeOrder},
+                                    data: {'graphID':graphID, 'currentOrder':nodeOrder, 'sessionId': sessionId},
                                     success: function(result)
                                     {
                                         if (result.includes("ERROR:"))
@@ -22105,7 +22110,7 @@
                                 var xhr = $.ajax({
                                     type: 'POST',
                                     url: '/kadmos_add_function_problem_roles',
-                                    data: {'graphID':graphID, 'currentOrder':nodeOrder},
+                                    data: {'graphID':graphID, 'currentOrder':nodeOrder, 'sessionId': sessionId},
                                     success: function(result)
                                     {
                                         if (result.includes("ERROR:"))
@@ -22213,7 +22218,7 @@
                                     var xhr = $.ajax({
                                         type: 'POST',
                                         url: '/kadmos_get_possible_function_order',
-                                        data: {'graphID':graphID, 'sortingMethod':method, 'currentOrder':nodeOrder},
+                                        data: {'graphID':graphID, 'sortingMethod':method, 'currentOrder':nodeOrder, 'sessionId': sessionId},
                                         success: function(result)
                                         {
                                             if (result.includes("ERROR:"))
@@ -22276,7 +22281,8 @@
                                     var xhr = $.ajax({
                                         type: 'POST',
                                         url: '/kadmos_remove_unused_outputs',
-                                        data: {'graphID':graphID, 'currentOrder':nodeOrder, 'cleanUp':selection},
+                                        data: {'graphID':graphID, 'currentOrder':nodeOrder, 'cleanUp':selection,
+                                            'sessionId': sessionId},
                                         success: function(result)
                                         {
                                             if (result.includes("ERROR:"))
@@ -22361,7 +22367,7 @@
                                     var xhr = $.ajax({
                                         type: 'POST',
                                         url: '/kadmos_start_defining_MDAO_architecture',
-                                        data: {'graphID':graphID, 'currentOrder': nodeOrder, 'newGraphName':newGraphName, 'newGraphID':newGraphID},
+                                        data: {'graphID':graphID, 'currentOrder': nodeOrder, 'newGraphName':newGraphName, 'newGraphID':newGraphID, 'sessionId': sessionId},
                                         success: function(result)
                                         {
                                             if (result.includes("ERROR:"))
@@ -22490,7 +22496,8 @@
                                                'mdao_architecture':MDAO_architecture,
                                                'doe_method':DOE_method,
                                                'coupling_decomposition':coupling_decomposition,
-                                               'allow_unconverged_couplings':allow_unconverged_couplings},
+                                               'allow_unconverged_couplings':allow_unconverged_couplings,
+                                               'sessionId':sessionId},
                                         success: function(result)
                                         {
                                             if (result.includes("ERROR:"))
@@ -22589,6 +22596,7 @@
                                 event.preventDefault();
                                 var formData = new FormData($('#scriptForm')[0]);
                                 formData.append('graphID', graphID);
+                                formData.append('sessionId', sessionId);
                                
                                 if (typeof currentGraph.xdsm.workflow !== 'undefined' && currentGraph.xdsm.workflow.length > 0) 
                                 {
@@ -23156,7 +23164,7 @@
                                                     var xhr = $.ajax({
                                                         type: 'POST',
                                                         url: '/kadmos_delete_edge',
-                                                        data: {graphID: graphID, nodeName: anEdge.from_uID, edgeName: formData[0].value, 'currentOrder':nodeOrder},
+                                                        data: {graphID: graphID, nodeName: anEdge.from_uID, edgeName: formData[0].value, 'currentOrder':nodeOrder, 'sessionId': sessionId},
                                                         success: function(result)
                                                         {
                                                             if (result.includes("ERROR:"))
diff --git a/kadmos/vistoms/vistoms.py b/kadmos/vistoms/vistoms.py
index bec1611a2..ddbef6888 100644
--- a/kadmos/vistoms/vistoms.py
+++ b/kadmos/vistoms/vistoms.py
@@ -80,7 +80,7 @@ def interface(debug=True, tempdir=None):
 
                 number_of_files = len(uploaded_files)
                 if number_of_files > 2:
-                    return("ERROR: Max. number of files that can be uploaded is 2!")
+                    return "ERROR: Max. number of files that can be uploaded is 2!"
 
                 mpgFile = []
                 dgFile = []
@@ -92,20 +92,20 @@ def interface(debug=True, tempdir=None):
 
                 # check if the post request has the file part
                 if 'file[]' not in request.files:
-                   return("ERROR: No file part!")
+                   return "ERROR: No file part!"
 
                 # if user does not select file, browser also
                 # submit a empty part without filename
                 if dgFile.filename == '':
-                    return("ERROR: No file part!")
+                    return "ERROR: No file part!"
                 if dgFile:
                     # Check if the right filetypes were chosen
                     if fileType == 'CMDOWS file' and dgFile.filename.rsplit('.', 1)[1].lower() != "xml":
-                        return ("ERROR: Wrong file type! Please use a valid CMDOWS file")
+                        return "ERROR: Wrong file type! Please use a valid CMDOWS file"
                     elif fileType == 'KDMS file(s)' and dgFile.filename.rsplit('.', 1)[1].lower() != "kdms":
-                        return ("ERROR: Wrong file type! Please use a valid KDMS file")
+                        return "ERROR: Wrong file type! Please use a valid KDMS file"
                     elif fileType == 'Database' and dgFile.filename.rsplit('.', 1)[1].lower() != "zip":
-                        return ("ERROR: Wrong file type! Please use a valid zip file")
+                        return "ERROR: Wrong file type! Please use a valid zip file"
 
                     session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
 
@@ -141,7 +141,7 @@ def interface(debug=True, tempdir=None):
                     elif mpgFile:
                         # Check if the right filetype was chosen
                         if mpgFile.filename.rsplit('.', 1)[1].lower() != "kdms":
-                            return ("ERROR: Wrong file type! Please use a valid KDMS file")
+                            return "ERROR: Wrong file type! Please use a valid KDMS file"
                         graph = loaded_graph
                         mpgFileName = mpgFile.filename
                         mpgFile.save(os.path.join(session_folder, mpgFileName))
@@ -173,7 +173,7 @@ def interface(debug=True, tempdir=None):
 
                     return newVistomsData
 
-            return("ERROR: File type " + dgFile.filename.rsplit('.', 1)[1].lower() + " not allowed!")
+            return "ERROR: File type " + dgFile.filename.rsplit('.', 1)[1].lower() + " not allowed!"
 
         except Exception as e:
             return "ERROR: " + e.message
@@ -301,10 +301,12 @@ def interface(debug=True, tempdir=None):
             return "ERROR: " + e.message
             # Logs the error appropriately.
 
-    @app.route('/kadmos_download/<path:filename>')
-    def kadmos_download(filename):
+    # TODO Benedikt: Download of CMDOWS does not work for me.
+    @app.route('/kadmos_download/<path:filename>/<path:session_id>')
+    def kadmos_download(filename, session_id):
         try:
-            return send_from_directory(directory=SESSIONS_CATALOG_FOLDER, filename=filename)
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+            return send_from_directory(directory=session_folder, filename=filename)
 
         except Exception as e:
             return "ERROR: " + e.message
@@ -313,9 +315,11 @@ def interface(debug=True, tempdir=None):
     @app.route('/kadmos_remove_obsolete_files', methods=['POST'])
     def kadmos_remove_obsolete_files():
         try:
-            for file in os.listdir(SESSIONS_CATALOG_FOLDER):
-                if "tmp_" not in file:
-                    os.remove(os.path.join(SESSIONS_CATALOG_FOLDER, file))
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+            for file in os.listdir(session_folder):
+                if "tmp_" not in file and os.path.splitext(file)[1] != '.json':  # JSON file should also be kept!
+                    os.remove(os.path.join(session_folder, file))
             return ""
 
         except Exception as e:
@@ -335,15 +339,17 @@ def interface(debug=True, tempdir=None):
             fileName = request.form['fileName']
             graphID = request.form['graphID']
             fileType = request.form['fileType']
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
 
             files = []
             graphFileName = TEMP_FILE+'_'+graphID+'.kdms'
             mpgFileName = TEMP_FILE+'_'+graphID+'_mpg.kdms'
-            if os.path.exists(os.path.join(SESSIONS_CATALOG_FOLDER, mpgFileName)):
-                graph = load(os.path.join(SESSIONS_CATALOG_FOLDER, graphFileName), file_check_critical=False)
-                mpg = load(os.path.join(SESSIONS_CATALOG_FOLDER, mpgFileName), file_check_critical=False)
+            if os.path.exists(os.path.join(session_folder, mpgFileName)):
+                graph = load(os.path.join(session_folder, graphFileName), file_check_critical=False)
+                mpg = load(os.path.join(session_folder, mpgFileName), file_check_critical=False)
             else:
-                graph = load(os.path.join(SESSIONS_CATALOG_FOLDER, graphFileName), file_check_critical=False)
+                graph = load(os.path.join(session_folder, graphFileName), file_check_critical=False)
                 mpg = None
 
             # Add problem function roles if they are not already existing
@@ -358,7 +364,8 @@ def interface(debug=True, tempdir=None):
 
             # Save as kdms file
             if fileType == "kdms":
-                graph.save(os.path.join(SESSIONS_CATALOG_FOLDER, fileName), file_type=fileType, graph_check_critical=False, mpg=mpg)
+                graph.save(os.path.join(session_folder, fileName), file_type=fileType, graph_check_critical=False,
+                           mpg=mpg)
                 file = fileName + ".kdms"
                 files.append(file)
                 if mpg is not None:
@@ -366,7 +373,7 @@ def interface(debug=True, tempdir=None):
                     files.append(mpgfile)
             # Save as CMDOWS file
             elif fileType == "cmdows":
-                graph.save(os.path.join(SESSIONS_CATALOG_FOLDER, fileName), file_type=fileType, graph_check_critical=False, mpg=mpg)
+                graph.save(os.path.join(session_folder, fileName), file_type=fileType, graph_check_critical=False, mpg=mpg)
                 file = fileName+".xml"
                 files.append(file)
             else:
@@ -390,12 +397,14 @@ def interface(debug=True, tempdir=None):
             graphID = request.form['graphID']
             newGraphName = request.form['newGraphName']
             newGraphID = request.form['newGraphID']
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
 
             function_order = None
             if request.form['currentOrder'].split(',') != '':
                 function_order = request.form['currentOrder'].split(',')
 
-            tmpDir = SESSIONS_CATALOG_FOLDER
+            tmpDir = session_folder
             graphFileName = TEMP_FILE + '_' + graphID + '.kdms'
             mpgFileName = TEMP_FILE + '_' + graphID + '_mpg.kdms'
             if os.path.exists(os.path.join(tmpDir, mpgFileName)):
@@ -408,7 +417,7 @@ def interface(debug=True, tempdir=None):
             newFileName = TEMP_FILE + '_' + newGraphID + '.kdms'
             graph.graph['name'] = newGraphName
             graph.graph['id'] = newGraphID
-            graph.save(os.path.join(SESSIONS_CATALOG_FOLDER, newFileName), file_type="kdms", graph_check_critical=False, mpg=mpg)
+            graph.save(os.path.join(session_folder, newFileName), file_type="kdms", graph_check_critical=False, mpg=mpg)
 
             newVistomsData = graph.vistoms_add_json(function_order=function_order, mpg=mpg, graph_id=newGraphID)
 
@@ -429,8 +438,10 @@ def interface(debug=True, tempdir=None):
         try:
             # get request form
             graphID = request.form['graphID']
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
 
-            tmpDir = SESSIONS_CATALOG_FOLDER
+            tmpDir = session_folder
             graphFileName = TEMP_FILE + '_' + graphID + '.kdms'
             backupGraphFileName = TEMP_FILE + '_' + graphID + '_backup.kdms'
             mpgFileName = TEMP_FILE + '_' + graphID + '_mpg.kdms'
@@ -459,10 +470,14 @@ def interface(debug=True, tempdir=None):
            :return: the graphs compressed as VISTOMS data
         """
         try:
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+
             # First of all, delete all graphs, that end with a _backup
-            delete_backup_graphs()
+            delete_backup_graphs(session_folder)
 
-            tmpDir = SESSIONS_CATALOG_FOLDER
+            tmpDir = session_folder
             newVIstomsDataArray = []
             file_list = os.listdir(tmpDir)
             if file_list:
@@ -483,14 +498,14 @@ def interface(debug=True, tempdir=None):
 
                         # Use function order for VISTOMS if it is available in the graph information
                         function_order = None
-                        if graph.graph_has_nested_attributes('problem_formulation', 'function_order') and mpg == None:
+                        if graph.graph_has_nested_attributes('problem_formulation', 'function_order') and mpg is None:
                             function_order = graph.graph['problem_formulation']['function_order']
 
-                        graph.save(os.path.join(SESSIONS_CATALOG_FOLDER, graphFileName), file_type="kdms",
+                        graph.save(os.path.join(session_folder, graphFileName), file_type="kdms",
                                    graph_check_critical=False, mpg=mpg)
 
-                        newVIstomsDataArray.append(graph.vistoms_add_json(graph_id=graphID, function_order=function_order, mpg=mpg))
-
+                        newVIstomsDataArray.append(graph.vistoms_add_json(graph_id=graphID,
+                                                                          function_order=function_order, mpg=mpg))
             return jsonify(newVIstomsDataArray)
 
         except Exception as e:
@@ -507,7 +522,11 @@ def interface(debug=True, tempdir=None):
             # get request form
             graphID = request.form['graphID']
 
-            tmpDir = SESSIONS_CATALOG_FOLDER
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+
+            tmpDir = session_folder
             graphFileName = TEMP_FILE + '_' + graphID + '.kdms'
             mpgFileName = TEMP_FILE + '_' + graphID + '_mpg.kdms'
             backupGraphFileName = TEMP_FILE + '_' + graphID + '_backup.kdms'
@@ -528,9 +547,9 @@ def interface(debug=True, tempdir=None):
                 backupMpg = None
 
             # Switch graph and backup graph (What used to be the backup graph is now the new graph and vice versa)
-            graph.save(os.path.join(SESSIONS_CATALOG_FOLDER, backupGraphFileName), file_type="kdms", graph_check_critical=False,
+            graph.save(os.path.join(session_folder, backupGraphFileName), file_type="kdms", graph_check_critical=False,
                        mpg=mpg)
-            backupGraph.save(os.path.join(SESSIONS_CATALOG_FOLDER, graphFileName), file_type="kdms", graph_check_critical=False,
+            backupGraph.save(os.path.join(session_folder, graphFileName), file_type="kdms", graph_check_critical=False,
                              mpg=backupMpg)
 
             # Get function_oder of the backup graph
@@ -538,22 +557,22 @@ def interface(debug=True, tempdir=None):
             if backupGraph.graph_has_nested_attributes('problem_formulation', 'function_order'):
                 function_order = backupGraph.graph['problem_formulation']['function_order']
 
-            newVistomsData = backupGraph.vistoms_add_json(function_order=function_order,  mpg=backupMpg, graph_id=graphID)
-
+            newVistomsData = backupGraph.vistoms_add_json(function_order=function_order,  mpg=backupMpg,
+                                                          graph_id=graphID)
             return newVistomsData
 
         except Exception as e:
             return "ERROR: " + e.message
             # Logs the error appropriately.
 
-    def savePreviousGraph(graph_id):
+    def savePreviousGraph(graph_id, session_id):
         """
             Function saves the last graph, so you can revert a graph change within VISTOMS
 
             :param graph: Initial fundamental problem graph (FPG) to start working on the MDAO architecture definition
             :return: New VISTOMS json data with initial FPG
         """
-        path = SESSIONS_CATALOG_FOLDER
+        path = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
         # current graph and mpg name
         graphFileName = TEMP_FILE + '_' + graph_id + '.kdms'
         mpgFileName = TEMP_FILE + '_' + graph_id + '_mpg.kdms'
@@ -566,18 +585,17 @@ def interface(debug=True, tempdir=None):
             backupMpgFileName = TEMP_FILE + '_' + graph_id + '_mpg_backup.kdms'
             copyfile(os.path.join(path, mpgFileName), os.path.join(path, backupMpgFileName))
 
-    def delete_backup_graphs():
+    def delete_backup_graphs(session_folder):
         """
             Function deletes all graphs that end with a _backup
         """
-        for file in os.listdir(SESSIONS_CATALOG_FOLDER):
+        for file in os.listdir(session_folder):
             if fnmatch.fnmatch(file, '*_backup*'):
-                os.remove(os.path.join(SESSIONS_CATALOG_FOLDER, file))
-    ########################################################################################################################
-
+                os.remove(os.path.join(session_folder, file))
 
+    ####################################################################################################################
     # Graph inspection functions
-    ########################################################################################################################
+    ####################################################################################################################
     @app.route('/kadmos_find_all_nodes', methods=['POST'])
     def kadmos_find_all_nodes():
         """
@@ -597,7 +615,11 @@ def interface(debug=True, tempdir=None):
             xPath_include = str(request.form['xPath_include']).split(', ')
             xPath_exclude = str(request.form['xPath_exclude']).split(', ')
 
-            path = SESSIONS_CATALOG_FOLDER
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+
+            path = session_folder
             graphFileName = TEMP_FILE + '_' + graphID + '.kdms'
             mpgFileName = TEMP_FILE + '_' + graphID + '_mpg.kdms'
             if os.path.exists(os.path.join(path, mpgFileName)):
@@ -618,7 +640,9 @@ def interface(debug=True, tempdir=None):
             if xPath_exclude == [""]:
                 xPath_exclude = None
 
-            allNodes = graph.find_all_nodes(category=category,subcategory=sub_category,attr_cond=attr_cond,attr_include=attr_include,attr_exclude=attr_exclude,xpath_include=xPath_include,xpath_exclude=xPath_exclude)
+            allNodes = graph.find_all_nodes(category=category, subcategory=sub_category, attr_cond=attr_cond,
+                                            attr_include=attr_include, attr_exclude=attr_exclude,
+                                            xpath_include=xPath_include, xpath_exclude=xPath_exclude)
 
             # allNodes_str = ', '.join(str(e) for e in allNodes)
             allNodes_str = json.dumps(allNodes)
@@ -639,10 +663,14 @@ def interface(debug=True, tempdir=None):
         try:
             # Get request form
             graphID = request.form['graphID']
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
 
-            path = SESSIONS_CATALOG_FOLDER
+            path = session_folder
             graphFileName = TEMP_FILE + '_' + graphID + '.kdms'
             mpgFileName = TEMP_FILE + '_' + graphID + '_mpg.kdms'
+            # TODO Benedikt: mpg is not used in this function, can it be removed, or should it be used?
             if os.path.exists(os.path.join(path, mpgFileName)):
                 graph = load(os.path.join(path, graphFileName), file_check_critical=False)
                 mpg = load(os.path.join(path, mpgFileName), file_check_critical=False)
@@ -652,8 +680,8 @@ def interface(debug=True, tempdir=None):
 
             check_result = graph._check_category_a()
 
-            if check_result[0] == True:
-                return ("Check successful!")
+            if check_result[0]:
+                return "Check successful!"
             else:
                 return "ERROR: Check was not successful. For further information, please consult the python log"
 
@@ -672,9 +700,14 @@ def interface(debug=True, tempdir=None):
             # Get request form
             graphID = request.form['graphID']
 
-            path = SESSIONS_CATALOG_FOLDER
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+
+            path = session_folder
             graphFileName = TEMP_FILE + '_' + graphID + '.kdms'
             mpgFileName = TEMP_FILE + '_' + graphID + '_mpg.kdms'
+            # TODO Benedikt: mpg is not used in this function, can it be removed, or should it be used?
             if os.path.exists(os.path.join(path, mpgFileName)):
                 graph = load(os.path.join(path, graphFileName), file_check_critical=False)
                 mpg = load(os.path.join(path, mpgFileName), file_check_critical=False)
@@ -684,8 +717,8 @@ def interface(debug=True, tempdir=None):
 
             check_result = graph._check_category_b()
 
-            if check_result[0] == True:
-                return ("Check successful!")
+            if check_result[0]:
+                return "Check successful!"
             else:
                 return "ERROR: Check was not successful. For further information, please consult the python log"
 
@@ -704,9 +737,14 @@ def interface(debug=True, tempdir=None):
             # Get request form
             graphID = request.form['graphID']
 
-            path = SESSIONS_CATALOG_FOLDER
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+
+            path = session_folder
             graphFileName = TEMP_FILE + '_' + graphID + '.kdms'
             mpgFileName = TEMP_FILE + '_' + graphID + '_mpg.kdms'
+            # TODO Benedikt: mpg is not used in this function, can it be removed, or should it be used?
             if os.path.exists(os.path.join(path, mpgFileName)):
                 graph = load(os.path.join(path, graphFileName), file_check_critical=False)
                 mpg = load(os.path.join(path, mpgFileName), file_check_critical=False)
@@ -716,18 +754,18 @@ def interface(debug=True, tempdir=None):
 
             check_result = graph._check_category_c()
 
-            if check_result[0] == True:
-                return ("Check successful!")
+            if check_result[0]:
+                return "Check successful!"
             else:
                 return "ERROR: Check was not successful. For further information, please consult the python log"
 
         except Exception as e:
             return "ERROR: " + e.message
             # Logs the error appropriately.
-    ########################################################################################################################
 
+    ####################################################################################################################
     # Upload custom kadmos script
-    ########################################################################################################################
+    ####################################################################################################################
     @app.route('/kadmos_run_custom_script', methods=['POST'])
     def kadmos_run_custom_script():
         """
@@ -740,6 +778,9 @@ def interface(debug=True, tempdir=None):
         try:
             # Get request form
             graphID = request.form['graphID']
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
             uploaded_files = request.files.getlist("file[]")
 
             script_file = []
@@ -750,9 +791,9 @@ def interface(debug=True, tempdir=None):
                 script_file = aFile
 
             # Save previous graph as backup before making the changes
-            savePreviousGraph(graphID)
+            savePreviousGraph(graphID, session_id)
 
-            path = SESSIONS_CATALOG_FOLDER
+            path = session_folder
             graphFileName = TEMP_FILE + '_' + graphID + '.kdms'
             mpgFileName = TEMP_FILE + '_' + graphID + '_mpg.kdms'
             if os.path.exists(os.path.join(path, mpgFileName)):
@@ -763,8 +804,8 @@ def interface(debug=True, tempdir=None):
                 mpg = None
 
             # save kadmos script in temp folder
-            script_file.save(os.path.join(SESSIONS_CATALOG_FOLDER, script_file.filename))
-            kadmos_file_path = os.path.join(SESSIONS_CATALOG_FOLDER, script_file.filename)
+            script_file.save(os.path.join(session_folder, script_file.filename))
+            kadmos_file_path = os.path.join(session_folder, script_file.filename)
 
             # execute script and return graph data (graph, mpg)
             import imp
@@ -773,7 +814,7 @@ def interface(debug=True, tempdir=None):
 
             # Get function order for VISTOMS in case of FPG
             function_order = None
-            if mpg == None:
+            if mpg is None:
                 # Get function_oder of the graph after the script has done the manipulations
                 if graph.graph_has_nested_attributes('problem_formulation', 'function_order'):
                     function_order = graph.graph['problem_formulation']['function_order']
@@ -781,18 +822,17 @@ def interface(debug=True, tempdir=None):
             # Add modified graph to VISTOMS
             newVistomsData = graph.vistoms_add_json(function_order=function_order, graph_id=graphID, mpg=mpg)
             # Save the graph in temp/tmp.kdms
-            graph.save(os.path.join(SESSIONS_CATALOG_FOLDER, TEMP_FILE + '_' + graphID + '.kdms'), file_type='kdms',
+            graph.save(os.path.join(session_folder, TEMP_FILE + '_' + graphID + '.kdms'), file_type='kdms',
                        graph_check_critical=False, mpg=mpg)
             return newVistomsData
 
         except Exception as e:
             return "ERROR: " + e.message
             # Logs the error appropriately.
-    ########################################################################################################################
-
 
+    ####################################################################################################################
     # FPG manipulation functions
-    ########################################################################################################################
+    ####################################################################################################################
     @app.route('/kadmos_start_defining_MDO_problem', methods=['POST'])
     def kadmos_start_defining_MDO_problem():
         """
@@ -808,24 +848,29 @@ def interface(debug=True, tempdir=None):
             newGraphID = request.form['newGraphID']
             newGraphName = request.form['newGraphName']
 
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+
             newFileName = TEMP_FILE + '_' + newGraphID + '.kdms'
 
-            path = SESSIONS_CATALOG_FOLDER
+            path = session_folder
             graphFileName = TEMP_FILE+'_'+graphID+'.kdms'
             mpgFileName = TEMP_FILE+'_'+graphID+'_mpg.kdms'
             if os.path.exists(os.path.join(path, mpgFileName)):
-                return ("ERROR: Graph is already an MDPG! FPG Cannot be initialized again!")
+                return "ERROR: Graph is already an MDPG! FPG Cannot be initialized again!"
             else:
                 mpg = None
 
                 graph = load(os.path.join(path, graphFileName), file_check_critical=False)
 
                 if isinstance(graph, FundamentalProblemGraph):
-                    return("ERROR: Graph is already an FPG and cannot be initialized again!")
+                    return "ERROR: Graph is already an FPG and cannot be initialized again!"
                 fpg_initial = graph.deepcopy_as(FundamentalProblemGraph)
 
                 fpg_initial.graph['name'] = newGraphName
-                fpg_initial.graph['description'] = 'Fundamental problem graph to solve the "' + graph.graph['name'] + '".'
+                fpg_initial.graph['description'] = 'Fundamental problem graph to solve the "' + graph.graph['name'] \
+                                                   + '".'
                 fpg_initial.graph['problem_formulation'] = dict()
                 fpg_initial.graph['problem_formulation']['function_order'] = functionOrder
                 fpg_initial.graph['problem_formulation']['mdao_architecture'] = "None"
@@ -833,8 +878,8 @@ def interface(debug=True, tempdir=None):
                 # Add the graph with the updated function order to VISTOMS
                 newVistomsData = fpg_initial.vistoms_add_json(graph_id=newGraphID, mpg=mpg)
                 # Save the graph in temp/tmp.kdms
-                fpg_initial.save(os.path.join(SESSIONS_CATALOG_FOLDER, newFileName), file_type="kdms", graph_check_critical=False, mpg=mpg)
-
+                fpg_initial.save(os.path.join(session_folder, newFileName), file_type="kdms",
+                                 graph_check_critical=False, mpg=mpg)
                 return newVistomsData
 
         except Exception as e:
@@ -857,23 +902,25 @@ def interface(debug=True, tempdir=None):
             nodeName = request.form['nodeName']
             metadata_str = request.form['metadata_str']
 
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+
             # read json data
             metadata_py = json.loads(metadata_str)
 
             # Save previous graph as backup before making the changes
-            savePreviousGraph(graphID)
+            savePreviousGraph(graphID, session_id)
 
-            path = SESSIONS_CATALOG_FOLDER
+            path = session_folder
             graphFileName = TEMP_FILE+'_'+graphID+'.kdms'
             mpgFileName = TEMP_FILE+'_'+graphID+'_mpg.kdms'
             if os.path.exists(os.path.join(path, mpgFileName)):
-                return "ERROR: You cannot add metadata to a design competence in an MPG! Please go back to the RCG to do so."
+                return "ERROR: You cannot add metadata to a design competence in an MPG! Please go back to the RCG " \
+                       "to do so."
             else:
                 graph = load(os.path.join(path, graphFileName), file_check_critical=False)
                 mpg = None
-
-                print metadata_py
-
                 graph.add_dc_general_info(nodeName, description=metadata_py['general_info']['description'],
                                           status=metadata_py['general_info']['status'],
                                           owner_uid=metadata_py['general_info']['owner_uid'],
@@ -901,10 +948,11 @@ def interface(debug=True, tempdir=None):
                 # Add the graph with the updated function order to VISTOMS
                 newVistomsData = graph.vistoms_add_json(function_order=function_order, graph_id=graphID, mpg=mpg)
                 # Use function order for VISTOMS if it is available in the graph information
-                if graph.graph_has_nested_attributes('problem_formulation', 'function_order') and mpg == None:
+                if graph.graph_has_nested_attributes('problem_formulation', 'function_order') and mpg is None:
                     graph.graph['problem_formulation']['function_order'] = function_order
                 # Save the graph in temp/tmp.kdms
-                graph.save(os.path.join(SESSIONS_CATALOG_FOLDER, TEMP_FILE + '_' + graphID + '.kdms'), file_type='kdms', graph_check_critical=False, mpg=mpg)
+                graph.save(os.path.join(session_folder, TEMP_FILE + '_' + graphID + '.kdms'), file_type='kdms',
+                           graph_check_critical=False, mpg=mpg)
 
                 return newVistomsData
 
@@ -927,6 +975,10 @@ def interface(debug=True, tempdir=None):
                 function_order = request.form['currentOrder'].split(',')
             form_data_str = request.form['form_data']
 
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+
             # convert stringified data into python objects/arrays/.. with json.loads function
             form_data_py = json.loads(form_data_str)
 
@@ -939,10 +991,10 @@ def interface(debug=True, tempdir=None):
             language = form_data_py['language']
 
             # Save previous graph as backup before making the changes to the graph
-            savePreviousGraph(graphID)
+            savePreviousGraph(graphID, session_id)
 
             # Load the current graph from the temporary folder
-            path = SESSIONS_CATALOG_FOLDER
+            path = session_folder
             graphFileName = TEMP_FILE+'_'+graphID+'.kdms'
             mpgFileName = TEMP_FILE+'_'+graphID+'_mpg.kdms'
             if os.path.exists(os.path.join(path, mpgFileName)):
@@ -970,10 +1022,10 @@ def interface(debug=True, tempdir=None):
                 # The graph with the added mathematical function is now saved as json data for vistoms
                 newVistomsData = graph.vistoms_add_json(function_order=function_order, graph_id=graphID, mpg=mpg)
                 # Use function order for VISTOMS if it is available in the graph information
-                if graph.graph_has_nested_attributes('problem_formulation', 'function_order') and mpg == None:
+                if graph.graph_has_nested_attributes('problem_formulation', 'function_order') and mpg is None:
                     graph.graph['problem_formulation']['function_order'] = function_order
                 # Save the graph in temp/tmp.kdms
-                graph.save(os.path.join(SESSIONS_CATALOG_FOLDER, TEMP_FILE + '_' + graphID + '.kdms'), file_type='kdms',
+                graph.save(os.path.join(session_folder, TEMP_FILE + '_' + graphID + '.kdms'), file_type='kdms',
                            graph_check_critical=False, mpg=mpg)
 
                 return newVistomsData
@@ -996,15 +1048,18 @@ def interface(debug=True, tempdir=None):
             input_xml = request.files['input_xml']
             output_xml = request.files['output_xml']
 
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
 
             # Save previous graph as backup before making the changes
-            savePreviousGraph(graphID)
+            savePreviousGraph(graphID, session_id)
 
-            path = SESSIONS_CATALOG_FOLDER
+            path = session_folder
             graphFileName = TEMP_FILE+'_'+graphID+'.kdms'
             mpgFileName = TEMP_FILE+'_'+graphID+'_mpg.kdms'
             if os.path.exists(os.path.join(path, mpgFileName)):
-                return ("ERROR: You cannot add a design competence to an MPG! Please go back to the RCG to do so.")
+                return "ERROR: You cannot add a design competence to an MPG! Please go back to the RCG to do so."
             else:
                 graph = load(os.path.join(path, graphFileName), file_check_critical=False)
                 mpg = None
@@ -1012,7 +1067,7 @@ def interface(debug=True, tempdir=None):
                 # Here the dc cmdows file is loaded
                 # Save the template cmdows file in the tmp folder
                 cmdows_template = os.path.join('templates', 'cmdows_template.xml')
-                cmdows_file = os.path.join(SESSIONS_CATALOG_FOLDER, 'cmdows_template.xml')
+                cmdows_file = os.path.join(session_folder, 'cmdows_template.xml')
                 # Write the new competence to the CMDOWS template xml file
                 tree = ET.parse(cmdows_template)
                 root = tree.getroot()
@@ -1023,8 +1078,8 @@ def interface(debug=True, tempdir=None):
                 tree.write(cmdows_file)
 
                 # Copy the uploaded input/outut files to the tmp folder
-                input_xml_file = os.path.join(SESSIONS_CATALOG_FOLDER, function_node + '-input.xml')
-                output_xml_file = os.path.join(SESSIONS_CATALOG_FOLDER, function_node + '-output.xml')
+                input_xml_file = os.path.join(session_folder, function_node + '-input.xml')
+                output_xml_file = os.path.join(session_folder, function_node + '-output.xml')
                 input_xml.save(input_xml_file)
                 output_xml.save(output_xml_file)
 
@@ -1052,7 +1107,7 @@ def interface(debug=True, tempdir=None):
                 newVistomsData = new_graph.vistoms_add_json(graph_id=graphID, mpg=mpg)
 
                 # Save the graph in temp/tmp.kdms
-                new_graph.save(os.path.join(SESSIONS_CATALOG_FOLDER, TEMP_FILE + '_' + graphID + '.kdms'), file_type='kdms',
+                new_graph.save(os.path.join(session_folder, TEMP_FILE + '_' + graphID + '.kdms'), file_type='kdms',
                                graph_check_critical=False, mpg=mpg)
 
                 return newVistomsData
@@ -1075,14 +1130,18 @@ def interface(debug=True, tempdir=None):
             if request.form['currentOrder'].split(',') != '':
                 function_order = request.form['currentOrder'].split(',')
 
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+
             # Save previous graph as backup before making the changes
-            savePreviousGraph(graphID)
+            savePreviousGraph(graphID, session_id)
 
-            path = SESSIONS_CATALOG_FOLDER
+            path = session_folder
             graphFileName = TEMP_FILE+'_'+graphID+'.kdms'
             mpgFileName = TEMP_FILE+'_'+graphID+'_mpg.kdms'
             if os.path.exists(os.path.join(path, mpgFileName)):
-                return ("ERROR: You cannot change organizational info on an MPG! Please go back to the RCG to do so.")
+                return "ERROR: You cannot change organizational info on an MPG! Please go back to the RCG to do so."
             else:
                 graph = load(os.path.join(path, graphFileName), file_check_critical=False)
                 mpg = None
@@ -1094,7 +1153,7 @@ def interface(debug=True, tempdir=None):
                 newVistomsData = graph.vistoms_add_json(graph_id=graphID, mpg=mpg, function_order=function_order)
 
                 # Save the graph in temp/tmp.kdms
-                graph.save(os.path.join(SESSIONS_CATALOG_FOLDER, TEMP_FILE + '_' + graphID + '.kdms'), file_type='kdms',
+                graph.save(os.path.join(session_folder, TEMP_FILE + '_' + graphID + '.kdms'), file_type='kdms',
                            graph_check_critical=False, mpg=mpg)
 
                 return newVistomsData
@@ -1120,14 +1179,19 @@ def interface(debug=True, tempdir=None):
                 function_order = request.form['currentOrder'].split(',')
             newPos = int(request.form['newPos'])
 
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+
             # Save previous graph as backup before making the changes
-            savePreviousGraph(graphID)
+            savePreviousGraph(graphID, session_id)
 
-            path = SESSIONS_CATALOG_FOLDER
+            path = session_folder
             graphFileName = TEMP_FILE+'_'+graphID+'.kdms'
             mpgFileName = TEMP_FILE+'_'+graphID+'_mpg.kdms'
             if os.path.exists(os.path.join(path, mpgFileName)):
-                return ("ERROR: You cannot change a competence's position on an existing MPG! Please go back to the FPG or RCG to do so.")
+                return "ERROR: You cannot change a competence's position on an existing MPG! Please go back to the " \
+                       "FPG or RCG to do so."
             else:
                 graph = load(os.path.join(path, graphFileName), file_check_critical=False)
                 mpg = None
@@ -1145,7 +1209,7 @@ def interface(debug=True, tempdir=None):
                 # Add the graph with the updated function order to VISTOMS
                 newVistomsData = graph.vistoms_add_json(function_order=function_order, graph_id=graphID, mpg=mpg)
                 # Save the graph in temp/tmp.kdms
-                graph.save(os.path.join(SESSIONS_CATALOG_FOLDER, TEMP_FILE + '_' + graphID + '.kdms'), file_type='kdms',
+                graph.save(os.path.join(session_folder, TEMP_FILE + '_' + graphID + '.kdms'), file_type='kdms',
                            graph_check_critical=False, mpg=mpg)
                 return newVistomsData
 
@@ -1168,14 +1232,19 @@ def interface(debug=True, tempdir=None):
             if request.form['currentOrder'].split(',') != '':
                 function_order = request.form['currentOrder'].split(',')
 
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+
             # Save previous graph as backup before making the changes
-            savePreviousGraph(graphID)
+            savePreviousGraph(graphID, session_id)
 
-            path = SESSIONS_CATALOG_FOLDER
+            path = session_folder
             graphFileName = TEMP_FILE+'_'+graphID+'.kdms'
             mpgFileName = TEMP_FILE+'_'+graphID+'_mpg.kdms'
             if os.path.exists(os.path.join(path, mpgFileName)):
-                return ("ERROR: You cannot remove a competence from an existing MPG! Please go back to the FPG or RCG to do so.")
+                return "ERROR: You cannot remove a competence from an existing MPG! Please go back to the FPG or RCG" \
+                       " to do so."
             else:
                 graph = load(os.path.join(path, graphFileName), file_check_critical=False)
                 mpg = None
@@ -1188,10 +1257,11 @@ def interface(debug=True, tempdir=None):
                 # Add the graph with the updated function order to VISTOMS
                 newVistomsData = graph.vistoms_add_json(function_order=function_order, graph_id=graphID, mpg=mpg)
                 # Use function order for VISTOMS if it is available in the graph information
-                if graph.graph_has_nested_attributes('problem_formulation', 'function_order') and mpg == None:
+                if graph.graph_has_nested_attributes('problem_formulation', 'function_order') and mpg is None:
                     graph.graph['problem_formulation']['function_order'] = function_order
                 # Save the graph in temp/tmp.kdms
-                graph.save(os.path.join(SESSIONS_CATALOG_FOLDER, TEMP_FILE + '_' + graphID + '.kdms'), file_type='kdms', graph_check_critical=False, mpg=mpg)
+                graph.save(os.path.join(session_folder, TEMP_FILE + '_' + graphID + '.kdms'), file_type='kdms',
+                           graph_check_critical=False, mpg=mpg)
 
                 return newVistomsData
 
@@ -1216,10 +1286,14 @@ def interface(debug=True, tempdir=None):
             if request.form['currentOrder'].split(',') != '':
                 function_order = request.form['currentOrder'].split(',')
 
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+
             # Save previous graph as backup before making the changes
-            savePreviousGraph(graphID)
+            savePreviousGraph(graphID, session_id)
 
-            path = SESSIONS_CATALOG_FOLDER
+            path = session_folder
             graphFileName = TEMP_FILE+'_'+graphID+'.kdms'
             mpgFileName = TEMP_FILE+'_'+graphID+'_mpg.kdms'
             if os.path.exists(os.path.join(path, mpgFileName)):
@@ -1234,7 +1308,8 @@ def interface(debug=True, tempdir=None):
             # Add the graph with the updated function order to VISTOMS
             newVistomsData = graph.vistoms_add_json(function_order=function_order, graph_id=graphID, mpg=mpg)
             # Save the graph in temp/tmp.kdms
-            graph.save(os.path.join(SESSIONS_CATALOG_FOLDER, TEMP_FILE + '_' + graphID + '.kdms'), file_type='kdms', graph_check_critical=False, mpg=mpg)
+            graph.save(os.path.join(session_folder, TEMP_FILE + '_' + graphID + '.kdms'), file_type='kdms',
+                       graph_check_critical=False, mpg=mpg)
 
             return newVistomsData
 
@@ -1258,14 +1333,19 @@ def interface(debug=True, tempdir=None):
             if request.form['currentOrder'].split(',') != '':
                 function_order = request.form['currentOrder'].split(',')
 
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+
             # Save previous graph as backup before making the changes
-            savePreviousGraph(graphID)
+            savePreviousGraph(graphID, session_id)
 
-            path = SESSIONS_CATALOG_FOLDER
+            path = session_folder
             graphFileName = TEMP_FILE + '_' + graphID + '.kdms'
             mpgFileName = TEMP_FILE + '_' + graphID + '_mpg.kdms'
             if os.path.exists(os.path.join(path, mpgFileName)):
-                return ("ERROR: You cannot remove a competence from an existing MPG! Please go back to the FPG or RCG to do so.")
+                return "ERROR: You cannot remove a competence from an existing MPG! Please go back to the FPG or RCG " \
+                       "to do so."
             else:
                 graph = load(os.path.join(path, graphFileName), file_check_critical=False)
                 mpg = None
@@ -1282,7 +1362,7 @@ def interface(debug=True, tempdir=None):
                 # Add the graph with the updated function order to VISTOMS
                 newVistomsData = fpg.vistoms_add_json(function_order=function_order, graph_id=graphID, mpg=mpg)
                 # Save the graph in temp/tmp.kdms
-                fpg.save(os.path.join(SESSIONS_CATALOG_FOLDER, TEMP_FILE + '_' + graphID + '.kdms'),
+                fpg.save(os.path.join(session_folder, TEMP_FILE + '_' + graphID + '.kdms'),
                          file_type='kdms', graph_check_critical=False, mpg=mpg)
                 return newVistomsData
 
@@ -1306,19 +1386,22 @@ def interface(debug=True, tempdir=None):
                 function_order = request.form['currentOrder'].split(',')
             nodeList = request.form['nodeList'].split(',')
 
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+
             # Save previous graph as backup before making the changes
-            savePreviousGraph(graphID)
+            savePreviousGraph(graphID, session_id)
 
-            path = SESSIONS_CATALOG_FOLDER
+            path = session_folder
             graphFileName = TEMP_FILE + '_' + graphID + '.kdms'
             mpgFileName = TEMP_FILE + '_' + graphID + '_mpg.kdms'
             if os.path.exists(os.path.join(path, mpgFileName)):
-                return ("ERROR: You cannot merge comeptences on an existing MPG! Please go back to the FPG or RCG to do so.")
+                return "ERROR: You cannot merge comeptences on an existing MPG! Please go back to the FPG or RCG to " \
+                       "do so."
             else:
                 graph = load(os.path.join(path, graphFileName), file_check_critical=False)
                 mpg = None
-
-
                 new_node = '-'.join(nodeList) + '--seq'
 
                 if isinstance(graph, FundamentalProblemGraph):
@@ -1334,7 +1417,7 @@ def interface(debug=True, tempdir=None):
                 # Add the graph with the updated function order to VISTOMS
                 newVistomsData = fpg.vistoms_add_json(function_order=function_order, graph_id=graphID, mpg=mpg)
                 # Save the graph in temp/tmp.kdms
-                fpg.save(os.path.join(SESSIONS_CATALOG_FOLDER, TEMP_FILE + '_' + graphID + '.kdms'),
+                fpg.save(os.path.join(session_folder, TEMP_FILE + '_' + graphID + '.kdms'),
                          file_type='kdms', graph_check_critical=False, mpg=mpg)
                 return newVistomsData
 
@@ -1358,14 +1441,19 @@ def interface(debug=True, tempdir=None):
                 function_order = request.form['currentOrder'].split(',')
             nodeList = request.form['nodeList'].split(',')
 
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+
             # Save previous graph as backup before making the changes
-            savePreviousGraph(graphID)
+            savePreviousGraph(graphID, session_id)
 
-            path = SESSIONS_CATALOG_FOLDER
+            path = session_folder
             graphFileName = TEMP_FILE + '_' + graphID + '.kdms'
             mpgFileName = TEMP_FILE + '_' + graphID + '_mpg.kdms'
             if os.path.exists(os.path.join(path, mpgFileName)):
-                return ("ERROR: You cannot merge comeptences on an existing MPG! Please go back to the FPG or RCG to do so.")
+                return "ERROR: You cannot merge comeptences on an existing MPG! Please go back to the FPG or RCG to " \
+                       "do so."
             else:
                 graph = load(os.path.join(path, graphFileName), file_check_critical=False)
                 mpg = None
@@ -1386,7 +1474,7 @@ def interface(debug=True, tempdir=None):
                 # Add the graph with the updated function order to VISTOMS
                 newVistomsData = fpg.vistoms_add_json(function_order=function_order, graph_id=graphID, mpg=mpg)
                 # Save the graph in temp/tmp.kdms
-                fpg.save(os.path.join(SESSIONS_CATALOG_FOLDER, TEMP_FILE + '_' + graphID + '.kdms'),
+                fpg.save(os.path.join(session_folder, TEMP_FILE + '_' + graphID + '.kdms'),
                          file_type='kdms', graph_check_critical=False, mpg=mpg)
                 return newVistomsData
 
@@ -1410,14 +1498,19 @@ def interface(debug=True, tempdir=None):
                 function_order = request.form['currentOrder'].split(',')
             nodeList = request.form['nodeList'].split(',')
 
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+
             # Save previous graph as backup before making the changes
-            savePreviousGraph(graphID)
+            savePreviousGraph(graphID, session_id)
 
-            path = SESSIONS_CATALOG_FOLDER
+            path = session_folder
             graphFileName = TEMP_FILE + '_' + graphID + '.kdms'
             mpgFileName = TEMP_FILE + '_' + graphID + '_mpg.kdms'
             if os.path.exists(os.path.join(path, mpgFileName)):
-                return ("ERROR: You cannot merge comeptences on an existing MPG! Please go back to the FPG or RCG to do so.")
+                return "ERROR: You cannot merge comeptences on an existing MPG! Please go back to the FPG or RCG to " \
+                       "do so."
             else:
                 graph = load(os.path.join(path, graphFileName), file_check_critical=False)
                 mpg = None
@@ -1442,7 +1535,7 @@ def interface(debug=True, tempdir=None):
                 # Add the graph with the updated function order to VISTOMS
                 newVistomsData = fpg.vistoms_add_json(function_order=function_order, graph_id=graphID, mpg=mpg)
                 # Save the graph in temp/tmp.kdms
-                fpg.save(os.path.join(SESSIONS_CATALOG_FOLDER, TEMP_FILE + '_' + graphID + '.kdms'),
+                fpg.save(os.path.join(session_folder, TEMP_FILE + '_' + graphID + '.kdms'),
                          file_type='kdms', graph_check_critical=False, mpg=mpg)
                 return newVistomsData
 
@@ -1466,14 +1559,19 @@ def interface(debug=True, tempdir=None):
             if request.form['currentOrder'].split(',') != '':
                 function_order = request.form['currentOrder'].split(',')
 
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+
             # Save previous graph as backup before making the changes
-            savePreviousGraph(graphID)
+            savePreviousGraph(graphID, session_id)
 
-            path = SESSIONS_CATALOG_FOLDER
+            path = session_folder
             graphFileName = TEMP_FILE + '_' + graphID + '.kdms'
             mpgFileName = TEMP_FILE + '_' + graphID + '_mpg.kdms'
             if os.path.exists(os.path.join(path, mpgFileName)):
-                return ("ERROR: You cannot merge comeptences on an existing MPG! Please go back to the FPG or RCG to do so.")
+                return "ERROR: You cannot merge comeptences on an existing MPG! Please go back to the FPG or RCG to " \
+                       "do so."
             else:
                 graph = load(os.path.join(path, graphFileName), file_check_critical=False)
                 mpg = None
@@ -1492,7 +1590,7 @@ def interface(debug=True, tempdir=None):
                 # Add the graph with the updated function order to VISTOMS
                 newVistomsData = fpg.vistoms_add_json(function_order=function_order, graph_id=graphID, mpg=mpg)
                 # Save the graph in temp/tmp.kdms
-                fpg.save(os.path.join(SESSIONS_CATALOG_FOLDER, TEMP_FILE + '_' + graphID + '.kdms'),
+                fpg.save(os.path.join(session_folder, TEMP_FILE + '_' + graphID + '.kdms'),
                          file_type='kdms', graph_check_critical=False, mpg=mpg)
                 return newVistomsData
 
@@ -1513,14 +1611,19 @@ def interface(debug=True, tempdir=None):
             graphID = request.form['graphID']
             method = request.form['sortingMethod']
 
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+
             # Save previous graph as backup before making the changes
-            savePreviousGraph(graphID)
+            savePreviousGraph(graphID, session_id)
 
-            path = SESSIONS_CATALOG_FOLDER
+            path = session_folder
             graphFileName = TEMP_FILE + '_' + graphID + '.kdms'
             mpgFileName = TEMP_FILE + '_' + graphID + '_mpg.kdms'
             if os.path.exists(os.path.join(path, mpgFileName)):
-                return ("ERROR: You cannot merge comeptences on an existing MPG! Please go back to the FPG or RCG to do so.")
+                return "ERROR: You cannot merge comeptences on an existing MPG! Please go back to the FPG or RCG to " \
+                       "do so."
             else:
                 graph = load(os.path.join(path, graphFileName), file_check_critical=False)
                 mpg = None
@@ -1538,7 +1641,7 @@ def interface(debug=True, tempdir=None):
                     fpg.add_function_problem_roles()
 
                 # Save the graph in temp/tmp.kdms
-                fpg.save(os.path.join(SESSIONS_CATALOG_FOLDER, TEMP_FILE + '_' + graphID + '.kdms'),
+                fpg.save(os.path.join(session_folder, TEMP_FILE + '_' + graphID + '.kdms'),
                          file_type='kdms', graph_check_critical=False, mpg=mpg)
 
                 # Add the graph with the updated function order to VISTOMS
@@ -1564,14 +1667,18 @@ def interface(debug=True, tempdir=None):
             if request.form['currentOrder'].split(',') != '':
                 function_order = request.form['currentOrder'].split(',')
 
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+
             # Save previous graph as backup before making the changes
-            savePreviousGraph(graphID)
+            savePreviousGraph(graphID, session_id)
 
-            path = SESSIONS_CATALOG_FOLDER
+            path = session_folder
             graphFileName = TEMP_FILE + '_' + graphID + '.kdms'
             mpgFileName = TEMP_FILE + '_' + graphID + '_mpg.kdms'
             if os.path.exists(os.path.join(path, mpgFileName)):
-                return ("ERROR: You cannot do that on an existing MPG! Please go back to the FPG or RCG to do so.")
+                return "ERROR: You cannot do that on an existing MPG! Please go back to the FPG or RCG to do so."
             else:
                 graph = load(os.path.join(path, graphFileName), file_check_critical=False)
                 mpg = None
@@ -1583,15 +1690,15 @@ def interface(debug=True, tempdir=None):
 
                 fpg.graph['problem_formulation']['function_order'] = function_order
 
-                # Function to check the graph for collisions and holes. Collisions are solved based on the function order and holes
-                # will simply be removed.
+                # Function to check the graph for collisions and holes. Collisions are solved based on the function
+                # order and holes will simply be removed.
                 fpg.make_all_variables_valid()
 
 
                 # Add the graph with the updated function order to VISTOMS
                 newVistomsData = fpg.vistoms_add_json(function_order=function_order, graph_id=graphID, mpg=mpg)
                 # Save the graph in temp/tmp.kdms
-                fpg.save(os.path.join(SESSIONS_CATALOG_FOLDER, TEMP_FILE + '_' + graphID + '.kdms'),
+                fpg.save(os.path.join(session_folder, TEMP_FILE + '_' + graphID + '.kdms'),
                          file_type='kdms', graph_check_critical=False, mpg=mpg)
                 return newVistomsData
 
@@ -1613,14 +1720,18 @@ def interface(debug=True, tempdir=None):
             if request.form['currentOrder'].split(',') != '':
                 function_order = request.form['currentOrder'].split(',')
 
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+
             # Save previous graph as backup before making the changes
-            savePreviousGraph(graphID)
+            savePreviousGraph(graphID, session_id)
 
-            path = SESSIONS_CATALOG_FOLDER
+            path = session_folder
             graphFileName = TEMP_FILE + '_' + graphID + '.kdms'
             mpgFileName = TEMP_FILE + '_' + graphID + '_mpg.kdms'
             if os.path.exists(os.path.join(path, mpgFileName)):
-                return ("ERROR: You cannot do that on an existing MPG! Please go back to the FPG or RCG to do so.")
+                return "ERROR: You cannot do that on an existing MPG! Please go back to the FPG or RCG to do so."
             else:
                 graph = load(os.path.join(path, graphFileName), file_check_critical=False)
                 mpg = None
@@ -1638,7 +1749,7 @@ def interface(debug=True, tempdir=None):
                 # Add the graph with the updated function order to VISTOMS
                 newVistomsData = fpg.vistoms_add_json(function_order=function_order, graph_id=graphID, mpg=mpg)
                 # Save the graph in temp/tmp.kdms
-                fpg.save(os.path.join(SESSIONS_CATALOG_FOLDER, TEMP_FILE + '_' + graphID + '.kdms'),
+                fpg.save(os.path.join(session_folder, TEMP_FILE + '_' + graphID + '.kdms'),
                          file_type='kdms', graph_check_critical=False, mpg=mpg)
                 return newVistomsData
 
@@ -1649,9 +1760,10 @@ def interface(debug=True, tempdir=None):
     @app.route('/kadmos_mark_variable', methods=['POST'])
     def kadmos_mark_variable():
         """
-            Function to mark a variable as "special variable" (constraint, objective, design variable, quantity of interest)
+            Function to mark a variable as "special variable" (constraint, objective, design variable, quantity of
+            interest)
             :param xPath: xPath of the variable in the XML schema
-            :param variableType: type of the variable it shall be marked as (constraint, objective, design variable, quantity of interest)
+            :param variableType: type of the variable it shall be marked as
             :return: VISTOMS json data with graph information
         """
         try:
@@ -1664,14 +1776,18 @@ def interface(debug=True, tempdir=None):
             # read json data
             variableData_py = json.loads(variableData_str)
 
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+
             # Save previous graph as backup before making the changes
-            savePreviousGraph(graphID)
+            savePreviousGraph(graphID, session_id)
 
-            path = SESSIONS_CATALOG_FOLDER
+            path = session_folder
             graphFileName =  TEMP_FILE+'_'+graphID+'.kdms'
             mpgFileName =  TEMP_FILE+'_'+graphID+'_mpg.kdms'
             if os.path.exists(os.path.join(path, mpgFileName)):
-                return ('ERROR: This function can only be performed on an FPG!')
+                return 'ERROR: This function can only be performed on an FPG!'
             else:
                 graph = load(os.path.join(path, graphFileName), file_check_critical=False)
                 mpg = None
@@ -1683,20 +1799,23 @@ def interface(debug=True, tempdir=None):
             for data in variableData_py:
                 if data['variableType'] == 'designVariable':
                     fpg.mark_as_design_variable(data['xPath'], nominal_value=float(data['nominalValue']),
-                                                upper_bound=float(data['upperBound']), lower_bound=float(data['lowerBound']))
+                                                upper_bound=float(data['upperBound']),
+                                                lower_bound=float(data['lowerBound']))
                 elif data['variableType'] == 'objective':
                     fpg.mark_as_objective(data['xPath'])
                 elif data['variableType'] == 'constraint':
-                    fpg.mark_as_constraint(data['xPath'], reference_value=float(data['nominalValue']), operator=data['operator'])
+                    fpg.mark_as_constraint(data['xPath'], reference_value=float(data['nominalValue']),
+                                           operator=data['operator'])
                 elif data['variableType'] == 'quantityOfInterest':
                     fpg.mark_as_qois([data['xPath']])
                 else:
-                    return ("ERROR: Something went wrong in KADMOS!")
+                    return "ERROR: Something went wrong in KADMOS!"
 
             # Add the graph with the updated function order to VISTOMS
             newVistomsData = fpg.vistoms_add_json(function_order=function_order, graph_id=graphID, mpg=mpg)
             # Save the graph in temp/tmp.kdms
-            fpg.save(os.path.join(SESSIONS_CATALOG_FOLDER, TEMP_FILE + '_' + graphID + '.kdms'), file_type='kdms', graph_check_critical=False, mpg=mpg)
+            fpg.save(os.path.join(session_folder, TEMP_FILE + '_' + graphID + '.kdms'), file_type='kdms',
+                     graph_check_critical=False, mpg=mpg)
 
             return newVistomsData
 
@@ -1719,14 +1838,18 @@ def interface(debug=True, tempdir=None):
                 function_order = request.form['currentOrder'].split(',')
             xPath = request.form['xPath']
 
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+
             # Save previous graph as backup before making the changes
-            savePreviousGraph(graphID)
+            savePreviousGraph(graphID, session_id)
 
-            path = SESSIONS_CATALOG_FOLDER
+            path = session_folder
             graphFileName =  TEMP_FILE+'_'+graphID+'.kdms'
             mpgFileName =  TEMP_FILE+'_'+graphID+'_mpg.kdms'
             if os.path.exists(os.path.join(path, mpgFileName)):
-                return ('ERROR: This function can only be performed on an FPG!')
+                return 'ERROR: This function can only be performed on an FPG!'
             else:
                 graph = load(os.path.join(path, graphFileName), file_check_critical=False)
                 mpg = None
@@ -1741,7 +1864,8 @@ def interface(debug=True, tempdir=None):
             # Add the graph with the updated function order to VISTOMS
             newVistomsData = fpg.vistoms_add_json(function_order=function_order, graph_id=graphID, mpg=mpg)
             # Save the graph in temp/tmp.kdms
-            fpg.save(os.path.join(SESSIONS_CATALOG_FOLDER, TEMP_FILE + '_' + graphID + '.kdms'), file_type='kdms', graph_check_critical=False, mpg=mpg)
+            fpg.save(os.path.join(session_folder, TEMP_FILE + '_' + graphID + '.kdms'), file_type='kdms',
+                     graph_check_critical=False, mpg=mpg)
 
             return newVistomsData
 
@@ -1768,14 +1892,18 @@ def interface(debug=True, tempdir=None):
             else:
                 cleanUp = False
 
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+
             # Save previous graph as backup before making the changes
-            savePreviousGraph(graphID)
+            savePreviousGraph(graphID, session_id)
 
-            path = SESSIONS_CATALOG_FOLDER
+            path = session_folder
             graphFileName = TEMP_FILE + '_' + graphID + '.kdms'
             mpgFileName = TEMP_FILE + '_' + graphID + '_mpg.kdms'
             if os.path.exists(os.path.join(path, mpgFileName)):
-                return ("ERROR: You cannot do that on an existing MPG! Please go back to the FPG or RCG to do so.")
+                return "ERROR: You cannot do that on an existing MPG! Please go back to the FPG or RCG to do so."
             else:
                 graph = load(os.path.join(path, graphFileName), file_check_critical=False)
                 mpg = None
@@ -1812,7 +1940,7 @@ def interface(debug=True, tempdir=None):
                 # Add the graph with the updated function order to VISTOMS
                 newVistomsData = fpg.vistoms_add_json(function_order=function_order, graph_id=graphID, mpg=mpg)
                 # Save the graph in temp/tmp.kdms
-                fpg.save(os.path.join(SESSIONS_CATALOG_FOLDER, TEMP_FILE + '_' + graphID + '.kdms'),
+                fpg.save(os.path.join(session_folder, TEMP_FILE + '_' + graphID + '.kdms'),
                          file_type='kdms', graph_check_critical=False, mpg=mpg)
                 return newVistomsData
 
@@ -1839,29 +1967,33 @@ def interface(debug=True, tempdir=None):
             newGraphID = request.form['newGraphID']
             newGraphName = request.form['newGraphName']
 
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
+
             # Save previous graph as backup before making the changes
-            savePreviousGraph(graphID)
+            savePreviousGraph(graphID, session_id)
 
             newFileName = TEMP_FILE + '_' + newGraphID + '.kdms'
 
-            path = SESSIONS_CATALOG_FOLDER
+            path = session_folder
             graphFileName = TEMP_FILE+'_'+graphID+'.kdms'
             mpgFileName = TEMP_FILE+'_'+graphID+'_mpg.kdms'
             if os.path.exists(os.path.join(path, mpgFileName)):
-                return ("ERROR: Graph is already an MDPG! FPG Cannot be initialized again!")
+                return "ERROR: Graph is already an MDPG! FPG Cannot be initialized again!"
             else:
                 mpg = None
 
                 graph = load(os.path.join(path, graphFileName), file_check_critical=False)
 
                 if not isinstance(graph, FundamentalProblemGraph):
-                    return("ERROR: Graph is not an FPG yet. Please perform the FPG Manipulation steps first!")
+                    return "ERROR: Graph is not an FPG yet. Please perform the FPG Manipulation steps first!"
 
                 # check if fpg is well defined
                 check_result = graph._check_category_a()
                 if check_result[0] != True:
-                    return("ERROR: The FPG is not well defined yet. Please perform FPG manipulation steps first and check the graph again!")
-
+                    return "ERROR: The FPG is not well defined yet. Please perform FPG manipulation steps first and" \
+                           " check the graph again!"
 
                 mdg = deepcopy(graph)
                 mdg.graph['name'] = newGraphName
@@ -1873,7 +2005,8 @@ def interface(debug=True, tempdir=None):
                 # Add the graph with the updated function order to VISTOMS
                 newVistomsData = mdg.vistoms_add_json(function_order=functionOrder, graph_id=newGraphID, mpg=mpg)
                 # Save the graph in temp/tmp.kdms
-                mdg.save(os.path.join(SESSIONS_CATALOG_FOLDER, newFileName), file_type="kdms", graph_check_critical=False, mpg=mpg)
+                mdg.save(os.path.join(session_folder, newFileName), file_type="kdms", graph_check_critical=False,
+                         mpg=mpg)
 
                 return newVistomsData
 
@@ -1904,15 +2037,18 @@ def interface(debug=True, tempdir=None):
             else:
                 allow_unconverged_couplings = False
 
+            # First determine session folder
+            session_id = request.form['sessionId']
+            session_folder = retrieve_session_folder(SESSIONS_CATALOG_FOLDER, session_id)
 
             # Save previous graph as backup before making the changes
-            savePreviousGraph(graphID)
+            savePreviousGraph(graphID, session_id)
 
-            path = SESSIONS_CATALOG_FOLDER
+            path = session_folder
             graphFileName = TEMP_FILE + '_' + graphID + '.kdms'
             mpgFileName = TEMP_FILE + '_' + graphID + '_mpg.kdms'
             if os.path.exists(os.path.join(path, mpgFileName)):
-                return ("ERROR: You cannot perform this on an existing MPG! Please go back to the FPG to do so.")
+                return "ERROR: You cannot perform this on an existing MPG! Please go back to the FPG to do so."
             else:
                 graph = load(os.path.join(path, graphFileName), file_check_critical=False)
                 mpg = None
@@ -1926,7 +2062,8 @@ def interface(debug=True, tempdir=None):
                     coupling_decomposition = None
 
                 if not isinstance(graph, FundamentalProblemGraph):
-                    return "ERROR: Your graph is not an FPG yet. Please perform FPG manipulation steps before imposing an MDAO architecture!"
+                    return "ERROR: Your graph is not an FPG yet. Please perform FPG manipulation steps before " \
+                           "imposing an MDAO architecture!"
 
                 fpg = graph
 
@@ -1962,12 +2099,12 @@ def interface(debug=True, tempdir=None):
                 mdg, mpg = fpg.impose_mdao_architecture()
 
                 mpg.graph['name'] = 'XDSM - {}'.format(mdao_definition)
-                mpg.graph['description'] = 'Solution strategy to solve the super-sonic business jet test case optimization ' \
-                                           'problem using the strategy: {}.'.format(mdao_definition)
+                mpg.graph['description'] = 'Solution strategy to solve the super-sonic business jet test case ' \
+                                           'optimization problem using the strategy: {}.'.format(mdao_definition)
                 # Add the graph with the updated function order to VISTOMS
                 newVistomsData = mdg.vistoms_add_json(graph_id=graphID, mpg=mpg)
                 # Save the graph in temp/tmp.kdms
-                mdg.save(os.path.join(SESSIONS_CATALOG_FOLDER, TEMP_FILE + '_' + graphID + '.kdms'),
+                mdg.save(os.path.join(session_folder, TEMP_FILE + '_' + graphID + '.kdms'),
                          file_type='kdms', graph_check_critical=False, mpg=mpg)
                 return newVistomsData
 
-- 
GitLab