diff --git a/src/cluster/cluster.cpp b/src/cluster/cluster.cpp
index 22cf940e392a4a49969a14c068fbd43547839756..44bfefed1daaa57a8452c2d4227c233da02861ee 100644
--- a/src/cluster/cluster.cpp
+++ b/src/cluster/cluster.cpp
@@ -212,6 +212,19 @@ void cluster(const string& config_file, const string& data_file, const string& o
 	message = "INFO: First iteration took " + to_string(elapsed.count()) + "s.\n";
 	logger->log(message);
 	time_logger->log(message);
+	if (jer != 0) {
+	  // First loop failed. Halt the calculation.
+	  tppoan.close();
+	  fclose(timing_file);
+	  fclose(output);
+	  delete p_scattering_angles;
+	  delete cid;
+	  delete logger;
+	  delete time_logger;
+	  delete sconf;
+	  delete gconf;
+	  return jer;
+	}
 
 	// here go the calls that send data to be duplicated on other MPI processes from process 0 to others, using MPI broadcasts, but only if MPI is actually used
 #ifdef MPI_VERSION
@@ -625,6 +638,8 @@ int cluster_jxi488_cycle(int jxi488, ScattererConfiguration *sconf, GeometryConf
   message = "INFO: matrix inversion for scale " + to_string(jxi488) + " took " + to_string(elapsed.count()) + "s.\n";
   logger->log(message);
   if (jer != 0) {
+    message = "ERROR: matrix inversion ended with error code " + to_string(jer) + ".\n";
+    logger.err(message);
     return jer;
     // break; // jxi488 loop: goes to memory clean
   }