fixed memory leaks and speed up program considerably