moved the leader election code to a method