Small refactoring, removing static calls, etc.
Updated fix for #2644. Improved SQL statement and added aditional tests.