Some code simplifications and bug fixes