refactor with bug fixes