Code cleanup + imporove some tests