improved logic, more docstrings