fix bugs, improve tests and performance