Improved exception handling + cleaned inner loop