rearranged some logic