Rearranged and cleaned code