Fixing the nested loops indexes