Here's an updated patch with better comments.