Joint-related cleanups and fixed crash on exit

See the commit messages for details.