Merged Looper's fix with some small modifications.