fix hangup bug; refactor a few functions slightly