small bugfixes and leaks, patch by João Silva