Grouped code into templates. Fixed looping.