Can we document this code a bit better?

(@akjags you might want to attribute the source of this code, and also check on its license.  @sefk can help you with that)