Code cleanup and better history handling