diff --git a/.gitignore b/.gitignore
index 9209ef5bfd4b97ad8e60f8b0a845db305b9a8094..dffe73526fb5f1e4481011707cf848254d46cf8e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,5 @@
 node_modules
 out
+dynare_m
+dynare_m_old
+dynareApp.code-workspace
diff --git a/package-lock.json b/package-lock.json
index 44326bee7821a3c78488c07fe88c90c52e64bb38..b1e231c9a181c196274482efe970b979bd1edd31 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -773,6 +773,17 @@
       "dev": true,
       "requires": {
         "rimraf": "^2.5.2"
+      },
+      "dependencies": {
+        "rimraf": {
+          "version": "2.7.1",
+          "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz",
+          "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==",
+          "dev": true,
+          "requires": {
+            "glob": "^7.1.3"
+          }
+        }
       }
     },
     "cuint": {
@@ -2590,6 +2601,18 @@
             "klaw": "^1.0.0",
             "path-is-absolute": "^1.0.0",
             "rimraf": "^2.2.8"
+          },
+          "dependencies": {
+            "rimraf": {
+              "version": "2.7.1",
+              "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz",
+              "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==",
+              "dev": true,
+              "optional": true,
+              "requires": {
+                "glob": "^7.1.3"
+              }
+            }
           }
         },
         "jsonfile": {
@@ -2721,6 +2744,15 @@
             "osenv": "^0.1.4"
           }
         },
+        "rimraf": {
+          "version": "2.7.1",
+          "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz",
+          "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==",
+          "dev": true,
+          "requires": {
+            "glob": "^7.1.3"
+          }
+        },
         "semver": {
           "version": "5.7.1",
           "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz",
@@ -2755,6 +2787,14 @@
             "osenv": "^0.1.4"
           }
         },
+        "rimraf": {
+          "version": "2.7.1",
+          "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz",
+          "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==",
+          "requires": {
+            "glob": "^7.1.3"
+          }
+        },
         "tar": {
           "version": "4.4.13",
           "resolved": "https://registry.npmjs.org/tar/-/tar-4.4.13.tgz",
@@ -3392,9 +3432,9 @@
       }
     },
     "rimraf": {
-      "version": "2.6.3",
-      "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz",
-      "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==",
+      "version": "3.0.2",
+      "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz",
+      "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==",
       "requires": {
         "glob": "^7.1.3"
       }
@@ -3496,9 +3536,9 @@
       "dev": true
     },
     "source-map-support": {
-      "version": "0.5.12",
-      "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.12.tgz",
-      "integrity": "sha512-4h2Pbvyy15EE02G+JOZpUCmqWJuqrs+sEkzewTm++BPi7Hvn/HwcqLAcNxYAyI0x13CpPPn+kMjl+hplXMHITQ==",
+      "version": "0.5.19",
+      "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.19.tgz",
+      "integrity": "sha512-Wonm7zOCIJzBGQdB+thsPar0kYuCIzYvxZwlBa87yi/Mdjv7Tip2cyVbLj5o0cFPN4EVkuTwb3GDDyUx2DGnGw==",
       "dev": true,
       "requires": {
         "buffer-from": "^1.0.0",
diff --git a/package.json b/package.json
index 739584601201b01030fa19364836ed18871f965c..57d6cf4b2fbc8d5f71cdeac090d57b3b4728915a 100644
--- a/package.json
+++ b/package.json
@@ -46,6 +46,7 @@
   "dependencies": {
     "electron-debug": "^3.1.0",
     "electron-squirrel-startup": "^1.0.0",
+    "rimraf": "^3.0.2",
     "short-uuid": "^3.1.1",
     "sqlite3": "^4.0.6"
   },
@@ -55,6 +56,7 @@
     "@electron-forge/maker-rpm": "^6.0.0-beta.33",
     "@electron-forge/maker-squirrel": "^6.0.0-beta.33",
     "@electron-forge/maker-zip": "^6.0.0-beta.33",
-    "electron": "4.1.4"
+    "electron": "4.1.4",
+    "source-map-support": "^0.5.19"
   }
 }
diff --git a/src/appModules.js b/src/appModules.js
index e98401ce0e8cc2d7a3d0e4f98e77f4102659cff0..c4cc49c27c7d15e99004213163d5d2e2d110b457 100644
--- a/src/appModules.js
+++ b/src/appModules.js
@@ -302,6 +302,19 @@ module.exports = {
     });
   },
 
