simplify the code and add a function