Fix formatting and loop bugs