refactor heap code