Fixed bugs related to rearranging code