Major refactoring + bug fix