added a lot of documentation, and a bit of optimization