Refactored. 1st step for it can be used as a library. Removed old docstrings. Better function names