+  movenewdatafile: function (myfilename, myfiletype, myfilepath) {
+    //careful in Electron we need to copy the file and not move
+    //copies the selected file from its current directory to the work folder
+    //an alterbative would be to use directly the original file at its path (not what we do here)
+    return new Promise(function (resolve, reject) {
+      var filePath = path.resolve(__dirname, './assets/modfiles/' + myfilename + '_datafile.' + myfiletype);
+      fs.copyFile(myfilepath, filePath, function (err) {
+        if (err) return reject(new Error('Unable to move datafile to work folder: ' + err));
+        return resolve();
+      });
+    });
+  },
+
   loadjsonfile: function (myfilename) {
     return new Promise(function (resolve, reject) {
 
@@ -388,7 +401,7 @@ module.exports = {
       }
       if (pptype == 2) {
         // cwd is important here
-        child = spawn(exePath, [myfilename], {
+        child = spawn(exePath, [myfilename, 'console'], {
           cwd: workPath
         });
       }
@@ -415,7 +428,8 @@ module.exports = {
         if (code == 0) {
           return resolve(dynarestdout);
         } else {
-          return reject(new Error('dynare_m did not exit with code 0 in preprocess: ' + dynarestdout));
+          //this will return the error output of the preprocessor and replace the local modfile path with just 'modfile'. The RegExp is used to replace all occurences
+          return reject(new Error(dynarestdout.replace(new RegExp(filePath, 'g'), 'modfile') + 'Dynare preprocessor did not exit with code 0 in preprocess.\n\n'));
         }
       });
     });
@@ -606,6 +620,146 @@ module.exports = {
         }
       }
 
+
+      console.log('in preparejsonfiles before estimation writing');
+
+
+
+      if (runtype == 3) {
+        //for estimation we don't write a json file but write everything on the mod file
+
+        //writing observables
+        if ('obsdescription' in jsonindata) {
+          modfilecontent += 'varobs ';
+          Object.keys(jsonindata['obsdescription']).forEach((key, index) => {
+            modfilecontent += modeljson['endogenous'][parseInt(jsonindata['obsdescription'][key]['obsindex'], 10)]['longName'] + ' ';
+          });
+          modfilecontent += ';\n\n';
+        }
+
+        //writing estimated params
+
+        var priorname = ['dummy', 'dummy', 'beta_pdf', 'gamma_pdf', 'normal_pdf', 'uniform_pdf', 'inv_gamma_pdf', 'inv_gamma1_pdf', 'inv_gamma2_pdf', 'weibull_pdf'];
+
+        if ('pardescription' in jsonindata) {
+
+          // console.log(jsonindata['pardescription'])
+
+          modfilecontent += 'estimated_params;\n';
+          Object.keys(jsonindata['pardescription']).forEach((key, index) => {
+            
+
+            if (jsonindata['pardescription'][key]['parshockindex'] > 999) {
+              if (jsonindata['pardescription'][key]['parassoshockindex'] > 0) {
+                modfilecontent += "corr " + modeljson['exogenous'][parseInt(jsonindata['pardescription'][key]['parshockindex'], 10) - 1000]['longName'] + ',' + modeljson['exogenous'][parseInt(jsonindata['pardescription'][key]['parassoshockindex'], 10) - 1000]['longName'] + ', ';
+              } else {
+                modfilecontent += "stderr " + modeljson['exogenous'][parseInt(jsonindata['pardescription'][key]['parshockindex'], 10)-1000]['longName'] + ', ';
+              }
+            } else {
+              modfilecontent += modeljson['parameters'][parseInt(jsonindata['pardescription'][key]['parshockindex'], 10)]['longName'] + ', ';
+            }
+
+            if (!(jsonindata['pardescription'][key]['parinivalue'] === null)) {
+              modfilecontent += jsonindata['pardescription'][key]['parinivalue'] + ', ';
+            } else {
+              modfilecontent += 'NaN,';
+            }
+
+            if (!(jsonindata['pardescription'][key]['parLbound'] === null)) {
+              modfilecontent += jsonindata['pardescription'][key]['parLbound'] + ', ';
+            } else {
+              modfilecontent += 'NaN,';
+            }
+
+            if (!(jsonindata['pardescription'][key]['parUbound'] === null)) {
+              modfilecontent += jsonindata['pardescription'][key]['parUbound'] + ', ';
+            } else {
+              modfilecontent += 'NaN';
+            }
+
+            if (jsonindata['pardescription'][key]['parprior'] > 1) {
+              modfilecontent +=','+ priorname[parseInt(jsonindata['pardescription'][key]['parprior'], 10)] + ', ';
+
+
+              if (!(jsonindata['pardescription'][key]['parpriormean'] === null)) {
+                modfilecontent += jsonindata['pardescription'][key]['parpriormean'] + ', ';
+              }
+
+              if (!(jsonindata['pardescription'][key]['parpriorstderr'] === null)) {
+                modfilecontent += jsonindata['pardescription'][key]['parpriorstderr'] + ', ';
+              }
+
+              if (!(jsonindata['pardescription'][key]['parprior3par'] === null)) {
+                modfilecontent += jsonindata['pardescription'][key]['parprior3par'] + ', ';
+              } else {
+                modfilecontent += 'NaN,';
+              }
+
+              if (!(jsonindata['pardescription'][key]['parprior4par'] === null)) {
+                modfilecontent += jsonindata['pardescription'][key]['parprior4par'] + ', ';
+              } else {
+                modfilecontent += 'NaN,';
+              }
+
+
+              if (!(jsonindata['pardescription'][key]['parpriorscale'] === null)) {
+                modfilecontent += jsonindata['pardescription'][key]['parpriorscale'] + ', ';
+              }
+              else{
+                modfilecontent += 'NaN';
+              }
+
+            }
+
+            modfilecontent += ';\n';
+
+            // modfilecontent += modeljson['endogenous'][parseInt(jsonindata['obsdescription'][key]['obsindex'], 10)]['longName']+ ' ';
+          });
+          modfilecontent += 'end;\n\n';
+        }
+
+        //writing estimation command
+
+        console.log(jsonindata['nobs'])
+        console.log(jsonindata['mhreplic'])
+        console.log(jsonindata['mhnblocks'])
+        console.log(jsonindata['mhjscale'])
+
+        modfilecontent +="estimation(datafile='"+modelhash + "_datafile."+jsonindata['datafiletype']+"'"; 
+
+        //put all the estimation options here
+        if (!(jsonindata['nobs'] === null)) {
+          modfilecontent +=',nobs='+parseInt(jsonindata['nobs'], 10);
+        }
+
+        if (!(jsonindata['mhreplic'] === null)) {
+          modfilecontent +=',mh_replic='+parseInt(jsonindata['mhreplic'], 10);
+        }
+
+        if (!(jsonindata['mhnblocks'] === null)) {
+          modfilecontent +=',mh_nblocks='+parseInt(jsonindata['mhnblocks'], 10);
+        }
+
+        if (!(jsonindata['mhjscale'] === null)) {
+          modfilecontent +=',mh_jscale='+parseInt(jsonindata['mhjscale'], 10);
+        }
+
+
+        //end of options close estimation command
+        modfilecontent +=');'
+
+
+
+
+
+
+
+
+
+      }
+
+      console.log('in preparejsonfiles AFTER estimation writing');
+
       // writing the temp.mod file
       try {
         await module.exports.createnewfile('temp.mod', modfilecontent);
diff --git a/src/assets/dynareapp.JSON b/src/assets/dynareapp.JSON
new file mode 100644
index 0000000000000000000000000000000000000000..8678ec488652b612fb1ec601d849a7039c89fddc
--- /dev/null
+++ b/src/assets/dynareapp.JSON
@@ -0,0 +1 @@
+{"matlabpath":"/Applications/MATLAB_R2018a.app","dynarepath":"/Applications/Dynare/4.6.2"}
\ No newline at end of file
diff --git a/src/assets/modfiles/di_estimation.m b/src/assets/modfiles/di_estimation.m
new file mode 100644
index 0000000000000000000000000000000000000000..86c7f2bf69405fc0e88de566e0cb890405bc87fe
--- /dev/null
+++ b/src/assets/modfiles/di_estimation.m
@@ -0,0 +1,109 @@
+function di_stochastic_simulations()
+
+	global M_ options_ oo_ dataset_ estim_params_
+
+
+	disp('di_estimation performing Matlab tasks');
+
+
+	data2json=struct();
+
+	data2json.exo_names=char(M_.exo_names);
+	data2json.param_names=char(M_.param_names);
+	data2json.exo_nbr=M_.exo_nbr;
+	data2json.param_nbr=M_.param_nbr;
+
+	%Smoothed shocks
+	if isfield(oo_,'SmoothedShocks')==1
+	data2json.SmoothedShocks=oo_.SmoothedShocks;
+	end
+
+	%Data
+	data2json.obs_nbr=length(dataset_.name);
+	data2json.obs_names=char(dataset_.name);
+	data2json.obs_data=dataset_.data;
+
+	data2json.obs_data={};
+	for nobs = 1:length(dataset_.name)
+		data2json.obs_data.(strtrim(char(dataset_.name(nobs,:))))=dataset_.data(:,nobs);
+	end
+
+	%Smoothed observables
+	if isfield(oo_,'SmoothedVariables')==1
+	data2json.SmoothedObs={};
+	for nobs = 1:length(dataset_.name)
+		data2json.SmoothedObs.(strtrim(char(dataset_.name(nobs,:))))=oo_.SmoothedVariables.(strtrim(char(dataset_.name(nobs,:))));
+	end
+	end
+
+	if isfield(oo_,'mle_mode')==1
+		%this is produced only with ML estim 
+		data2json.estimtypeflag=0; %this will indicate ML estimation
+
+		% if isfield(oo_.mle_mode,'parameters')==1
+		% data2json.mle_mode_params=oo_.mle_mode.parameters;
+		% data2json.mle_std_params=oo_.mle_std_at_mode.parameters;
+		% end
+		
+		% if isfield(oo_.mle_mode,'shocks_std')==1
+		% data2json.mle_mode_shocks_std=oo_.mle_mode.shocks_std;
+		% data2json.mle_std_shocks_std=oo_.mle_std_at_mode.shocks_std;
+		% end
+
+		if isfield(oo_,'mle_mode')==1
+			data2json.mle_mode=oo_.mle_mode;
+		end
+
+		if isfield(oo_,'mle_std_at_mode')==1
+			data2json.mle_std_at_mode=oo_.mle_std_at_mode;
+		end
+
+	else
+		data2json.estimtypeflag=1; %this will indicate Bayesian estimation
+
+		%prior info
+
+		
+
+		if isfield(estim_params_,'param_vals')==1
+			if isempty(estim_params_.param_vals)==0
+				data2json.param_vals=estim_params_.param_vals;
+			end
+		end
+
+		if isfield(estim_params_,'var_exo')==1
+			if isempty(estim_params_.var_exo)==0
+				data2json.var_exo=estim_params_.var_exo;
+			end
+		end
+
+		if isfield(estim_params_,'corrx')==1
+			if isempty(estim_params_.corrx)==0
+				data2json.corrx=estim_params_.corrx;
+			end
+		end
+
+		%prior density
+		if isfield(oo_,'prior_density')==1
+			data2json.prior_density=oo_.prior_density;
+		end
+
+		%posterior
+		if isfield(oo_,'posterior_density')==1
+			data2json.posterior_density=oo_.posterior_density;
+		end
+
+		if isfield(oo_,'posterior_mode')==1
+			data2json.posterior_mode=oo_.posterior_mode;
+			data2json.posterior_std=oo_.posterior_std_at_mode;
+			data2json.posterior_mean=oo_.posterior_mean;
+			data2json.posterior_hpdinf=oo_.posterior_hpdinf;
+			data2json.posterior_hpdsup=oo_.posterior_hpdsup;
+		end
+
+	end
+
+
+	savejson('',data2json,'estimout.JSON');
+
+return;
diff --git a/src/assets/modfiles/di_stochastic_simulations.m b/src/assets/modfiles/di_stochastic_simulations.m
index d59a7e77769028230ba13a05c19aa1a336f84654..8cb40c2e7698beee68575473e2b56b389f862757 100644
--- a/src/assets/modfiles/di_stochastic_simulations.m
+++ b/src/assets/modfiles/di_stochastic_simulations.m
@@ -43,7 +43,7 @@ function di_stochastic_simulations()
 	% 	options_.k_order_solver = 3;
 	% end
 	var_list_ = char();
-	info = stoch_simul(var_list_);
+	[info, oo_, options_, M_] = stoch_simul(M_, options_, oo_, var_list_);%stoch_simul(var_list_);
 
 	irfnames=fieldnames(oo_.irfs);
 	for jj = 1:numel(fieldnames(oo_.irfs))
diff --git a/src/assets/modfiles/readme.txt b/src/assets/modfiles/readme.txt
deleted file mode 100644
index 446b8fbb97fe56ee82bdd0b95a0da6fcf5855525..0000000000000000000000000000000000000000
--- a/src/assets/modfiles/readme.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-Working directory.
-Also the place for Matlab functions.
diff --git a/src/background.js b/src/background.js
index 7c9265a3925140445efe07c45624e1db9201cd0f..e47b97958a10ee0dfef13b0cca2e815db027268d 100644
--- a/src/background.js
+++ b/src/background.js
@@ -13,7 +13,7 @@ async function main() {
 
   //loading matlab
   var exePath = path.resolve(__dirname, matlabpath + '/bin/matlab');
-  const child = spawn(exePath, ['-nosplash'], {
+  const child = spawn(exePath, ['-nosplash -nodisplay'], {
     shell: true
   });
 
@@ -50,6 +50,14 @@ async function main() {
         };
       }
 
+      if (origincalltype == 3) {
+        //this is the return from estimation computation
+        mymessage = {
+          'messageid': 'matlabready',
+          'message': 3
+        };
+      }
+
       // process.send('matlabready', origincalltype);
       process.send(mymessage);
       // }
@@ -57,11 +65,33 @@ async function main() {
       //   origincalltype += 1;
       // }
     } else {
-      // process.send('stdoutmessage', data)
-      mymessage = {
-        'messageid': 'stdoutmessage',
-        'message': `${data}`
-      };
+
+      data=data.toString();
+
+      
+
+
+      // if (data[0] == 8){
+      if (data.includes('RW Metropolis-Hastings')==true){
+        //capturing RW Metropolis-Hastings (1/2) Current acceptance ratio wrong char
+        // data=data.slice(69).toString();
+        // data=data+'\n';
+        mymessage = {
+          'messageid': 'stdoutmessage',
+          'messagetype': 'progressbar',
+          'message': data //'message': `${data}`
+        };
+      }
+      else{
+        // data=data.toString();
+        mymessage = {
+          'messageid': 'stdoutmessage',
+          'messagetype': 'normal',
+          'message': data //'message': `${data}`
+        };
+      }
+
+
       process.send(mymessage);
     }
   });
@@ -85,16 +115,21 @@ async function main() {
 
       if (pmessage.messagetype == 'stochastic') {
         origincalltype = 1;
-        child.stdin.write('run temp.m;run di_stochastic_simulations.m;\n');
+        child.stdin.write('run temp.driver.m;run di_stochastic_simulations.m;\n');
         child.stdin.on('drain', () => {});
       }
 
       if (pmessage.messagetype == 'perfect') {
         origincalltype = 2;
-        child.stdin.write('run temp.m;run di_perfect_foresight.m;\n');
+        child.stdin.write('run temp.driver.m;run di_perfect_foresight.m;\n');
         child.stdin.on('drain', () => {});
       }
 
+      if (pmessage.messagetype=='estimation'){
+        origincalltype = 3;
+        child.stdin.write('run temp.driver.m;run di_estimation.m;\n');
+        child.stdin.on('drain', () => {});
+      }
 
 
     }
diff --git a/src/index.html b/src/index.html
index 63b6383d46fc1b0ff1d6343255d20b9cdc4fc7d6..b25d1aa810b8e6a6407b6e45791b971d08ad5da3 100644
--- a/src/index.html
+++ b/src/index.html
@@ -76,17 +76,18 @@
       <span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span> Save
     </button>
     <button id="runcode" type="button" title="Run" class="btn btn-success btn-lg">
-      <span class="glyphicon glyphicon-play" aria-hidden="true"></span> Run
+      <span class="glyphicon glyphicon-play" aria-hidden="true"></span> Preprocess
     </button>
   </div>
   <div class="btn-group">
     <button id="runsim" type="button" title="Simulation" class="btn btn-success btn-lg dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
-      <span class="glyphicon glyphicon-play" aria-hidden="true"></span> Simulation <span class="caret"></span>
+      <span class="glyphicon glyphicon-play" aria-hidden="true"></span> Run... <span class="caret"></span>
     </button>
     <ul class="dropdown-menu">
       <!-- <li data-toggle="modal" data-target="#perforModal"><a href="#">Perfect foresight</a></li> -->
-      <li id="setperfect"><a href="#">Perfect foresight</a></li>
-      <li id="setstochastic"><a href="#">Stochastic</a></li>
+      <li id="setperfect"><a href="#">Perfect foresight simulation</a></li>
+      <li id="setstochastic"><a href="#">Stochastic simulation</a></li>
+      <li id="setestimation"><a href="#">Estimation</a></li>
       <!-- <li><a href="#">Another action</a></li>
       <li><a href="#">Something else here</a></li>
       <li role="separator" class="divider"></li>
@@ -123,6 +124,7 @@
       </div>
       <div class="outputdata">
         <div id="outputtable"></div>
+        <div id="outputtable2"></div>
         <div id="plotbtn"></div>
         <div id="plotbox" style="height:500px;"></div>
         <div id="graphend"><a href="#stophere"></a></div>
@@ -146,9 +148,34 @@
 
 
 <!-- Modals -->
+
+<!-- MH acceptance ratio modal -->
+<div class="modal fade" id="MHmodal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
+  <div class="modal-dialog modal-lg" role="document">
+    <div class="modal-content">
+      <!-- Modal Header -->
+      <div class="modal-header">
+        <button type="button" class="close" data-dismiss="modal">
+          <span aria-hidden="true">&times;</span>
+          <span class="sr-only">Close</span>
+        </button>
+        <h4 class="modal-title" id="myModalLabel">
+          RW Metropolis-Hastings (<span id="MHloop">1</span>/<span id="MHloopover">2</span>) Current acceptance ratio <span id="MHCAR">1</span>
+        </h4>
+      </div>
+
+      <div class="modal-body">
+        <div id="myProgress">
+          <div id="myBar">0%</div>
+        </div>
+      </div>
+
+    </div>
+  </div>
+</div>
+
 <!-- perfect foresight modal Start -->
-<div class="modal fade" id="perforModal" tabindex="-1" role="dialog"
-     aria-labelledby="myModalLabel" aria-hidden="true">
+<div class="modal fade" id="perforModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
     <div class="modal-dialog modal-lg">
         <div class="modal-content">
             <!-- Modal Header -->
@@ -329,6 +356,156 @@
 </div>
 <!-- stochastic sim modal End-->
 
+
+
+<!-- estimation modal Start -->
+<div class="modal fade" id="estimModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
+  <div class="modal-dialog modal-lg">
+      <div class="modal-content">
+          <!-- Modal Header -->
+          <div class="modal-header">
+              <button type="button" class="close"
+                 data-dismiss="modal">
+                     <span aria-hidden="true">&times;</span>
+                     <span class="sr-only">Close</span>
+              </button>
+              <h4 class="modal-title" id="myModalLabel">
+                  Estimation
+              </h4>
+          </div>
+
+          <!-- Modal Body -->
+          <div class="modal-body">
+
+            <ul class="nav nav-tabs tabs-up" id="estimmodaltabs">
+              <li class="active"><a data-toggle="tab" href="#estimsetuptable">Setup</a></li>
+              <li><a data-toggle="tab" href="#estimparams">Parameters</a></li>
+              <li><a data-toggle="tab" href="#estimoptions">Options</a></li>
+            </ul>
+            <br>
+            <div class="tab-content">
+
+              <div id="estimsetuptable" class="tab-pane fade in active">
+                <h4>Data <div class="tooltipcsshead"><span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span><span class="tooltiptextcsshead">A .m file, a .mat file, a .csv file, or a .xls/.xlsx file.</span></div></h4>
+                  <table class="table small">
+                    <tbody>
+                      <tr>
+                        <td>Please choose a data file:</td>
+                        <td><input type="file" class="form-control-file no-border" id="estfile" accept=".m,.csv,.xls,.xlsx,.mat"></td>
+                        <input id="estmodel_endonum" name="estmodel_endonum" value="" type="hidden">
+                        <input id="estmodel_exonum" name="estmodel_exonum" value="" type="hidden">
+                        <input id="estmodel_paramnum" name="estmodel_paramnum" value="" type="hidden">
+                      </tr>
+                    </tbody>
+                  </table>
+
+                  <h4>Observable variables <div class="tooltipcsshead"><span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span><span class="tooltiptextcsshead">List of the name(s) of observed endogenous variables for the estimation procedure. These variables must be available in the data file.</span></div></h4>
+                  <button id="estaddobs" type="button" title="addobs" class="btn btn-success btn-sm">Add observables</button>
+                  <table id="estobstable" class="table table-striped small">
+                  <thead>
+                  <tr>
+                  <!-- <th>#</th> -->
+                  <th>Variable</th>
+                  <th>X</th>
+                  </tr>
+                  </thead>
+                  <tbody>
+                  </tbody>
+                </table>
+                  <div id="estinittable"></div>
+              </div>
+
+
+                <div id="estimparams" class="tab-pane fade in">
+                  <h4>Estimated parameters <div class="tooltipcsshead"><span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span><span class="tooltiptextcsshead">List of all parameters to be estimated and specification of bounds and priors as necessary.</span></div></h4>
+                  <button id="estaddparam" type="button" title="addparam" class="btn btn-success btn-sm">Add parameter</button>
+                  <table id="estpartable" class="table table-striped small">
+                  <thead>
+                  <tr>
+                  <!-- <th>#</th> -->
+                  <th>Parameter/Variable</th>
+                  <th>Value</th>
+                  <th>Lower bound</th>
+                  <th>Upper bound</th>
+                  <th>Prior density</th>
+                  <th>Prior Mean</th>
+                  <th>Prior StdErr</th>
+                  <th>Prior 3rd param</th>
+                  <th>Prior 4th param</th>
+                  <th>Scale</th>
+                  <th>Correleted var</th>
+                  <th>X</th>
+                  </tr>
+                  </thead>
+                  <tbody>
+                  </tbody>
+                </table>
+
+                </div>
+
+                <div id="estimoptions" class="tab-pane fade in">
+                  <h4>Options</h4>
+                    <table class="table table-striped small">
+                      <thead>
+                        <tr>
+                          <th>#</th>
+                          <th>Option</th>
+                          <th>Value</th>
+                          <th>Info</th>
+                        </tr>
+                      </thead>
+                      <tbody>
+                        <tr>
+                          <th scope="row">1</th>
+                          <td>Number of observations (nobs)</td>
+                          <td><input class="form-control no-border input-sm" name="estimopt_nobs" id="estimopt_nobs" placeholder="All" type="text" value=""></td>
+                          <td><div class="tooltipcss"><span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span><span class="tooltiptextcss">The number of observations following first_obs to be used.<br> Default: all observations in the file after first_obs.</span></div></td>
+                        </tr>
+                        <tr>
+                        <th scope="row">2</th>
+                        <td>Number of replications (mh_replic)</td>
+                        <td><input class="form-control no-border input-sm" name="estimopt_mh_replic" id="estimopt_mh_replic" placeholder="20000" type="text" value=""></td>
+                        <td><div class="tooltipcss"><span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span><span class="tooltiptextcss">Number of replications for Metropolis-Hastings algorithm. For the time being, mh_replic should be larger than 1200.<br> Default: 20000.</span></div></td>
+                      </tr>
+
+                      <tr>
+                        <th scope="row">3</th>
+                        <td>Number of blocks (mh_nblocks)</td>
+                        <td><input class="form-control no-border input-sm" name="estimopt_mh_nblocks" id="estimopt_mh_nblocks" placeholder="2" type="text" value=""></td>
+                        <td><div class="tooltipcss"><span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span><span class="tooltiptextcss">Number of parallel chains for Metropolis-Hastings algorithm.<br> Default: 2.</span></div></td>
+                      </tr>
+
+                      <tr>
+                        <th scope="row">4</th>
+                        <td>Scale parameter (mh_jscale)</td>
+                        <td><input class="form-control no-border input-sm" name="estimopt_mh_jscale" id="estimopt_mh_jscale" placeholder="0.2" type="text" value=""></td>
+                        <td><div class="tooltipcss"><span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span><span class="tooltiptextcss">The scale parameter of the jumping distribution’s covariance matrix (Metropolis-Hastings or TaRB-algorithm). The default value is rarely satisfactory. This option must be tuned to obtain, ideally, an acceptance ratio of 25%-33%. Basically, the idea is to increase the variance of the jumping distribution if the acceptance ratio is too high, and decrease the same variance if the acceptance ratio is too low. In some situations it may help to consider parameter-specific values for this scale parameter. This can be done in the estimated_params- block.<br> Note that mode_compute=6 will tune the scale parameter to achieve an acceptance rate of AcceptanceRateTarget. The resulting scale parameter will be saved into a file named MODEL_FILENAME_mh_scale.mat. This file can be loaded in subsequent runs via the posterior_sampler_options-option scale_file. Both mode_compute=6 and scale_file will overwrite any value specified in estimated_params with the tuned value.<br> Default: 0.2.</span></div></td>
+                      </tr>
+
+                      </tbody>
+                    </table>
+                </div>
+
+                
+
+            </div>
+          </div>
+
+          <!-- Modal Footer -->
+          <div class="modal-footer">
+              <button type="button" class="btn btn-default"
+                      data-dismiss="modal">
+                          Close
+              </button>
+              <button type="button" id="runestimation" class="btn btn-primary">
+                  Run estimation
+              </button>
+          </div>
+      </div>
+  </div>
+</div>
+<!-- estimation modal End-->
+
 <!-- End Modals -->
 
 
@@ -406,6 +583,7 @@
         <script src="./static/js/editor.js"></script>
         <script src="./static/js/perfectforesight.js"></script>
         <script src="./static/js/stochastic.js"></script>
+        <script src="./static/js/estimation.js"></script>
 
 
   </body>
diff --git a/src/index.js b/src/index.js
index 6719a53356091fb1dea3747bb639b39091de8b52..ce4cb3628ceb3740ed087aa60a60a320097c59c3 100644
--- a/src/index.js
+++ b/src/index.js
@@ -117,12 +117,13 @@ function createWindow() {
     backgroundColor: '#FFF',
     minWidth: 256,
     webPreferences: {
+      devTools: false,
       nodeIntegration: true
     }
   });
   mainWindow.maximize();
   mainWindow.webContents.loadURL(`file://${__dirname}/index.html`); // #A
-  mainWindow.webContents.openDevTools();
+  // mainWindow.webContents.openDevTools();
 
   // Wait for 'ready-to-show' to display our window
   mainWindow.once('ready-to-show', () => {
@@ -233,6 +234,8 @@ app.on('ready', async function () {
   };
   const child = fork(program, parameters, options);
 
+  var initprogressbar=0;
+  var progressbarcount=0;
 
   // this message comes from either stochastic or perfect foresight and is a call to perform simulations
   ipcMain.on('rundynarematlab', function (event, data) {
@@ -240,6 +243,12 @@ app.on('ready', async function () {
     console.log('received ipc message from runprocesses');
     console.log(data)
 
+    if (data=='estimation')
+    {
+      initprogressbar=1;
+      progressbarcount=0;
+    }
+
 
     if (matlabreadyflag == 1) {
       console.log("Matlab is ready !");
@@ -282,12 +291,50 @@ app.on('ready', async function () {
         mainWindow.webContents.send('perfectsimfinish', message.message);
       }
 
+      if (message.message == 3) {
+        console.log('-=estimation computation completed=-');
+        mainWindow.webContents.send('estimationfinish', message.message);
+      }
+
     }
 
     if (message.messageid == 'stdoutmessage') {
-      console.log("stdoutmessage");
-      console.log(`${message.message}`);
-      mainWindow.webContents.send('matlabmessagetoconsole', message.message);
+      // console.log("stdoutmessage");
+      // console.log(`${message.message}`);
+
+      if (message.messagetype=='progressbar'){
+        if (initprogressbar==1)
+        {
+          initprogressbar=0;
+          mainWindow.webContents.send('matlabmessagetoconsole_progressbar_init', message.message);
+          // sockIO.emit('matlabmessagetoconsole_progressbar_init', message.message);
+          // console.log('matlabmessagetoconsole_progressbar_init sent');
+        }
+        else {
+  
+          progressbarcount=progressbarcount+1;
+  
+          if (progressbarcount%50==0){
+            // sockIO.emit('matlabmessagetoconsole_progressbar', message.message);
+            mainWindow.webContents.send('matlabmessagetoconsole_progressbar', message.message);
+            // console.log('matlabmessagetoconsole_progressbar');
+          }
+          
+  
+        } 
+        
+      }
+      else{
+        console.log(message.message);
+        // sockIO.emit('matlabmessagetoconsole', message.message);
+        mainWindow.webContents.send('matlabmessagetoconsole', message.message);
+      }
+
+
+
+
+
+      
       messageprocess = 1;
     }
 
diff --git a/src/renderer.js b/src/renderer.js
index fa7995adb8593ae99b100f8c603fe21cf97e5718..eac34076665199924ba2707433295d27f9166120 100755
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -137,10 +137,60 @@ initapp();
 
 
 
-ipc.on('matlabmessagetoconsole', (event, arg) => {
-  showconsolealert(`${arg}`,0);
+ipc.on('matlabmessagetoconsole', (event, msg) => {
+  // showconsolealert(`${arg}`,0);
+  showconsolealert(msg,0);
+  scrolltextarea();
 });
 
+var numberPattern = /\d+/g;
+
+ipc.on('matlabmessagetoconsole_progressbar_init', (event, arg) => {
+  //initializes the MH progress bar
+  // socket.on('matlabmessagetoconsole_progressbar_init', function(msg){
+    
+    $('#MHmodal').modal({backdrop: 'static', keyboard: false}) ;
+    $('#MHmodal').modal('show'); 
+    // modalupdatecount=0;
+    // console.log('matlabmessagetoconsole_progressbar_init received');
+    // document.getElementById("MHloop").innerHTML="1";
+  // });
+});
+
+ipc.on('matlabmessagetoconsole_progressbar', (event, msg) => {
+  //updates the MH progress bar
+  // socket.on('matlabmessagetoconsole_progressbar', function(msg){
+    // console.log('matlabmessagetoconsole_progressbar received');
+   
+    var mynumarray=msg.match(numberPattern);
+    document.getElementById("MHloop").innerHTML=mynumarray[0];
+    document.getElementById("MHloopover").innerHTML=mynumarray[1];
+    document.getElementById("MHCAR").innerHTML=mynumarray[2].toString()+'.'+mynumarray[3].toString();
+    var elem = document.getElementById("myBar");
+    var width = mynumarray[4];
+
+    if (width >= 100) {
+      i = 0;
+    } else {
+      // width++;
+      elem.style.width = width + "%";
+      elem.innerHTML = width  + "%";
+    }
+
+  // });
+});
+
+
+
+
+
+
+
+
+
+
+
+
 ipc.on('createnewproject', (event, arg) => {
   console.log('got it!')
   createnewproject();
diff --git a/src/runprocesses.js b/src/runprocesses.js
index 3a128c840a52dc23dfbf835df8d1c51984093fd2..f998b1e4482ca8252df50a928fa54963953549e3 100644
--- a/src/runprocesses.js
+++ b/src/runprocesses.js
@@ -7,8 +7,11 @@ const basedir = require('./appModules').basedir;
 const loadjsonfile = require('./appModules').loadjsonfile;
 const checkfileexist = require('./appModules').checkfileexist
 const preparejsonfiles = require('./appModules').preparejsonfiles;
+const movenewdatafile = require('./appModules').movenewdatafile;
 const cl = require('./appModules').cl;
-
+const path = require('path');
+var fs = require('fs');
+var rimraf = require("rimraf");
 
 
 
@@ -77,7 +80,7 @@ module.exports = {
             var dynarestdout = '';
             var preprocok = 1;
             try {
-                dynarestdout += await preprocess(dynaremodel['modelhash'] + '_ini.mod', 3);
+                dynarestdout += await preprocess(dynaremodel['modelhash'] + '_ini.mod', 1);
             } catch (error) {
                 dynarestdout += error.toString();
                 preprocok = 0;
@@ -177,6 +180,49 @@ module.exports = {
                 });
             }
 
+            //starting with Dynare 4.6 the JSON file is created in a subfolder and it is called 'modfile.json'
+            //for simplicity we move it out of there and delete the folder
+
+            new Promise(function (resolve, reject) {
+                var oldfilepath = path.resolve(__dirname, './assets/modfiles/' + dynaremodel['modelhash'] + '_ini/model/json/modfile.json');
+                console.log(oldfilepath)
+                var newfilePath = path.resolve(__dirname, './assets/modfiles/' + dynaremodel['modelhash'] + '_ini.json');
+                console.log(newfilePath)
+                fs.rename(oldfilepath, newfilePath, function (err) {
+                    if (err) return reject(new Error('Unable to move model JSON to work folder: ' + err));
+                    return resolve();
+                });
+            });
+
+
+
+            new Promise(function (resolve, reject) {
+                var oldfilepath = path.resolve(__dirname, './assets/modfiles/' + dynaremodel['modelhash'] + '_ini/model/json/steady_state_model.json');
+                var newfilePath = path.resolve(__dirname, './assets/modfiles/' + dynaremodel['modelhash'] + '_ini_steady_state_model.json');
+                fs.rename(oldfilepath, newfilePath, function (err) {
+                    if (err) return reject(new Error('Unable to move steady_state_model JSON to work folder: ' + err));
+                    return resolve();
+                });
+            });
+
+            //careful the following rmdir function requires node version 12 or higher 
+            new Promise(function (resolve, reject) {
+                var oldfilepath = path.resolve(__dirname, './assets/modfiles/' + dynaremodel['modelhash'] + '_ini/');
+                // fs.rmdir(oldfilepath, { recursive: true }, function (err) {
+                //     if (err) return reject(new Error('Unable to remove directory: ' + err));
+                //     return resolve();
+                // });
+
+                //for some reason fs.rmdir returns an error in electron, we use rimraf instead
+                rimraf(oldfilepath, function (err) {
+                    if (err) return reject(new Error('Unable to remove directory: ' + err));
+                    return resolve();
+                });
+
+            });
+
+
+
             // loading JSON created by dynare preprocessor
             try {
                 var dynaremodeljson = await loadjsonfile(dynaremodel['modelhash'] + '_ini.json');
@@ -235,12 +281,75 @@ module.exports = {
         }); //end of main promise
     },
 
+    runsaveestimationfilenode: (datafileinfo) => {
+
+        return new Promise(async function (resolve, reject) {
+            //because datafileinfo is in FormData format, we use get to get its elements. This might not be compatible with older versions of Chromium
+            const filepath = datafileinfo.get('file').path;
+            const filesavename = datafileinfo.get('filename');
+            const filesavetype = datafileinfo.get('filetype');
+
+            try {
+                await movenewdatafile(filesavename, filesavetype, filepath);
+            } catch (error) {
+                return reject(error);
+            }
+
+            return resolve('Done runsaveestimationfilenode');
+
+        }); //end of main promise
+
+
+    },
+
+
+    runestimationnode: (estimval) => {
+
+        return new Promise(async function (resolve, reject) {
+
+            estimval=JSON.parse(estimval);
+
+
+            console.log('inside runestimationnode');
+            console.log(estimval);
+
+            var modelhash = estimval['modelhash'];
+            // preparing only the standardized JSON in data
+            var estimindata = {
+                'nobs': estimval['parnobs'],
+                'mhreplic': estimval['parmhreplic'],
+                'mhnblocks': estimval['parmhnblocks'],
+                'mhjscale': estimval['parmhjscale'],
+                'obsdescription': estimval['obsdescription'],
+                'pardescription': estimval['pardescription'],
+                'datafiletype': estimval['datafiletype']
+            };
+
+            try {
+                await preparejsonfiles(modelhash, 3, estimval, estimindata);
+            } catch (error) {
+                return reject(error);
+            }
+
+            const reply = ipc.sendSync('rundynarematlab', "estimation");
+            cl(reply);
+
+            return resolve('Done runstochasticnode');
+
+
+        }); //end of main promise
+
+
+    },
+
 
 
     runstochasticnode: (stosimval) => {
 
         return new Promise(async function (resolve, reject) {
 
+            stosimval=JSON.parse(stosimval);
+
             var modelhash = stosimval['modelhash'];
             // preparing only the standardized JSON in data
             var stochsimindata = {
@@ -272,6 +381,8 @@ module.exports = {
 
         return new Promise(async function (resolve, reject) {
 
+            perfectval=JSON.parse(perfectval);
+
 
             console.log('inside runperfectnode');
 
diff --git a/src/static/css/dynareinterface.css b/src/static/css/dynareinterface.css
index 6608639232ccf5c8b6cb7638819510c28805024e..b9624c6dc18d93b87f38dacbc670d0ca90966bac 100644
--- a/src/static/css/dynareinterface.css
+++ b/src/static/css/dynareinterface.css
@@ -104,6 +104,8 @@ body { padding-top: 70px; }
 
  }
 
+ 
+
 
 
 
@@ -252,3 +254,83 @@ html {
 body, input {
   font: menu; // #A
 }
+
+
+/* CSS tool tips */
+
+.tooltipcss {
+  position: relative;
+  display: inline-block;
+  font-size:110%
+}
+
+.tooltipcss .tooltiptextcss {
+  visibility: hidden;
+  width: 3000%;
+  background-color: #F5F5F5;
+  color: #808080;
+  text-align: justify;
+  border-radius: 6px;
+  padding: 10px;
+  /* Position the tooltip */
+  position: absolute;
+  z-index: 1;
+  top: -5px;
+  right: 105%;
+}
+
+/* .tooltipcss .tooltiptextcss::after {
+  content: "";
+  position: absolute;
+  bottom: 100%;
+  left: 50%;
+  margin-left: -5px;
+  border-width: 5px;
+  border-style: solid;
+  border-color: transparent transparent black transparent;
+} */
+
+.tooltipcss:hover .tooltiptextcss {
+  visibility: visible;
+}
+
+
+.tooltipcsshead {
+  position: relative;
+  display: inline-block;
+  font-size:70%
+}
+
+.tooltipcsshead .tooltiptextcsshead {
+  visibility: hidden;
+  width: 3000%;
+  background-color: #F5F5F5;
+  color: #808080;
+  text-align: justify;
+  border-radius: 6px;
+  padding: 10px;
+  /* Position the tooltip */
+  position: absolute;
+  z-index: 1;
+  top: -5px;
+  left: 105%;
+}
+
+
+.tooltipcsshead:hover .tooltiptextcsshead {
+  visibility: visible;
+}
+
+#myProgress {
+  width: 100%;
+  background-color: #ddd;
+}
+
+#myBar {
+  width: 0%;
+  height: 30px;
+  background-color: #5aa8f1;
+  text-align: center;
+  line-height: 30px;
+  color: white;
+}
diff --git a/src/static/js/dynareinterface.js b/src/static/js/dynareinterface.js
index b64f58f8a70597cbadd532f086a87f5ab2c03b74..85e85dbd916ed25c81d3f8c658f8a7b37b4fd3c9 100644
--- a/src/static/js/dynareinterface.js
+++ b/src/static/js/dynareinterface.js
@@ -15,6 +15,11 @@ function download(filename, text) {
   document.body.removeChild(element);
 }
 
+function scrolltextarea(){
+  var textarea = document.getElementById('preprocessorout');
+  textarea.scrollTop = textarea.scrollHeight; 
+}
+
 
 
 //new project on click function
@@ -222,11 +227,8 @@ try {
 }
 
 showconsolealert(resp.message, 1);
-
 //displays the new save time
 var currentdate = new Date();
 $('#classlist-form-messages').text('Last saved at: ' + currentdate);
-
-
   return false;
 });
diff --git a/src/static/js/estimation.js b/src/static/js/estimation.js
new file mode 100644
index 0000000000000000000000000000000000000000..259440ac3050811639dc726ff58cf84b7b7c3774
--- /dev/null
+++ b/src/static/js/estimation.js
@@ -0,0 +1,1607 @@
+const ipcest = require('electron').ipcRenderer;
+// const setpreprocessmore = require('./runprocesses').setpreprocessmore;
+const runestimationnode = require('./runprocesses').runestimationnode;
+const runsaveestimationfilenode = require('./runprocesses').runsaveestimationfilenode;
+
+
+
+
+var estmatlabdata;
+
+$('#setestimation').click(async function () {
+
+  // let basedir = path.resolve(__dirname, './assets/modfiles/');
+
+  let modelname = $('#codename').val();
+  if (modelname == null || modelname == "") {
+    $.alert({
+      title: 'Project name is empty.',
+      content: 'Please choose a name for this project...',
+    });
+    return false;
+  }
+
+  let modelcode = {
+    'modelcode': window.editor_dynare.getValue(),
+    'modelhash': $('#codehash').val(),
+    'modelname': $('#codename').val(),
+    'accesstype': 'setestimation'
+  };
+
+// calling the 'node side'
+try {
+  var resp = await setpreprocessmore(modelcode);
+} catch (error) {
+  if (error.status == 200) {
+    console.log("200")
+    return popthis('Error', error.message);
+  } else if (error.status == 100) {
+    console.log("100")
+    showconsolealert(error.message, 1);
+    console.log('console error');
+    return false;
+  } else if (error.status == 999) {
+    popthis('Error', resp.message);
+  }
+}
+
+      showconsolealert(resp.message, 1);
+      scrolltextarea();
+
+      var currentdate = new Date();
+      $('#classlist-form-messages').text('Last saved at: ' + currentdate);
+
+
+      dynaremodel = resp.modeljson;
+
+      // if a steady state has not been provided if ask extra info on that
+      // steady-state compute table
+      document.getElementById("estinittable").innerHTML = "";
+      if (resp.status == 201) {
+        var extrassinfo = "";
+        var extrasshelp = "";
+        if (resp.extrassinfo !== null) {
+          extrassinfo = resp.extrassinfo;
+          extrasshelp = " (the last known steady-state info have been loaded below)"
+        }
+        var extrasstype = "";
+        if (resp.extrasstype == 1) {
+          extrasstype = 'checked';
+        }
+
+        sscomputeeendo = `
+        <h4>Steady state</h4>
+        <p style="color:#3399CC">You did not provide any way to compute the steady-state. Please specify a way to compute the steady-state` + extrasshelp + `.</p>
+        <div class="form-group no-margin"> <textarea class="form-control" id="estSSblock" name="estSSblock" placeholder="Steady-state equations;" rows="7">` + extrassinfo + `</textarea> </div>
+        <div class="form-group no-margin"><label><input type="checkbox" name="estissteadystateblock" id="estissteadystateblock"` + extrasstype + `/> Check if the above will compute the exact steady-state (will be interpreted as a <span style="font-style: italic;">steady_state_model</span> block). Leave unchecked if the above should be used as a starting point to compute the steady-state (will be interpreted as an <span style="font-style: italic;">initval</span> block).</label></div>
+        <input id="estmodelsteadystatestatus" name="estmodelsteadystatestatus" value="99" type="hidden">
+        `;
+      } else if (resp.status == 2) {
+        sscomputeeendo = `
+        <input id="estmodelsteadystatestatus" name="estmodelsteadystatestatus" value="55" type="hidden">
+        `;
+      } else {
+        sscomputeeendo = `
+        <input id="estmodelsteadystatestatus" name="estmodelsteadystatestatus" value="0" type="hidden">
+        `;
+      }
+      document.getElementById("estinittable").innerHTML = sscomputeeendo;
+      document.getElementById("estmodel_endonum").value = (dynaremodel.endogenous).length;
+      document.getElementById("estmodel_exonum").value = (dynaremodel.exogenous).length;
+      document.getElementById("estmodel_paramnum").value = (dynaremodel.exogenous).length + (dynaremodel.parameters).length;
+      $('#estimModal').modal('show');
+
+
+  return false;
+
+});
+
+
+var estobsnum = [];
+var estparnum = [];
+for (i = 0; i < 1000; i++) {
+  estobsnum[i] = 0;
+  estparnum[i] = 0;
+}
+
+
+$('#estaddobs').click(function () {
+  var estobsrowindex;
+  var estobsxcond = 0;
+  var estobsiter = 0;
+
+  while (estobsxcond == 0) {
+    if (estobsnum[estobsiter] == 0) {
+      estobsxcond = 1;
+      estobsrowindex = estobsiter;
+      estobsnum[estobsiter] = 1;
+    }
+    estobsiter = estobsiter + 1;
+  }
+  estobsexpectedshockstable = '';
+  estobsexpectedshockstable += '<tr><td><select id="estobsvarname' + estobsrowindex + '" class="form-control input-sm" name="estobsvarname">';
+  for (x in dynaremodel.endogenous) {
+    estobsexpectedshockstable += '<option value="' + x + '">' + dynaremodel.endogenous[x]["longName"] + '</option>';
+  }
+  estobsexpectedshockstable += "</select></td>";
+
+
+  estobsexpectedshockstable += '<td><input type="button" value="X" onclick="estobsSomeDeleteRowFunction(this,' + estobsrowindex + ')" class="form-control no-border input-sm btn-default btn-xs" name="estobsremoveshock' + estobsrowindex + '" id="estobsremoveshock' + estobsrowindex + '"></td></tr>';
+  $('#estobstable tbody').append(estobsexpectedshockstable);
+  return false;
+});
+
+function estobsSomeDeleteRowFunction(o, estobsrowindex) {
+  var p = o.parentNode.parentNode;
+  p.parentNode.removeChild(p);
+  estobsnum[estobsrowindex] = 0;
+}
+
+
+
+
+$('#estaddparam').click(function () {
+  var estparrowindex;
+  var estparxcond = 0;
+  var estpariter = 0;
+  var exovarcounter = 999;
+  while (estparxcond == 0) {
+    if (estparnum[estpariter] == 0) {
+      estparxcond = 1;
+      estparrowindex = estpariter;
+      estparnum[estpariter] = 1;
+    }
+    estpariter = estpariter + 1;
+  }
+  estparexpectedshockstable = '';
+  estparexpectedshockstable += '<tr><td><select id="estparname' + estparrowindex + '" class="form-control input-sm" name="estparname" onchange="enableestvarcorr(' + estparrowindex + ')">';
+  estparexpectedshockstable += '<option disabled>Parameters</option>';
+  for (x in dynaremodel.parameters) {
+    estparexpectedshockstable += '<option value="' + x + '">' + dynaremodel.parameters[x]["longName"] + '</option>';
+  }
+
+  estparexpectedshockstable += '<option disabled>Exo variables</option>';
+  for (x in dynaremodel.exogenous) {
+    exovarcounter++;
+    estparexpectedshockstable += '<option value="' + exovarcounter + '">' + dynaremodel.exogenous[x]["longName"] + '</option>';
+  }
+  estparexpectedshockstable += "</select></td>";
+
+  estparexpectedshockstable += '<td><input type="text" class="form-control no-border input-sm" name="estparvalue' + estparrowindex + '" id="estparvalue' + estparrowindex + '" placeholder="Value"></td>';
+  estparexpectedshockstable += '<td><input type="text" class="form-control no-border input-sm" name="estparLbound' + estparrowindex + '" id="estparLbound' + estparrowindex + '" placeholder="L. Bound"></td>';
+  estparexpectedshockstable += '<td><input type="text" class="form-control no-border input-sm" name="estparUbound' + estparrowindex + '" id="estparUbound' + estparrowindex + '" placeholder="U. Bound"></td>';
+
+  estparexpectedshockstable += '<td><select id="estparprior' + estparrowindex + '" class="form-control input-sm" name="estparprior' + estparrowindex + '" onchange="enablebayesian(' + estparrowindex + ')"><option value="1" selected="selected">N/A</option><option value="2">beta_pdf</option><option value="3">gamma_pdf</option><option value="4">normal_pdf</option><option value="5">uniform_pdf</option><option value="6">inv_gamma_pdf</option><option value="7">inv_gamma1_pdf</option><option value="8">inv_gamma2_pdf</option><option value="9">weibull_pdf</option></td>';
+
+  estparexpectedshockstable += '<td><input type="text" class="form-control no-border input-sm" name="estparpriormean' + estparrowindex + '" id="estparpriormean' + estparrowindex + '" placeholder="Prior mean" disabled></td>';
+  estparexpectedshockstable += '<td><input type="text" class="form-control no-border input-sm" name="estparpriorstderr' + estparrowindex + '" id="estparpriorstderr' + estparrowindex + '" placeholder="Prior Std. Err" disabled></td>';
+
+  estparexpectedshockstable += '<td><input type="text" class="form-control no-border input-sm" name="estparprior3par' + estparrowindex + '" id="estparprior3par' + estparrowindex + '" placeholder="Prior 3rd param" disabled></td>';
+  estparexpectedshockstable += '<td><input type="text" class="form-control no-border input-sm" name="estparprior4par' + estparrowindex + '" id="estparprior4par' + estparrowindex + '" placeholder="Prior 4th param" disabled></td>';
+  estparexpectedshockstable += '<td><input type="text" class="form-control no-border input-sm" name="estparpriorscale' + estparrowindex + '" id="estparpriorscale' + estparrowindex + '" placeholder="Scale" disabled></td>';
+
+  exovarcounter = 999;
+  estparexpectedshockstable += '<td><select id="estparcorrvar' + estparrowindex + '" class="form-control input-sm" name="estparcorrvar' + estparrowindex + '" disabled>';
+  estparexpectedshockstable += '<option value="0">N/A</option>';
+  for (x in dynaremodel.exogenous) {
+    exovarcounter++;
+    estparexpectedshockstable += '<option value="' + exovarcounter + '">' + dynaremodel.exogenous[x]["longName"] + '</option>';
+  }
+  estparexpectedshockstable += "</select></td>";
+  estparexpectedshockstable += '<td><input type="button" value="X" onclick="estparSomeDeleteRowFunction(this,' + estparrowindex + ')" class="form-control no-border input-sm" name="estparremoveshock' + estparrowindex + '" id="estparremoveshock' + estparrowindex + '"></td></tr>';
+  $('#estpartable tbody').append(estparexpectedshockstable);
+  return false;
+});
+
+function estparSomeDeleteRowFunction(o, estparrowindex) {
+  var p = o.parentNode.parentNode;
+  p.parentNode.removeChild(p);
+  estparnum[estparrowindex] = 0;
+}
+
+function enablebayesian(shockindex) {
+  var selectedvalue = $("#estparprior" + shockindex).val();
+  if (selectedvalue < 2) {
+    $("#estparpriormean" + shockindex).attr('disabled', 'disabled');
+    $("#estparpriorstderr" + shockindex).attr('disabled', 'disabled');
+    $("#estparprior3par" + shockindex).attr('disabled', 'disabled');
+    $("#estparprior4par" + shockindex).attr('disabled', 'disabled');
+    $("#estparpriorscale" + shockindex).attr('disabled', 'disabled');
+  } else {
+    $("#estparpriormean" + shockindex).removeAttr('disabled');
+    $("#estparpriorstderr" + shockindex).removeAttr('disabled');
+    $("#estparprior3par" + shockindex).removeAttr('disabled');
+    $("#estparprior4par" + shockindex).removeAttr('disabled');
+    $("#estparpriorscale" + shockindex).removeAttr('disabled');
+  }
+}
+
+function enableestvarcorr(shockindex) {
+  var selectedvalue = $("#estparname" + shockindex).val();
+  if (selectedvalue < 1000) {
+    $("#estparcorrvar" + shockindex).val('0');
+    $("#estparcorrvar" + shockindex).attr('disabled', 'disabled');
+  } else {
+    $("#estparcorrvar" + shockindex).removeAttr('disabled');
+  }
+}
+
+
+$('#runestimation').click(async function () {
+
+
+  var estendonum = $('#estmodel_endonum').val();
+  var estparamnum = $('#estmodel_paramnum').val();
+
+  // var datafilepath = $('#estfile');
+  var datafilepath = document.getElementById("estfile");
+  var estssstatus = $('#estmodelsteadystatestatus').val();
+  var estssdescription = [];
+
+
+
+
+  //checking input file and extension
+  if (datafilepath.files.length == 0) {
+    $('.nav-tabs a[href="#estimsetuptable"]').tab('show');
+    popthis('Setup error.', 'You did not provide a data file. This action is mandatory.');
+    return (0);
+  } else {
+    var filename = datafilepath.files[0].name;
+    extension = filename.split('.').pop();
+    var allowedextensions = ['m', 'mat', 'xls', 'xlsx', 'csv'];
+    var extcheck = 0;
+    allowedextensions.forEach(function (myextension) {
+      if (extension == myextension) {
+        extcheck = 1;
+      }
+    });
+    if (extcheck == 0) {
+      $('.nav-tabs a[href="#estimsetuptable"]').tab('show');
+      popthis('Setup error.', 'The file you provided does not seem to be of the correct type. Please provide a file with one of the following extensions:.m, .mat, .xls, .xlsx, .csv.');
+      return (0);
+    }
+  }
+
+
+  // steady-state info check
+  if (estssstatus == 99) {
+    estsstext = $('#estSSblock').val();
+    if (estsstext.length == 0) {
+      $('.nav-tabs a[href="#estimsetuptable"]').tab('show');
+      popthis('Setup error.', 'Please provide a way to compute the steady-state.');
+      return (0);
+    }
+    if ($('#estissteadystateblock').is(":checked") == true) {
+      var estsstype = 1;
+    } else {
+      var estsstype = 2;
+    }
+    estssdescription.push({
+      'sstext': estsstext,
+      'sstype': parseInt(estsstype, 10)
+    });
+  }
+
+
+
+  // Observations table check
+
+  //observables
+  var obsglobalvaluescount = 0;
+  var obsattributeflag = [];
+  for (i = 0; i < estendonum; i++) {
+    obsattributeflag[i] = 0;
+  }
+  var obsindex;
+  var obsdescription = [];
+
+  var obsrowCount = $('#estobstable tr').length - 1; // careful this counts the th row as a row, thus the -1
+
+  if (obsrowCount > 0) {
+    // there are shocks in the table
+    obsglobalvaluescount = 1;
+
+    var obsxcond = 0;
+    var obsiter = 0;
+    var obscountshocks = 0;
+
+    while (obsxcond == 0) {
+      // we iterate over global estobsnum that kept track of observable indexes in any order they were entered
+      if (estobsnum[obsiter] == 1) {
+        // if estobsnum identifies a valid row in the table, we start further checks
+        obscountshocks = obscountshocks + 1;
+
+        // We fetch shock infos
+        obsindex = $('#estobsvarname' + obsiter.toString()).val();
+
+
+        //we check if the same observable has already been declared
+        if (obsattributeflag[obsindex] > 0) {
+          $('.nav-tabs a[href="#estimsetuptable"]').tab('show');
+          popthis('Setup error.', 'The observable variable on row ' + obscountshocks + ', has already been declared. Please enter each observable only once.');
+          return (0);
+        } else {
+          obsattributeflag[obsindex] = 1;
+        }
+
+
+
+        obsdescription.push({
+          'obsindex': parseInt(obsindex, 10)
+        });
+
+        //we count the number of this specific shock
+        // shocksflag[shockindex] = shocksflag[shockindex] + 1;
+      }
+      if (obscountshocks == obsrowCount) {
+        obsxcond = 1;
+      }
+      obsiter = obsiter + 1;
+    }
+  }
+
+
+  // estimated params table check
+
+  var parglobalvaluescount = 0;
+  var parattributeflag = [];
+  for (i = 0; i < estparamnum; i++) {
+    parattributeflag[i] = 0;
+  }
+  var parindex;
+  var pardescription = [];
+
+  var parpairs = [];
+
+  var parrowCount = $('#estpartable tr').length - 1; // careful this counts the th row as a row, thus the -1
+
+  if (parrowCount > 0) {
+    // there are parameters in the table
+    parglobalvaluescount = 1;
+
+    var parxcond = 0;
+    var pariter = 0;
+    var parcountshocks = 0;
+
+    console.log("parcountshocks");
+    console.log(parcountshocks);
+
+    var bayesiancount = 0;
+    var mlcount = 0;
+
+    while (parxcond == 0) {
+      // we iterate over global estparnum that kept track of shock indexes in any order they were entered
+      if (estparnum[pariter] == 1) {
+        // if estparnum identifies a valid row in the table, we start further checks
+        parcountshocks = parcountshocks + 1;
+
+        //we find the true row number of the current checked line in the table
+        var partablerow = $('#estparname' + pariter.toString()).closest('tr');
+        var partablerowindex = partablerow.index() + 1;
+
+
+        // We fetch parameter infos
+        parshockindex = $('#estparname' + pariter.toString()).val();
+        console.log('parshockindex');
+        console.log(parshockindex);
+
+        parinivalue = $('#estparvalue' + pariter.toString()).val();
+        parLbound = $('#estparLbound' + pariter.toString()).val();
+        parUbound = $('#estparUbound' + pariter.toString()).val();
+        parprior = $('#estparprior' + pariter.toString()).val();
+        parpriormean = $('#estparpriormean' + pariter.toString()).val();
+        parpriorstderr = $('#estparpriorstderr' + pariter.toString()).val();
+        parprior3par = $('#estparprior3par' + pariter.toString()).val();
+        parprior4par = $('#estparprior4par' + pariter.toString()).val();
+        parpriorscale = $('#estparpriorscale' + pariter.toString()).val();
+        // parcorrattributevalue = $("#estparcorrvar" + pariter.toString()).val();
+
+        parinivalue = parinivalue.trim();
+        parLbound = parLbound.trim();
+        parUbound = parUbound.trim();
+        parpriormean = parpriormean.trim();
+        parpriorstderr = parpriorstderr.trim();
+        parprior3par = parprior3par.trim();
+        parprior4par = parprior4par.trim();
+        parpriorscale = parpriorscale.trim();
+
+        // parassoshockindex = -10;
+        parassoshockindex = $('#estparcorrvar' + pariter.toString()).val();
+
+        console.log("parassoshockindex")
+        console.log(parassoshockindex)
+
+        if (parshockindex > 999) {
+          //we first validate the case of an exogenous variable been selected (and correlation issues)
+
+
+          if (parassoshockindex > 0) { //if correlation has been selected
+
+            if (parshockindex == parassoshockindex) {
+              $('.nav-tabs a[href="#estimparams"]').tab('show');
+              popthis('Variables error.', 'On row ' + partablerowindex + ', the correlation should be specified for separate variables.');
+              return (0);
+            }
+
+            // we verify if correlation has already been specified for any two same shocks
+            if (Number(parassoshockindex) > Number(parshockindex)) {
+              if (parpairs.indexOf(parshockindex + '-' + parassoshockindex) == -1) {
+                parpairs.push(parshockindex + '-' + parassoshockindex);
+              } else {
+                popthis('Variables error.', 'On row ' + partablerowindex + ', this covariance/correlation has already been specified between these variables.');
+                return (0);
+              }
+            } else {
+              if (parpairs.indexOf(parassoshockindex + '-' + parshockindex) == -1) {
+                parpairs.push(parassoshockindex + '-' + parshockindex);
+              } else {
+                popthis('Variables error.', 'On row ' + partablerowindex + ', this covariance/correlation has already been specified between these variables.');
+                return (0);
+              }
+            }
+
+          }
+        }
+
+        //Standard check for all parameters/variables
+
+        //Check if parameter declared twice
+        if (parassoshockindex < 1000) {
+          if (parattributeflag[parshockindex] > 0) {
+            popthis('Pameters error.', 'On row ' + partablerowindex + ', You have already specified attributes for this parameter/variable. Please add only one row per parameter/variable.');
+            return (0);
+          } else {
+            parattributeflag[parshockindex] = 1;
+          }
+        }
+
+        //}
+
+        var parvalueflag = 0;
+
+        // we validate the shock value
+        if (!(parinivalue == null || parinivalue == "")) {
+          if (!(IsNumeric(parinivalue))) {
+            if (!(parinivalue.toLowerCase() == "inf")) {
+              popthis('Parameter error.', 'The parameter value on row ' + partablerowindex + ' is not a number or inf.');
+              return (0);
+            } else {
+              parvalueflag = 1;
+            }
+
+          } else {
+            parvalueflag = 1;
+          }
+        }
+
+        // we validate the shock prior mean
+        if (parprior > 1) {
+          bayesiancount += 1;
+          if (!(parpriormean == null || parpriormean == "")) {
+            if (!(IsNumeric(parpriormean))) {
+              if (!(parpriormean.toLowerCase() == "inf")) {
+                popthis('Parameter error.', 'The parameter prior mean on row ' + partablerowindex + ' is not a number or inf.');
+                return (0);
+              } else {
+                parvalueflag = 1;
+              }
+            } else {
+              parvalueflag = 1;
+            }
+          }
+
+          if (!(parpriorstderr == null || parpriorstderr == "")) {
+            if (!(IsNumeric(parpriorstderr))) {
+              if (!(parpriorstderr.toLowerCase() == "inf")) {
+                popthis('Parameter error.', 'The prior stdErr value on row ' + partablerowindex + ' is not a number or inf.');
+                return (0);
+              }
+            }
+          } else {
+            popthis('Parameter error.', 'You did not specify a prior stdErr for parameter on row ' + partablerowindex + '. This information is mandatory if you specified a prior shape.');
+            return (0);
+          }
+
+          if (!(parprior3par == null || parprior3par == "")) {
+            if (!(IsNumeric(parprior3par))) {
+              if (!(parprior3par.toLowerCase() == "inf")) {
+                popthis('Parameter error.', 'The prior 3rd param value on row ' + partablerowindex + ' is not a number or inf.');
+                return (0);
+              }
+            }
+          }
+
+          if (!(parprior4par == null || parprior4par == "")) {
+            if (!(IsNumeric(parprior4par))) {
+              if (!(parprior4par.toLowerCase() == "inf")) {
+                popthis('Parameter error.', 'The prior 4rd param value on row ' + partablerowindex + ' is not a number or inf.');
+                return (0);
+              }
+            }
+          }
+
+          if (!(parpriorscale == null || parpriorscale == "")) {
+            if (!(IsNumeric(parpriorscale))) {
+              if (!(parpriorscale.toLowerCase() == "inf")) {
+                popthis('Parameter error.', 'The prior scale value on row ' + partablerowindex + ' is not a number or inf.');
+                return (0);
+              }
+            }
+          }
+        } else {
+          mlcount += 1;
+        }
+
+
+        if (parvalueflag == 0) {
+          popthis('Parameter error.', 'You did not specify a value or a prior mean for parameter on row ' + partablerowindex + '. One of these information is mandatory.');
+          return (0);
+        }
+
+
+        if (!(parLbound == null || parLbound == "")) {
+          if (!(IsNumeric(parLbound))) {
+            if (!(parLbound.toLowerCase() == "inf")) {
+              popthis('Parameter error.', 'The lower bound value on row ' + partablerowindex + ' is not a number or inf.');
+              return (0);
+            }
+          }
+        }
+
+        if (!(parUbound == null || parUbound == "")) {
+          if (!(IsNumeric(parUbound))) {
+            if (!(parUbound.toLowerCase() == "inf")) {
+              popthis('Parameter error.', 'The upper bound value on row ' + partablerowindex + ' is not a number or inf.');
+              return (0);
+            }
+          }
+        }
+
+        console.log('bayesiancount');
+        console.log(bayesiancount);
+        console.log(mlcount);
+
+        if ((bayesiancount > 0) && (mlcount > 0)) {
+          popthis('Parameter error.', 'Estimation must be either fully ML or fully Bayesian. Please declare only variables/parameters with priors or only variables/parameters without priors.');
+          return (0);
+
+
+        }
+
+        
+
+
+        pardescription.push({
+          'parshockindex': parseInt(parshockindex, 10),
+          'parinivalue': (parinivalue.toLowerCase()=='inf') ? (parinivalue.toLowerCase()):(parseFloat(parinivalue, 10)),
+          'parLbound': (parLbound.toLowerCase()=='inf') ? (parLbound.toLowerCase()):(parseFloat(parLbound, 10)),
+          'parUbound': (parUbound.toLowerCase()=='inf') ? (parUbound.toLowerCase()):(parseFloat(parUbound, 10)),
+          'parprior': parseInt(parprior, 10),
+          'parpriormean': (parpriormean.toLowerCase()=='inf') ? (parpriormean.toLowerCase()):(parseFloat(parpriormean, 10)),
+          'parpriorstderr': (parpriorstderr.toLowerCase()=='inf') ? (parpriorstderr.toLowerCase()):(parseFloat(parpriorstderr, 10)),
+          'parprior3par': (parprior3par.toLowerCase()=='inf') ? (parprior3par.toLowerCase()):(parseFloat(parprior3par, 10)),
+          'parprior4par': (parprior4par.toLowerCase()=='inf') ? (parprior4par.toLowerCase()):(parseFloat(parprior4par, 10)),
+          'parpriorscale': (parpriorscale.toLowerCase()=='inf') ? (parpriorscale.toLowerCase()):(parseFloat(parpriorscale, 10)),
+          'parassoshockindex': parseInt(parassoshockindex, 10)
+        });
+
+        //we count the number of this specific shock
+        // shocksflag[shockindex] = shocksflag[parshockindex] + 1;
+      }
+      if (parcountshocks == parrowCount) {
+        parxcond = 1;
+      }
+      pariter = pariter + 1;
+    }
+
+
+  }
+
+
+  if (obsglobalvaluescount == 0) {
+    $('.nav-tabs a[href="#estimsetuptable"]').tab('show');
+    popthis('Estimation input error.', 'You have submitted no observable variable(s) for the estimation. Please add observable variable(s) and retry.');
+    return (0);
+  }
+
+  if (parglobalvaluescount == 0) {
+    $('.nav-tabs a[href="#estimparams"]').tab('show');
+    popthis('Estimation input error.', 'You have submitted no parameters/variables to be estimated. Please add observable variable(s) and retry.');
+    return (0);
+  }
+
+
+  // options check
+
+  parnobs = $('#estimopt_nobs').val();
+  parmhreplic = $('#estimopt_mh_replic').val();
+  parmhnblocks = $('#estimopt_mh_nblocks').val();
+  parmhjscale = $('#estimopt_mh_jscale').val();
+
+  if (!(parnobs == null || parnobs == "")) {
+    if (!(Number.isInteger(Number(parnobs)))) {
+      $('.nav-tabs a[href="#estimoptions"]').tab('show');
+      popthis('Options error.', 'Number of observations should be an integer number.');
+      return (0);
+    }
+    if (Number(parnobs) < 0) {
+      $('.nav-tabs a[href="#estimoptions"]').tab('show');
+      popthis('Options error.', 'Number of observations cannot be negative.');
+      return (0);
+    }
+  }
+
+  if (!(parmhreplic == null || parmhreplic == "")) {
+    if (!(Number.isInteger(Number(parmhreplic)))) {
+      $('.nav-tabs a[href="#estimoptions"]').tab('show');
+      popthis('Options error.', 'Number of replications should be an integer number.');
+      return (0);
+    }
+    if (Number(parmhreplic) < 0) {
+      $('.nav-tabs a[href="#estimoptions"]').tab('show');
+      popthis('Options error.', 'Number of replications cannot be negative.');
+      return (0);
+    }
+  }
+
+  if (!(parmhnblocks == null || parmhnblocks == "")) {
+    if (!(Number.isInteger(Number(parmhnblocks)))) {
+      $('.nav-tabs a[href="#estimoptions"]').tab('show');
+      popthis('Options error.', 'Number of blocks should be an integer number.');
+      return (0);
+    }
+    if (Number(parmhnblocks) < 0) {
+      $('.nav-tabs a[href="#estimoptions"]').tab('show');
+      popthis('Options error.', 'Number of blocks cannot be negative.');
+      return (0);
+    }
+  }
+
+  if (!(parmhjscale == null || parmhjscale == "")) {
+    if (!(IsNumeric(parmhjscale))) {
+      $('.nav-tabs a[href="#estimoptions"]').tab('show');
+      popthis('Options error.', 'Scale parameter is not a number.');
+      return (0);
+    }
+  }
+
+
+  //we post to the server
+
+  console.log('Ready to post variables');
+
+  //getting the file to be sent
+
+  // var formData = new FormData(document.getElementById("estfile").files[0]);
+  // formData.append("CustomField", "This is some extra data");
+
+  var fd = new FormData();
+  var re = /(?:\.([^.]+))?$/;
+  fd.append("file", document.getElementById('estfile').files[0]);
+  fd.append("filename", $('#codehash').val());
+  fd.append("filetype", re.exec(document.getElementById('estfile').files[0].name)[1]);
+
+  
+
+  // console.log(fd)
+  // console.log(...fd)
+  // console.log(fd.filename)
+  // console.log(fd.filetype)
+
+  var estimationval = {
+    'modelhash': $('#codehash').val(),
+    'parnobs': parseInt(parnobs, 10),
+    'parmhreplic': parseInt(parmhreplic, 10),
+    'parmhnblocks': parseInt(parmhnblocks, 10),
+    'parmhjscale': parseInt(parmhjscale, 10),
+    'ssstatus': parseInt(estssstatus, 10),
+    'ssdescription': estssdescription,
+    'obsdescription': obsdescription,
+    'pardescription': pardescription,
+    'datafiletype': re.exec(document.getElementById('estfile').files[0].name)[1],
+    'accesstype': 'runestimation'
+  };
+
+  // var estimationvaldata = JSON.stringify(estimationval);
+  $("#outputtable").empty();
+  $("#outputtable2").empty();
+  $("#plotbtn").empty();
+  $("#plotbox").empty();
+  $('#estimModal').modal('hide');
+  var div = document.createElement('div');
+  div.className = 'loader';
+  div.innerHTML = '';
+  document.getElementById('inner').appendChild(div);
+  $('.nav-tabs a[href="#console"]').tab('show');
+
+  console.log(estimationval);
+
+        // calling the 'node side'
+        try {
+          var resp = await runsaveestimationfilenode(fd);
+        } catch (error) {
+          console.log(error)
+          if (error.status == 2) {
+            $('.nav-tabs a[href="#console"]').tab('show');
+            $("#inner").empty();
+            document.getElementById("inner").innerHTML = '<p style="color:red;">Matlab errors found. See console.</p>';
+            return false;
+  
+          } else if (error.status == 3) {
+            currentout = currentout + resp.data.message;
+            $("textarea#preprocessorout").val(currentout + '\n \n The preprocessor could nor process your input. Please check the extra steady-state information you provided.');
+            $('.nav-tabs a[href="#console"]').tab('show');
+            $("#inner").empty();
+            document.getElementById("inner").innerHTML = '<p style="color:red;">Preprocessor errors found. See console.</p>';
+            return false;
+          }
+        }
+        console.log('ok file sent')
+
+        try {
+          var resp = await runestimationnode(JSON.stringify(estimationval));
+        } catch (error) {
+          console.log(error)
+          if (error.status == 2) {
+            $('.nav-tabs a[href="#console"]').tab('show');
+            $("#inner").empty();
+            document.getElementById("inner").innerHTML = '<p style="color:red;">Matlab errors found. See console.</p>';
+            return false;
+  
+          } else if (error.status == 3) {
+            currentout = currentout + resp.data.message;
+            $("textarea#preprocessorout").val(currentout + '\n \n The preprocessor could nor process your input. Please check the extra steady-state information you provided.');
+            $('.nav-tabs a[href="#console"]').tab('show');
+            $("#inner").empty();
+            document.getElementById("inner").innerHTML = '<p style="color:red;">Preprocessor errors found. See console.</p>';
+            return false;
+          }
+        }
+
+
+
+  return false;
+
+
+
+});
+
+
+
+ipcest.on('estimationfinish', (event, arg) => {
+
+  async function finishestimation() {
+
+
+    scrolltextarea();
+    $('#MHmodal').modal('hide');
+
+    $('.nav-tabs a[href="#output"]').tab('show');
+
+    try {
+      estmatlabdata = await loadjsonfile('estimout.JSON');
+    } catch (error) {
+      return popthis('Error', 'Unable to open estimout.JSON to process:' + error);
+    }
+
+
+    if (estmatlabdata.estimtypeflag == 0) {
+      //Reporting ML estimation
+
+      var estbl1 = `
+        <section>
+        <h2>Results from Maximum Likelihood Estimation</h2>
+        <table class="table table-striped table-hover">
+        <thead>
+        <tr>
+        <th>#</th>
+        <th>Variable/parameter</th>
+        <th>Estimate</th>
+        <th>Std. Dev</th>
+        <th>t-stat</th>
+        </tr>
+        </thead>
+        <tbody>
+        `;
+
+
+
+      if ("parameters" in estmatlabdata.mle_mode) {
+        estbl1 += '<tr><th id="par" colspan="5" scope="colgroup">Parameters</th></tr>';
+        y = 0;
+        for (x in estmatlabdata.mle_mode.parameters) {
+          y = y + 1;
+          estbl1 += '<tr><th scope="row">' + y + '</th>';
+
+          estbl1 += "<td>" + x + "</td>";
+          estbl1 += "<td>" + estmatlabdata.mle_mode.parameters[x] + "</td>";
+          estbl1 += "<td>" + estmatlabdata.mle_std_at_mode.parameters[x] + "</td>";
+          estbl1 += "<td></td></tr>";
+        }
+      }
+
+      if ("shocks_std" in estmatlabdata.mle_mode) {
+        estbl1 += '<tr><th id="par" colspan="5" scope="colgroup">Std. Dev. of shocks</th></tr>';
+        y = 0;
+        for (x in estmatlabdata.mle_mode.shocks_std) {
+          y = y + 1;
+          estbl1 += '<tr><th scope="row">' + y + '</th>';
+
+          estbl1 += "<td>" + x + "</td>";
+          estbl1 += "<td>" + estmatlabdata.mle_mode.shocks_std[x] + "</td>";
+          estbl1 += "<td>" + estmatlabdata.mle_std_at_mode.shocks_std[x] + "</td>";
+          estbl1 += "<td></td></tr>";
+        }
+      }
+
+      if ("shocks_corr" in estmatlabdata.mle_mode) {
+        estbl1 += '<tr><th id="par" colspan="5" scope="colgroup">Correlation of shocks</th></tr>';
+        y = 0;
+        for (x in estmatlabdata.mle_mode.shocks_corr) {
+          y = y + 1;
+          estbl1 += '<tr><th scope="row">' + y + '</th>';
+
+          estbl1 += "<td>" + x + "</td>";
+          estbl1 += "<td>" + estmatlabdata.mle_mode.shocks_corr[x] + "</td>";
+          estbl1 += "<td>" + estmatlabdata.mle_std_at_mode.shocks_corr[x] + "</td>";
+          estbl1 += "<td></td></tr>";
+        }
+      }
+
+
+      estbl1 += "</tbody></table></section>";
+
+
+      var plotdropdown = `
+    <section>
+    <h2>Plots</h2>
+    <div class="btn-group" role="group" aria-label="...">
+    <div class="btn-group" role="group">
+      <button id="plotbtn" class="btn btn-primary btn-lg dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
+        Select graph <span class="caret"></span><span class="sr-only">Toggle Dropdown</span>
+      </button>
+      <ul class="dropdown-menu" aria-labelledby="plotbtn">
+      <li class="dropdown-header">Smoothed shocks:</li>`;
+
+      y = 0;
+      if ("SmoothedShocks" in estmatlabdata) {
+        for (x in estmatlabdata.SmoothedShocks) {
+          plotdropdown += '<li onclick="estplotsmoothedshocks(&quot;' + x + '&quot;)"><a href="#stophere">' + x + '</a></li>';
+          if (y == 0) {
+            var firstname = x;
+            y = 1;
+          }
+        }
+      }
+
+      plotdropdown += '<li class="dropdown-header">Historical and smoothed variables:</li>';
+
+      if ("SmoothedObs" in estmatlabdata) {
+        for (x in estmatlabdata.SmoothedObs) {
+          plotdropdown += '<li onclick="estplotsmoothedvars(&quot;' + x + '&quot;)"><a href="#stophere">' + x + '</a></li>';
+        }
+      }
+
+      plotdropdown += '</ul></div>';
+      plotdropdown += `
+    <div class="btn-group" role="group">
+    <button id="exportbtn" class="btn btn-primary btn-lg dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
+      Export data <span class="caret"></span><span class="sr-only">Toggle Dropdown</span>
+    </button>
+    <ul class="dropdown-menu" aria-labelledby="exportbtn">
+    <li class="dropdown-header">Select file type:</li>
+    <li onclick="exportfile(&quot;json&quot;)"><a href="#stophere">Export to JSON</a></li>
+    <li onclick="exportfile(&quot;csv&quot;)"><a href="#stophere">Export to CSV</a></li>
+    </ul>
+    </div>`;
+
+      plotdropdown += `
+      </div>
+      </section>
+      `;
+      document.getElementById("plotbtn").innerHTML = plotdropdown;
+
+
+      estplotsmoothedshocks(firstname);
+
+    }
+
+    var priorname = ['dummy', 'beta_pdf', 'gamma_pdf', 'normal_pdf', 'inv_gamma_pdf', 'uniform_pdf', 'inv_gamma2_pdf', 'dummy', 'weibull_pdf'];
+
+    if (estmatlabdata.estimtypeflag == 1) {
+      //Reporting Bayesian estimation
+
+
+      var estbl1 = `
+      <section>
+      <h2>Results from Posterior Estimation</h2>
+      <table class="table table-striped table-hover">
+      <thead>
+      <tr>
+      <th>#</th>
+      <th>Variable/parameter</th>
+      <th>Prior mean</th>
+      <th>Mode</th>
+      <th>Std. Dev</th>
+      <th>Prior</th>
+      <th>Pstdev</th>
+      </tr>
+      </thead>
+      <tbody>
+      `;
+
+
+      if ("param_vals" in estmatlabdata) {
+        estbl1 += '<tr><th id="par" colspan="7" scope="colgroup">Parameters</th></tr>';
+        y = 0;
+        for (x in estmatlabdata.posterior_mode.parameters) {
+          estbl1 += '<tr><th scope="row">' + (y + 1) + '</th>';
+          estbl1 += "<td>" + x + "</td>";
+
+          if (Array.isArray(estmatlabdata.param_vals[0])) {
+            estbl1 += "<td>" + estmatlabdata.param_vals[y][5] + "</td>";
+          } else {
+            estbl1 += "<td>" + estmatlabdata.param_vals[5] + "</td>";
+          }
+
+          estbl1 += "<td>" + estmatlabdata.posterior_mode.parameters[x] + "</td>";
+          estbl1 += "<td>" + estmatlabdata.posterior_std.parameters[x] + "</td>";
+          if (Array.isArray(estmatlabdata.param_vals[0])) {
+            estbl1 += "<td>" + priorname[estmatlabdata.param_vals[y][4]] + "</td>";
+            estbl1 += "<td>" + estmatlabdata.param_vals[y][6] + "</td>";
+          } else {
+            estbl1 += "<td>" + priorname[estmatlabdata.param_vals[4]] + "</td>";
+            estbl1 += "<td>" + estmatlabdata.param_vals[6] + "</td>";
+          }
+          estbl1 += "<td></td></tr>";
+          y = y + 1;
+        }
+      }
+
+      if ("var_exo" in estmatlabdata) {
+        estbl1 += '<tr><th id="par" colspan="7" scope="colgroup">Standard deviation of shocks</th></tr>';
+        y = 0;
+        for (x in estmatlabdata.posterior_mode.shocks_std) {
+          estbl1 += '<tr><th scope="row">' + (y + 1) + '</th>';
+          estbl1 += "<td>" + x + "</td>";
+
+          if (Array.isArray(estmatlabdata.var_exo[0])) {
+            estbl1 += "<td>" + estmatlabdata.var_exo[y][5] + "</td>";
+          } else {
+            estbl1 += "<td>" + estmatlabdata.var_exo[5] + "</td>";
+          }
+          estbl1 += "<td>" + estmatlabdata.posterior_mode.shocks_std[x] + "</td>";
+          estbl1 += "<td>" + estmatlabdata.posterior_std.shocks_std[x] + "</td>";
+          if (Array.isArray(estmatlabdata.var_exo[0])) {
+            estbl1 += "<td>" + priorname[estmatlabdata.var_exo[y][4]] + "</td>";
+            estbl1 += "<td>" + estmatlabdata.var_exo[y][6] + "</td>";
+          } else {
+            estbl1 += "<td>" + priorname[estmatlabdata.var_exo[4]] + "</td>";
+            estbl1 += "<td>" + estmatlabdata.var_exo[6] + "</td>";
+          }
+          estbl1 += "<td></td></tr>";
+          y = y + 1;
+        }
+      }
+
+      if ("corrx" in estmatlabdata) {
+        estbl1 += '<tr><th id="par" colspan="7" scope="colgroup">Correlation of shocks</th></tr>';
+        y = 0;
+        for (x in estmatlabdata.posterior_mode.shocks_corr) {
+          estbl1 += '<tr><th scope="row">' + (y + 1) + '</th>';
+          estbl1 += "<td>" + x + "</td>";
+
+          if (Array.isArray(estmatlabdata.corrx[0])) {
+            estbl1 += "<td>" + estmatlabdata.corrx[y][6] + "</td>";
+          } else {
+            estbl1 += "<td>" + estmatlabdata.corrx[6] + "</td>";
+          }
+          estbl1 += "<td>" + estmatlabdata.posterior_mode.shocks_corr[x] + "</td>";
+          estbl1 += "<td>" + estmatlabdata.posterior_std.shocks_corr[x] + "</td>";
+          if (Array.isArray(estmatlabdata.corrx[0])) {
+            estbl1 += "<td>" + priorname[estmatlabdata.corrx[y][5]] + "</td>";
+            estbl1 += "<td>" + estmatlabdata.corrx[y][7] + "</td>";
+          } else {
+            estbl1 += "<td>" + priorname[estmatlabdata.corrx[5]] + "</td>";
+            estbl1 += "<td>" + estmatlabdata.corrx[7] + "</td>";
+          }
+          estbl1 += "<td></td></tr>";
+          y = y + 1;
+        }
+      }
+
+      estbl1 += "</tbody></table></section>";
+
+
+
+      var estbl2 = `
+      <section>
+      <h2>Estimation Results</h2>
+      <table class="table table-striped table-hover">
+      <thead>
+      <tr>
+      <th>#</th>
+      <th>Variable/parameter</th>
+      <th>Prior mean</th>
+      <th>Post. mean</th>
+      <th>90% HPD int. (inf)</th>
+      <th>90% HPD int. (sup)</th>
+      <th>Prior</th>
+      <th>Pstdev</th>
+      </tr>
+      </thead>
+      <tbody>
+      `;
+
+      if ("param_vals" in estmatlabdata) {
+        estbl2 += '<tr><th id="par" colspan="8" scope="colgroup">Parameters</th></tr>';
+        y = 0;
+        for (x in estmatlabdata.posterior_mean.parameters) {
+          estbl2 += '<tr><th scope="row">' + (y + 1) + '</th>';
+          estbl2 += "<td>" + x + "</td>";
+
+          if (Array.isArray(estmatlabdata.param_vals[0])) {
+            estbl2 += "<td>" + estmatlabdata.param_vals[y][5] + "</td>";
+          } else {
+            estbl2 += "<td>" + estmatlabdata.param_vals[5] + "</td>";
+          }
+          estbl2 += "<td>" + estmatlabdata.posterior_mean.parameters[x] + "</td>";
+          estbl2 += "<td>" + estmatlabdata.posterior_hpdinf.parameters[x] + "</td>";
+          estbl2 += "<td>" + estmatlabdata.posterior_hpdsup.parameters[x] + "</td>";
+
+          if (Array.isArray(estmatlabdata.param_vals[0])) {
+            estbl2 += "<td>" + priorname[estmatlabdata.param_vals[y][4]] + "</td>";
+            estbl2 += "<td>" + estmatlabdata.param_vals[y][6] + "</td>";
+          } else {
+            estbl2 += "<td>" + priorname[estmatlabdata.param_vals[4]] + "</td>";
+            estbl2 += "<td>" + estmatlabdata.param_vals[6] + "</td>";
+          }
+          estbl2 += "<td></td></tr>";
+          y = y + 1;
+        }
+      }
+
+      if ("var_exo" in estmatlabdata) {
+        estbl2 += '<tr><th id="par" colspan="8" scope="colgroup">Standard deviation of shocks</th></tr>';
+        y = 0;
+        for (x in estmatlabdata.posterior_mean.shocks_std) {
+          estbl2 += '<tr><th scope="row">' + (y + 1) + '</th>';
+          estbl2 += "<td>" + x + "</td>";
+          // estbl2+="<td>"+estmatlabdata.exo_names[y]+"</td>";
+          if (Array.isArray(estmatlabdata.var_exo[0])) {
+            estbl2 += "<td>" + estmatlabdata.var_exo[y][5] + "</td>";
+          } else {
+            estbl2 += "<td>" + estmatlabdata.var_exo[5] + "</td>";
+          }
+
+          estbl2 += "<td>" + estmatlabdata.posterior_mean.shocks_std[x] + "</td>";
+          estbl2 += "<td>" + estmatlabdata.posterior_hpdinf.shocks_std[x] + "</td>";
+          estbl2 += "<td>" + estmatlabdata.posterior_hpdsup.shocks_std[x] + "</td>";
+
+          if (Array.isArray(estmatlabdata.var_exo[0])) {
+            estbl2 += "<td>" + priorname[estmatlabdata.var_exo[y][4]] + "</td>";
+            estbl2 += "<td>" + estmatlabdata.var_exo[y][6] + "</td>";
+          } else {
+            estbl2 += "<td>" + priorname[estmatlabdata.var_exo[4]] + "</td>";
+            estbl2 += "<td>" + estmatlabdata.var_exo[6] + "</td>";
+          }
+          estbl2 += "<td></td></tr>";
+          y = y + 1;
+        }
+      }
+
+      if ("corrx" in estmatlabdata) {
+        estbl2 += '<tr><th id="par" colspan="8" scope="colgroup">Correlation of shocks</th></tr>';
+        y = 0;
+        for (x in estmatlabdata.posterior_mean.shocks_corr) {
+          estbl2 += '<tr><th scope="row">' + (y + 1) + '</th>';
+          estbl2 += "<td>" + x + "</td>";
+          // estbl2+="<td>"+estmatlabdata.exo_names[y]+"</td>";
+          if (Array.isArray(estmatlabdata.corrx[0])) {
+            estbl2 += "<td>" + estmatlabdata.corrx[y][6] + "</td>";
+          } else {
+            estbl2 += "<td>" + estmatlabdata.corrx[6] + "</td>";
+          }
+
+          estbl2 += "<td>" + estmatlabdata.posterior_mean.shocks_corr[x] + "</td>";
+          estbl2 += "<td>" + estmatlabdata.posterior_hpdinf.shocks_corr[x] + "</td>";
+          estbl2 += "<td>" + estmatlabdata.posterior_hpdsup.shocks_corr[x] + "</td>";
+
+          if (Array.isArray(estmatlabdata.corrx[0])) {
+            estbl2 += "<td>" + priorname[estmatlabdata.corrx[y][5]] + "</td>";
+            estbl2 += "<td>" + estmatlabdata.corrx[y][7] + "</td>";
+          } else {
+            estbl2 += "<td>" + priorname[estmatlabdata.corrx[5]] + "</td>";
+            estbl2 += "<td>" + estmatlabdata.corrx[7] + "</td>";
+          }
+          estbl2 += "<td></td></tr>";
+          y = y + 1;
+        }
+      }
+
+      estbl2 += "</tbody></table></section>";
+
+
+      var plotdropdown = `
+    <section>
+    <h2>Plots</h2>
+    <div class="btn-group" role="group" aria-label="...">
+    <div class="btn-group" role="group">
+      <button id="plotbtn" class="btn btn-primary btn-lg dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
+        Select graph <span class="caret"></span><span class="sr-only">Toggle Dropdown</span>
+      </button>
+      <ul class="dropdown-menu" aria-labelledby="plotbtn">
+      <li class="dropdown-header">Priors:</li>`;
+
+      //plotting priors
+      y = 0;
+      if ("parameters" in estmatlabdata.prior_density) {
+        for (x in estmatlabdata.prior_density.parameters) {
+          plotdropdown += '<li onclick="estplotpriors(&quot;' + x + '&quot;,0)"><a href="#stophere">' + x + '</a></li>';
+          if (y == 0) {
+            var firstname = x;
+            var firsttype = 0;
+            y = 1;
+          }
+        }
+      }
+
+      if ("shocks_std" in estmatlabdata.prior_density) {
+        for (x in estmatlabdata.prior_density.shocks_std) {
+          plotdropdown += '<li onclick="estplotpriors(&quot;' + x + '&quot;,1)"><a href="#stophere">' + x + '</a></li>';
+          if (y == 0) {
+            var firstname = x;
+            var firsttype = 1;
+            y = 1;
+          }
+        }
+      }
+
+      if ("shocks_corr" in estmatlabdata.prior_density) {
+        for (x in estmatlabdata.prior_density.shocks_corr) {
+          plotdropdown += '<li onclick="estplotpriors(&quot;' + x + '&quot;,2)"><a href="#stophere">' + x + '</a></li>';
+        }
+      }
+
+      //plotting priors+posteriors
+      plotdropdown += '<li class="dropdown-header">Priors and posteriors:</li>';
+
+      if ("parameters" in estmatlabdata.posterior_density) {
+        for (x in estmatlabdata.posterior_density.parameters) {
+          plotdropdown += '<li onclick="estplotposteriors(&quot;' + x + '&quot;,0)"><a href="#stophere">' + x + '</a></li>';
+        }
+      }
+
+      if ("shocks_std" in estmatlabdata.posterior_density) {
+        for (x in estmatlabdata.posterior_density.shocks_std) {
+          plotdropdown += '<li onclick="estplotposteriors(&quot;' + x + '&quot;,1)"><a href="#stophere">' + x + '</a></li>';
+        }
+      }
+
+      if ("shocks_corr" in estmatlabdata.posterior_density) {
+        for (x in estmatlabdata.posterior_density.shocks_corr) {
+          plotdropdown += '<li onclick="estplotposteriors(&quot;' + x + '&quot;,2)"><a href="#stophere">' + x + '</a></li>';
+        }
+      }
+
+      plotdropdown += '<li class="dropdown-header">Smoothed shocks:</li>';
+
+      if ("SmoothedShocks" in estmatlabdata) {
+        for (x in estmatlabdata.SmoothedShocks) {
+          plotdropdown += '<li onclick="estplotsmoothedshocks(&quot;' + x + '&quot;)"><a href="#stophere">' + x + '</a></li>';
+        }
+      }
+
+      plotdropdown += '<li class="dropdown-header">Historical and smoothed variables:</li>';
+
+      if ("SmoothedObs" in estmatlabdata) {
+        for (x in estmatlabdata.SmoothedObs) {
+          plotdropdown += '<li onclick="estplotsmoothedvars(&quot;' + x + '&quot;)"><a href="#stophere">' + x + '</a></li>';
+        }
+      }
+
+
+
+
+      plotdropdown += '</ul></div>';
+      plotdropdown += `
+    <div class="btn-group" role="group">
+    <button id="exportbtn" class="btn btn-primary btn-lg dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
+      Export data <span class="caret"></span><span class="sr-only">Toggle Dropdown</span>
+    </button>
+    <ul class="dropdown-menu" aria-labelledby="exportbtn">
+    <li class="dropdown-header">Select file type:</li>
+    <li onclick="exportfile(&quot;json&quot;)"><a href="#stophere">Export to JSON</a></li>
+    <li onclick="exportfile(&quot;csv&quot;)"><a href="#stophere">Export to CSV</a></li>
+    </ul>
+    </div>`;
+
+      plotdropdown += `
+      </div>
+      </section>
+      `;
+      document.getElementById("plotbtn").innerHTML = plotdropdown;
+
+
+      estplotpriors(firstname, firsttype);
+
+    }
+
+
+
+
+
+
+    $("#inner").empty();
+    document.getElementById("outputtable").innerHTML = estbl1;
+
+    if (estmatlabdata.estimtypeflag == 1) {
+      document.getElementById("outputtable2").innerHTML = estbl2;
+    }
+
+  }
+
+  finishestimation();
+
+});
+
+function estplotpriors(plotvar, priortype) {
+
+  if (priortype == 0) {
+    xvar = [];
+    yvar = [];
+    if ("parameters" in estmatlabdata.prior_density) {
+      for (i = 0; i < estmatlabdata.prior_density.parameters[plotvar].length; i++) {
+        xvar.push(estmatlabdata.prior_density.parameters[plotvar][i][0]);
+        yvar.push(estmatlabdata.prior_density.parameters[plotvar][i][1]);
+      }
+      var trace1 = {
+        x: xvar,
+        y: yvar,
+        line: {
+          color: 'rgb(182, 179, 179)',
+          width: 3
+        }
+      };
+      var data = [trace1];
+      var layout = {
+        title: plotvar,
+        xaxis: {
+          title: ''
+        },
+        yaxis: {
+          title: "Density"
+        }
+      };
+    }
+  }
+
+  if (priortype == 1) {
+    xvar = [];
+    yvar = [];
+    if ("shocks_std" in estmatlabdata.prior_density) {
+      for (i = 0; i < estmatlabdata.prior_density.shocks_std[plotvar].length; i++) {
+        xvar.push(estmatlabdata.prior_density.shocks_std[plotvar][i][0]);
+        yvar.push(estmatlabdata.prior_density.shocks_std[plotvar][i][1]);
+      }
+      var trace1 = {
+        x: xvar,
+        y: yvar,
+        line: {
+          color: 'rgb(182, 179, 179)',
+          width: 3
+        }
+      };
+      var data = [trace1];
+      var layout = {
+        title: 'SE_' + plotvar,
+        xaxis: {
+          title: ''
+        },
+        yaxis: {
+          title: "Density"
+        }
+      };
+    }
+  }
+
+  if (priortype == 2) {
+    xvar = [];
+    yvar = [];
+    if ("shocks_corr" in estmatlabdata.prior_density) {
+      for (i = 0; i < estmatlabdata.prior_density.shocks_corr[plotvar].length; i++) {
+        xvar.push(estmatlabdata.prior_density.shocks_corr[plotvar][i][0]);
+        yvar.push(estmatlabdata.prior_density.shocks_corr[plotvar][i][1]);
+      }
+      var trace1 = {
+        x: xvar,
+        y: yvar,
+        line: {
+          color: 'rgb(182, 179, 179)',
+          width: 3
+        }
+      };
+      var data = [trace1];
+      var layout = {
+        title: 'CC_' + plotvar,
+        xaxis: {
+          title: ''
+        },
+        yaxis: {
+          title: "Density"
+        }
+      };
+    }
+  }
+
+  Plotly.newPlot('plotbox', data, layout);
+
+}
+
+function estplotposteriors(plotvar, priortype) {
+
+  if (priortype == 0) {
+    xvar = [];
+    yvar = [];
+    x2var = [];
+    y2var = [];
+    if ("parameters" in estmatlabdata.prior_density) {
+      for (i = 0; i < estmatlabdata.prior_density.parameters[plotvar].length; i++) {
+        xvar.push(estmatlabdata.prior_density.parameters[plotvar][i][0]);
+        yvar.push(estmatlabdata.prior_density.parameters[plotvar][i][1]);
+      }
+      for (i = 0; i < estmatlabdata.posterior_density.parameters[plotvar].length; i++) {
+        x2var.push(estmatlabdata.posterior_density.parameters[plotvar][i][0]);
+        y2var.push(estmatlabdata.posterior_density.parameters[plotvar][i][1]);
+      }
+      var trace1 = {
+        x: xvar,
+        y: yvar,
+        name: 'Prior',
+        line: {
+          color: 'rgb(182, 179, 179)',
+          width: 3
+        }
+      };
+      var trace2 = {
+        x: x2var,
+        y: y2var,
+        name: 'Posterior',
+        line: {
+          color: 'rgb(0, 0, 0)',
+          width: 3
+        }
+      };
+
+
+      var data = [trace1, trace2];
+      var layout = {
+        title: plotvar,
+        xaxis: {
+          title: ''
+        },
+        yaxis: {
+          title: "Density"
+        },
+        shapes: [{
+          type: 'line',
+          x0: estmatlabdata.posterior_mode.parameters[plotvar],
+          y0: 0,
+          x1: estmatlabdata.posterior_mode.parameters[plotvar],
+          y1: Math.max(...trace2.y),
+          line: {
+            color: 'rgb(25, 253, 2)',
+            width: 2,
+            dash: 'dot'
+          }
+        }]
+      };
+    }
+  }
+
+  if (priortype == 1) {
+    xvar = [];
+    yvar = [];
+    x2var = [];
+    y2var = [];
+    if ("shocks_std" in estmatlabdata.prior_density) {
+      for (i = 0; i < estmatlabdata.prior_density.shocks_std[plotvar].length; i++) {
+        xvar.push(estmatlabdata.prior_density.shocks_std[plotvar][i][0]);
+        yvar.push(estmatlabdata.prior_density.shocks_std[plotvar][i][1]);
+      }
+      for (i = 0; i < estmatlabdata.posterior_density.shocks_std[plotvar].length; i++) {
+        x2var.push(estmatlabdata.posterior_density.shocks_std[plotvar][i][0]);
+        y2var.push(estmatlabdata.posterior_density.shocks_std[plotvar][i][1]);
+      }
+      var trace1 = {
+        x: xvar,
+        y: yvar,
+        name: 'Prior',
+        line: {
+          color: 'rgb(182, 179, 179)',
+          width: 3
+        }
+      };
+      var trace2 = {
+        x: x2var,
+        y: y2var,
+        name: 'Posterior',
+        line: {
+          color: 'rgb(0, 0, 0)',
+          width: 3
+        }
+      };
+
+      var data = [trace1, trace2];
+      var layout = {
+        title: 'SE_' + plotvar,
+        xaxis: {
+          title: ''
+        },
+        yaxis: {
+          title: "Density"
+        },
+        shapes: [{
+          type: 'line',
+          x0: estmatlabdata.posterior_mode.shocks_std[plotvar],
+          y0: 0,
+          x1: estmatlabdata.posterior_mode.shocks_std[plotvar],
+          y1: Math.max(...trace2.y),
+          line: {
+            color: 'rgb(25, 253, 2)',
+            width: 2,
+            dash: 'dot'
+          }
+        }]
+      };
+    }
+  }
+
+  if (priortype == 2) {
+    xvar = [];
+    yvar = [];
+    x2var = [];
+    y2var = [];
+    if ("shocks_corr" in estmatlabdata.prior_density) {
+      for (i = 0; i < estmatlabdata.prior_density.shocks_corr[plotvar].length; i++) {
+        xvar.push(estmatlabdata.prior_density.shocks_corr[plotvar][i][0]);
+        yvar.push(estmatlabdata.prior_density.shocks_corr[plotvar][i][1]);
+      }
+      for (i = 0; i < estmatlabdata.posterior_density.shocks_corr[plotvar].length; i++) {
+        x2var.push(estmatlabdata.posterior_density.shocks_corr[plotvar][i][0]);
+        y2var.push(estmatlabdata.posterior_density.shocks_corr[plotvar][i][1]);
+      }
+      var trace1 = {
+        x: xvar,
+        y: yvar,
+        name: 'Prior',
+        line: {
+          color: 'rgb(182, 179, 179)',
+          width: 3
+        }
+      };
+      var trace2 = {
+        x: x2var,
+        y: y2var,
+        name: 'Posterior',
+        line: {
+          color: 'rgb(0, 0, 0)',
+          width: 3
+        }
+      };
+
+      var data = [trace1, trace2];
+      var layout = {
+        title: 'CC_' + plotvar,
+        xaxis: {
+          title: ''
+        },
+        yaxis: {
+          title: "Density"
+        },
+        shapes: [{
+          type: 'line',
+          x0: estmatlabdata.posterior_mode.shocks_corr[plotvar],
+          y0: 0,
+          x1: estmatlabdata.posterior_mode.shocks_corr[plotvar],
+          y1: Math.max(...trace2.y),
+          line: {
+            color: 'rgb(25, 253, 2)',
+            width: 2,
+            dash: 'dot'
+          }
+        }]
+      };
+    }
+  }
+
+  Plotly.newPlot('plotbox', data, layout);
+
+}
+
+function estplotsmoothedshocks(plotvar) {
+
+  yvar = [];
+  for (i = 0; i < estmatlabdata.SmoothedShocks[plotvar].length; i++) {
+    yvar.push(estmatlabdata.SmoothedShocks[plotvar][i][0]);
+  }
+
+  var trace1 = {
+    y: yvar,
+    line: {
+      color: 'rgb(0, 0, 0)',
+      width: 1
+    }
+  };
+
+  var data = [trace1];
+  var layout = {
+    title: plotvar,
+    xaxis: {
+      title: ''
+    },
+    yaxis: {
+      title: ''
+    },
+    shapes: [{
+      type: 'line',
+      x0: 0,
+      y0: 0,
+      x1: (estmatlabdata.SmoothedShocks[plotvar].length - 1),
+      y1: 0,
+      line: {
+        color: 'rgb(253, 63, 2)',
+        width: 2,
+        dash: 'solid'
+      }
+    }]
+  };
+  Plotly.newPlot('plotbox', data, layout);
+
+}
+
+
+function estplotsmoothedvars(plotvar) {
+
+  yvar = [];
+  y2var = [];
+
+  for (i = 0; i < estmatlabdata.obs_data[plotvar].length; i++) {
+    yvar.push(estmatlabdata.obs_data[plotvar][i][0]);
+  }
+  for (i = 0; i < estmatlabdata.SmoothedObs[plotvar].length; i++) {
+    y2var.push(estmatlabdata.SmoothedObs[plotvar][i][0]);
+  }
+  var trace1 = {
+    y: yvar,
+    name: 'Historical',
+    line: {
+      color: 'rgb(0, 0, 0)',
+      width: 1
+    }
+  };
+  var trace2 = {
+    y: y2var,
+    name: 'Smoothed',
+    line: {
+      color: 'rgb(253, 63, 2)',
+      dash: 'longdash',
+      width: 1
+    }
+  };
+
+  var data = [trace1, trace2];
+  var layout = {
+    title: plotvar,
+    xaxis: {
+      title: ''
+    },
+    yaxis: {
+      title: ''
+    }
+  };
+
+  Plotly.newPlot('plotbox', data, layout);
+
+}
\ No newline at end of file
diff --git a/src/static/js/perfectforesight.js b/src/static/js/perfectforesight.js
index d6a83c3e2008025d22fe1a08467f12c12e58ac29..101ffc2a4b31aaa7938220f9856daa35903c7b65 100644
--- a/src/static/js/perfectforesight.js
+++ b/src/static/js/perfectforesight.js
@@ -55,10 +55,7 @@ $('#setperfect').click(async function () {
   }
 
   showconsolealert(resp.message, 1);
-
-
-  // $("textarea#preprocessorout").val(resp.data.message);
-  // $('.nav-tabs a[href="#console"]').tab('show');
+  scrolltextarea();
 
   var currentdate = new Date();
   $('#classlist-form-messages').text('Last saved at: ' + currentdate);
@@ -261,6 +258,12 @@ $('#runperfect').click(async function () {
       if (numshocks[iter] == 1) {
         // if numshocks identifies a valid row in the table, we start further checks
         countshocks = countshocks + 1;
+
+        //we find the true row number of the current checked line in the table
+        var perftablerow = $('#shockname' + iter.toString()).closest('tr');
+        var perftablerowindex = perftablerow.index()+1;
+
+
         shockvaluearray = [];
 
         // we fetch periods and values and anticipation dates
@@ -305,11 +308,11 @@ $('#runperfect').click(async function () {
           shockanticipdate = 0;
         } else {
           if (!(Number.isInteger(Number(shockanticipdate)))) {
-            popthis('Shocks error.', 'The shock expectation date on row ' + countshocks + ' is not an integer number.');
+            popthis('Shocks error.', 'The shock expectation date on row ' + perftablerowindex + ' is not an integer number.');
             return (0);
           }
           if (Number(shockanticipdate) < 1) {
-            popthis('Shocks error.', 'The shock expectation date on row ' + countshocks + ' can not be lower than 1.');
+            popthis('Shocks error.', 'The shock expectation date on row ' + perftablerowindex + ' can not be lower than 1.');
             return (0);
           }
           delayexist = 1;
@@ -326,15 +329,15 @@ $('#runperfect').click(async function () {
           transitoryflag[shockindex] = 1;
           // we validate the starting period
           if (shockstart == null || shockstart == "") {
-            popthis('Shocks error.', 'You did not specify any starting period for shock on row ' + countshocks + '.');
+            popthis('Shocks error.', 'You did not specify any starting period for shock on row ' + perftablerowindex + '.');
             return (0);
           } else {
             if (!(Number.isInteger(Number(shockstart)))) {
-              popthis('Shocks error.', 'The shock starting period on row ' + countshocks + ' is not an integer number.');
+              popthis('Shocks error.', 'The shock starting period on row ' + perftablerowindex + ' is not an integer number.');
               return (0);
             }
             if (Number(shockstart) < 1) {
-              popthis('Shocks error.', 'The shock starting period on row ' + countshocks + ' can not be lower than 1.');
+              popthis('Shocks error.', 'The shock starting period on row ' + perftablerowindex + ' can not be lower than 1.');
               return (0);
             }
             shockstart = parseInt(shockstart, 10);
@@ -342,7 +345,7 @@ $('#runperfect').click(async function () {
 
           // we validate the shock value
           if (shockvalue == null || shockvalue == "") {
-            popthis('Shocks error.', 'You did not specify any value for shock on row ' + countshocks + '.');
+            popthis('Shocks error.', 'You did not specify any value for shock on row ' + perftablerowindex + '.');
             return (0);
           } else {
             if (!(IsNumeric(shockvalue))) {
@@ -357,19 +360,19 @@ $('#runperfect').click(async function () {
                 if (columnsplitlength > 1) {
                   // if we are sure there should be at least 2 periods, we check the end period
                   if (shockend == null || shockend == "") {
-                    popthis('Shocks error.', 'You did not specify any ending period for shock on row ' + countshocks + '.');
+                    popthis('Shocks error.', 'You did not specify any ending period for shock on row ' + perftablerowindex + '.');
                     return (0);
                   } else {
                     if (!(Number.isInteger(Number(shockend)))) {
-                      popthis('Shocks error.', 'The shock ending period on row ' + countshocks + ' is not an integer number.');
+                      popthis('Shocks error.', 'The shock ending period on row ' + perftablerowindex + ' is not an integer number.');
                       return (0);
                     }
                     if (Number(shockend) > Number(simperiods)) {
-                      popthis('Shocks error.', 'The shock ending period on row ' + countshocks + ' can not be larger than the number of simulation periods.');
+                      popthis('Shocks error.', 'The shock ending period on row ' + perftablerowindex + ' can not be larger than the number of simulation periods.');
                       return (0);
                     }
                     if (Number(shockend) < Number(shockstart)) {
-                      popthis('Shocks error.', 'The shock ending period on row ' + countshocks + ' cannot be before the shock starting period.');
+                      popthis('Shocks error.', 'The shock ending period on row ' + perftablerowindex + ' cannot be before the shock starting period.');
                       return (0);
                     }
                     shockend = parseInt(shockend, 10);
@@ -377,14 +380,14 @@ $('#runperfect').click(async function () {
 
                   // we verify if the number of periods and values match
                   if (!(columnsplitlength == (shockend - shockstart + 1))) {
-                    popthis('Shocks error.', 'The number of periods and the number of shock values does not match on row ' + countshocks + '.');
+                    popthis('Shocks error.', 'The number of periods and the number of shock values does not match on row ' + perftablerowindex + '.');
                     return (0);
                   }
 
                   // we define a values array
                   for (i = 0; i < columnsplitlength; i++) {
                     if (!(IsNumeric(columnsplit[i]))) {
-                      popthis('Shocks error.', 'At least one shock vector value on row ' + countshocks + ' is not a number.');
+                      popthis('Shocks error.', 'At least one shock vector value on row ' + perftablerowindex + ' is not a number.');
                       return (0);
                     }
                     shockvaluearray.push(Number(columnsplit[i]));
@@ -392,14 +395,14 @@ $('#runperfect').click(async function () {
                 } else {
                   // this is a single shock with just a start period
                   if (!(IsNumeric(columnsplit[0]))) {
-                    popthis('Shocks error.', 'The shock value on row ' + countshocks + ' is not a number.');
+                    popthis('Shocks error.', 'The shock value on row ' + perftablerowindex + ' is not a number.');
                     return (0);
                   }
                   shockvaluearray.push(Number(columnsplit[0]));
                   shockend = parseInt(shockstart, 10);
                 }
               } else {
-                popthis('Shocks error.', 'The shock value on row ' + countshocks + ' is not a number.');
+                popthis('Shocks error.', 'The shock value on row ' + perftablerowindex + ' is not a number.');
                 return (0);
               }
             } else {
@@ -408,7 +411,7 @@ $('#runperfect').click(async function () {
               if (shockend == null || shockend == "") {
                 // this is a single shock with just a start period
                 if (!(IsNumeric(shockvalue))) {
-                  popthis('Shocks error.', 'The shock value on row ' + countshocks + ' is not a number.');
+                  popthis('Shocks error.', 'The shock value on row ' + perftablerowindex + ' is not a number.');
                   return (0);
                 }
                 shockend = parseInt(shockstart, 10);
@@ -416,11 +419,11 @@ $('#runperfect').click(async function () {
               } else {
                 // this is a single value but with a range, we repeat the value over the range
                 if (!(Number.isInteger(Number(shockend)))) {
-                  popthis('Shocks error.', 'The shock ending period on row ' + countshocks + ' is not an integer number.');
+                  popthis('Shocks error.', 'The shock ending period on row ' + perftablerowindex + ' is not an integer number.');
                   return (0);
                 }
                 if (Number(shockend) > Number(simperiods)) {
-                  popthis('Shocks error.', 'The shock ending period on row ' + countshocks + ' can not be larger than the number of simulation periods.');
+                  popthis('Shocks error.', 'The shock ending period on row ' + perftablerowindex + ' can not be larger than the number of simulation periods.');
                   return (0);
                 }
                 shockend = parseInt(shockend, 10);
@@ -452,11 +455,11 @@ $('#runperfect').click(async function () {
             shockstart = 1;
           } else {
             if (!(Number.isInteger(Number(shockstart)))) {
-              popthis('Shocks error.', 'The shock starting period on row ' + countshocks + ' is not an integer number.');
+              popthis('Shocks error.', 'The shock starting period on row ' + perftablerowindex + ' is not an integer number.');
               return (0);
             }
             if (Number(shockstart) < 1) {
-              popthis('Shocks error.', 'The shock starting period on row ' + countshocks + ' can not be lower than 1.');
+              popthis('Shocks error.', 'The shock starting period on row ' + perftablerowindex + ' can not be lower than 1.');
               return (0);
             }
             shockstart = parseInt(shockstart, 10);
@@ -467,7 +470,7 @@ $('#runperfect').click(async function () {
             shockanticipdate = 0;
           } else {
             if (Number(shockanticipdate) > Number(shockstart)) {
-              popthis('Shocks error.', 'The shock expectation date on row ' + countshocks + ' can not be after the start date.');
+              popthis('Shocks error.', 'The shock expectation date on row ' + perftablerowindex + ' can not be after the start date.');
               return (0);
             }
             // if ((nonanticipatedshockexist==1)&&(delayexist==1)){popthis('Shocks error.','Please either choose a non anticipated shock or a delayed anticipation shock with anticipation date for shock on row '+countshocks+', but not both.');return(0);}
@@ -494,11 +497,11 @@ $('#runperfect').click(async function () {
             shockstart = 1;
           } else {
             if (!(Number.isInteger(Number(shockstart)))) {
-              popthis('Shocks error.', 'The shock starting period on row ' + countshocks + ' is not an integer number.');
+              popthis('Shocks error.', 'The shock starting period on row ' + perftablerowindex + ' is not an integer number.');
               return (0);
             }
             if (Number(shockstart) < 1) {
-              popthis('Shocks error.', 'The shock starting period on row ' + countshocks + ' can not be lower than 1.');
+              popthis('Shocks error.', 'The shock starting period on row ' + perftablerowindex + ' can not be lower than 1.');
               return (0);
             }
             shockstart = parseInt(shockstart, 10);
@@ -506,11 +509,11 @@ $('#runperfect').click(async function () {
 
           // we validate the shock value
           if (shockvalue == null || shockvalue == "") {
-            popthis('Shocks error.', 'You did not specify any value for shock on row ' + countshocks + '.');
+            popthis('Shocks error.', 'You did not specify any value for shock on row ' + perftablerowindex + '.');
             return (0);
           } else {
             if (!(IsNumeric(shockvalue))) {
-              popthis('Shocks error.', 'The shock value on row ' + countshocks + ' is not numeric. A permanent shock can only have a single numeric value, no comma or semi-colon is authorized.');
+              popthis('Shocks error.', 'The shock value on row ' + perftablerowindex + ' is not numeric. A permanent shock can only have a single numeric value, no comma or semi-colon is authorized.');
               return (0);
             } else {
               // we collect the value
@@ -535,15 +538,15 @@ $('#runperfect').click(async function () {
 
           // we validate the starting period
           if (shockstart == null || shockstart == "") {
-            popthis('Shocks error.', 'You did not specify any starting period for shock on row ' + countshocks + '.');
+            popthis('Shocks error.', 'You did not specify any starting period for shock on row ' + perftablerowindex + '.');
             return (0);
           } else {
             if (!(Number.isInteger(Number(shockstart)))) {
-              popthis('Shocks error.', 'The shock starting period on row ' + countshocks + ' is not an integer number.');
+              popthis('Shocks error.', 'The shock starting period on row ' + perftablerowindex + ' is not an integer number.');
               return (0);
             }
             if (Number(shockstart) < 1) {
-              popthis('Shocks error.', 'The shock starting period on row ' + countshocks + ' can not be lower than 1.');
+              popthis('Shocks error.', 'The shock starting period on row ' + perftablerowindex + ' can not be lower than 1.');
               return (0);
             }
             shockstart = parseInt(shockstart, 10);
@@ -554,14 +557,14 @@ $('#runperfect').click(async function () {
             shockanticipdate = 0;
           } else {
             if (Number(shockanticipdate) > Number(shockstart)) {
-              popthis('Shocks error.', 'The shock expectation date on row ' + countshocks + ' can not be after the start date.');
+              popthis('Shocks error.', 'The shock expectation date on row ' + perftablerowindex + ' can not be after the start date.');
               return (0);
             }
           }
 
           // we validate the shock value
           if (shockvalue == null || shockvalue == "") {
-            popthis('Shocks error.', 'You did not specify any value for shock on row ' + countshocks + '.');
+            popthis('Shocks error.', 'You did not specify any value for shock on row ' + perftablerowindex + '.');
             return (0);
           } else {
             if (!(IsNumeric(shockvalue))) {
@@ -576,19 +579,19 @@ $('#runperfect').click(async function () {
                 if (columnsplitlength > 1) {
                   // if we are sure there should be at least 2 periods, we check the end period
                   if (shockend == null || shockend == "") {
-                    popthis('Shocks error.', 'You did not specify any ending period for shock on row ' + countshocks + '.');
+                    popthis('Shocks error.', 'You did not specify any ending period for shock on row ' + perftablerowindex + '.');
                     return (0);
                   } else {
                     if (!(Number.isInteger(Number(shockend)))) {
-                      popthis('Shocks error.', 'The shock ending period on row ' + countshocks + ' is not an integer number.');
+                      popthis('Shocks error.', 'The shock ending period on row ' + perftablerowindex + ' is not an integer number.');
                       return (0);
                     }
                     if (Number(shockend) > Number(simperiods)) {
-                      popthis('Shocks error.', 'The shock ending period on row ' + countshocks + ' can not be larger than the number of simulation periods.');
+                      popthis('Shocks error.', 'The shock ending period on row ' + perftablerowindex + ' can not be larger than the number of simulation periods.');
                       return (0);
                     }
                     if (Number(shockend) < Number(shockstart)) {
-                      popthis('Shocks error.', 'The shock ending period on row ' + countshocks + ' can before the shock starting period.');
+                      popthis('Shocks error.', 'The shock ending period on row ' + perftablerowindex + ' can before the shock starting period.');
                       return (0);
                     }
                     shockend = parseInt(shockend, 10);
@@ -596,14 +599,14 @@ $('#runperfect').click(async function () {
 
                   // we verify if the number of periods and values match
                   if (!(columnsplitlength == (shockend - shockstart + 1))) {
-                    popthis('Shocks error.', 'The number of periods and the number of shock values does not match on row ' + countshocks + '.');
+                    popthis('Shocks error.', 'The number of periods and the number of shock values does not match on row ' + perftablerowindex + '.');
                     return (0);
                   }
 
                   // we define a values array
                   for (i = 0; i < columnsplitlength; i++) {
                     if (!(IsNumeric(columnsplit[i]))) {
-                      popthis('Shocks error.', 'At least one shock vector value on row ' + countshocks + ' is not a number.');
+                      popthis('Shocks error.', 'At least one shock vector value on row ' + perftablerowindex + ' is not a number.');
                       return (0);
                     }
                     shockvaluearray.push(Number(columnsplit[i]));
@@ -611,14 +614,14 @@ $('#runperfect').click(async function () {
                 } else {
                   // this is a single shock with just a start period
                   if (!(IsNumeric(columnsplit[0]))) {
-                    popthis('Shocks error.', 'The shock value on row ' + countshocks + ' is not a number.');
+                    popthis('Shocks error.', 'The shock value on row ' + perftablerowindex + ' is not a number.');
                     return (0);
                   }
                   shockvaluearray.push(Number(columnsplit[0]));
                   shockend = parseInt(shockstart, 10);
                 }
               } else {
-                popthis('Shocks error.', 'The shock value on row ' + countshocks + ' is not a number.');
+                popthis('Shocks error.', 'The shock value on row ' + perftablerowindex + ' is not a number.');
                 return (0);
               }
             } else {
@@ -627,7 +630,7 @@ $('#runperfect').click(async function () {
               if (shockend == null || shockend == "") {
                 // this is a single shock with just a start period
                 if (!(IsNumeric(shockvalue))) {
-                  popthis('Shocks error.', 'The shock value on row ' + countshocks + ' is not a number.');
+                  popthis('Shocks error.', 'The shock value on row ' + perftablerowindex + ' is not a number.');
                   return (0);
                 }
                 shockend = parseInt(shockstart, 10);
@@ -635,11 +638,11 @@ $('#runperfect').click(async function () {
               } else {
                 // this is a single value but with a range, we repeat the value over the range
                 if (!(Number.isInteger(Number(shockend)))) {
-                  popthis('Shocks error.', 'The shock ending period on row ' + countshocks + ' is not an integer number.');
+                  popthis('Shocks error.', 'The shock ending period on row ' + perftablerowindex + ' is not an integer number.');
                   return (0);
                 }
                 if (Number(shockend) > Number(simperiods)) {
-                  popthis('Shocks error.', 'The shock ending period on row ' + countshocks + ' can not be larger than the number of simulation periods.');
+                  popthis('Shocks error.', 'The shock ending period on row ' + perftablerowindex + ' can not be larger than the number of simulation periods.');
                   return (0);
                 }
                 shockend = parseInt(shockend, 10);
@@ -755,7 +758,7 @@ $('#runperfect').click(async function () {
 
       // calling the 'node side'
       try {
-        var resp = await runperfectnode(perforval);
+        var resp = await runperfectnode(JSON.stringify(perforval));
       } catch (error) {
         console.log(error)
         if (error.status == 2) {
diff --git a/src/static/js/stochastic.js b/src/static/js/stochastic.js
index c90a9f87d32d547670845c56cac54a2fc3df07a8..201d31aa2a36b7508d91e01e71eea24343c761d6 100644
--- a/src/static/js/stochastic.js
+++ b/src/static/js/stochastic.js
@@ -59,6 +59,7 @@ $('#setstochastic').click(async function () {
   }
 
   showconsolealert(resp.message, 1);
+  scrolltextarea();
 
   //the model has exo shocks: we make a table
   // if a steady state has not been provided if ask extra info on that
@@ -146,7 +147,7 @@ function disableassociated(shockindex) {
   if (selectedvalue < 3) {
     $("#stoassoshockname" + shockindex).attr('disabled', 'disabled');
   } else {
-    $("#stoassoshockname" + shockindex).removeAttr('disabled');;
+    $("#stoassoshockname" + shockindex).removeAttr('disabled');
   }
   //cl(selectedvalue);
 }
@@ -261,6 +262,10 @@ $('#runstochastic').click(async function () {
         // if stonumshocks identifies a valid row in the table, we start further checks
         countshocks = countshocks + 1;
 
+        //we find the true row number of the current checked line in the table
+        var stotablerow = $('#stoshockname' + stoiter.toString()).closest('tr');
+        var stotablerowindex = stotablerow.index()+1;
+
         // We fetch shock infos
         shockindex = $('#stoshockname' + stoiter.toString()).val();
         shockattributevalue = $("#stoshockattribute" + stoiter.toString()).val();
@@ -271,7 +276,7 @@ $('#runstochastic').click(async function () {
         if (shockattributevalue > 2) { //covariance or correation was selected
           assoshockindex = $('#stoassoshockname' + stoiter.toString()).val();
           if (shockindex == assoshockindex) {
-            popthis('Shocks error.', 'On row ' + countshocks + ', the covariance/correlation should be taken for separate shocks.');
+            popthis('Shocks error.', 'On row ' + stotablerowindex + ', the covariance/correlation should be taken for separate shocks.');
             return (0);
           }
           // we verify if covariance/correlation has already been specified for any two same shocks
@@ -279,14 +284,14 @@ $('#runstochastic').click(async function () {
             if (shockspairs.indexOf(shockindex + '-' + assoshockindex) == -1) {
               shockspairs.push(shockindex + '-' + assoshockindex);
             } else {
-              popthis('Shocks error.', 'On row ' + countshocks + ', this covariance/correlation has already been specified between these shocks.');
+              popthis('Shocks error.', 'On row ' + stotablerowindex + ', this covariance/correlation has already been specified between these shocks.');
               return (0);
             }
           } else {
             if (shockspairs.indexOf(assoshockindex + '-' + shockindex) == -1) {
               shockspairs.push(assoshockindex + '-' + shockindex);
             } else {
-              popthis('Shocks error.', 'On row ' + countshocks + ', this covariance/correlation has already been specified between these shocks.');
+              popthis('Shocks error.', 'On row ' + stotablerowindex + ', this covariance/correlation has already been specified between these shocks.');
               return (0);
             }
           }
@@ -321,7 +326,7 @@ $('#runstochastic').click(async function () {
               stoyiter = stoyiter + 1;
             }
             if (stoyflag < 2) {
-              popthis('Shocks error.', 'On row ' + countshocks + ', the covariance relation requires that the variances (or std deviation) of both related shocks are declared. Please declare a value for both of them.');
+              popthis('Shocks error.', 'On row ' + stotablerowindex + ', the covariance relation requires that the variances (or std deviation) of both related shocks are declared. Please declare a value for both of them.');
               return (0);
             }
 
@@ -330,7 +335,7 @@ $('#runstochastic').click(async function () {
         } else {
           //we check if the same shock already has a std or variance flag
           if (attributeflag[shockindex] > 0) {
-            popthis('Shocks error.', 'On row ' + countshocks + ', You have already specified a variance or standard deviation attribute for this shock. Please keep only one such attribute per shock.');
+            popthis('Shocks error.', 'On row ' + stotablerowindex + ', You have already specified a variance or standard deviation attribute for this shock. Please keep only one such attribute per shock.');
             return (0);
           } else {
             attributeflag[shockindex] = shockattributevalue;
@@ -400,7 +405,7 @@ $('#runstochastic').click(async function () {
 
       // calling the 'node side'
       try {
-        var resp = await runstochasticnode(stosimval);
+        var resp = await runstochasticnode(JSON.stringify(stosimval));
       } catch (error) {
         console.log(error)
         if (error.status == 200) {
@@ -423,6 +428,8 @@ $('#runstochastic').click(async function () {
 ipc.on('stochasticsimfinish', (event, arg) => {
 
   async function finishstochastic() {
+  
+    scrolltextarea();
 
     // loading JSON output from Matlab
     try {