Fix pass by reference error and improve code quality