better code structure and some memory leaks removed