fix history bug, some code reorganization