fixing some bugs. It's working with Valgrind