add comments to document the code

This is still work in progress. Please tell me if the comment style is acceptable. And also please look at the comments and tell me if I misunderstood the code (especially @gmarik). I only guessed the semantics from reading through the code.