Revised all loops to improve performance and avoid unexpected behaviours