Refactor master election logic

Clean up the master election process