Beautify and remove duplicate code