made the functions into library and optimized code