added some comments, documentation, cleaned up code a bit