Add documentation and refactor a bit.

Change-Id: Ie73d45ae593b13fa278ee43019fbedcaf9ba84e4