History refactor

Not ready yet, only for review and comments.

Now working implementation with tests