Add logout support and fix various bugs