Added tests and simplified some places