Incorporate some changes from rafoo's branch.