optimize code, refactor tests