rearranged code to work correctly