Extract most of the code to a library