Replace repeated code with one function and bug fix