History backend logic

All the variables should be correct, but I've confused myself about which one corresponds to which category. @smnguyen, if you have some time, could you check this?