Various cleanups and bug fixes