Refactoring the code a bit

I've removed some duplication and improved a bit the code. Since it doesn't have tests, I changed with a bit more caution, so I think it's everything fine.


> Showing 11 changed files with 146 additions and 231 deletions.