optimized code
some bug fixes and improvements