Some code refactoring, so it looks slightly less ugly