Fix numerous bugs