reordering code and rename some ill-named functions