improved code structure; added documentation; fixed memory leak; added exit handler