This is Hoi-Ho Chan's patch with some minor fixes by me. There are some potential issues in this, but none worse than we can sort out on the list and over time.