Moved most function definitions to lib.py

I’m performing some basic refactoring of changewithin to make it easier to use with other places.