Split stuff into functions and a library

Split a lot of functions into a library file and adopted the scripts accordingly