Refactoring the code, still not working as well as expected...