refactored; merged with upstream;