Some code cleanup/simplification and bug fixes