fixed memory leaks and some other issues, to get it on CRAN