Added tests, fixed duplicate code