Handle more edge cases and fix various bugs