Some performance improvements anf a few bug fixes