Cleaned up patch provided by tterrag