Move function to lib and add tests