added rotation logic and rearranged some code