Broke heartbeat code into multiple chunks.

This is just a quick refactor to make the existing code a bit more comprehensible.