refactor some ugly code