Extract out the history code and create functions for it.

(Easier to fix issues later on)