Add a functionality document, and cleanup the code.

Thanks to Mahmoud Kassaie for his code review.