Added proper memory managment to enable use as a library without memory leaks