Refactoring. Documentation added.

NOTE: still needs to be tested