refactored to be useable as a library