Refactore code

Common method extracted into a separate module. Minor bug fix.