added documentation and simplified code