Refactor and bug fixing

Some refactoring and some issue fixing in order to make this work