Refactored previous code a bit (still work left to do)