add documentation and optimize code