Fix error and improve code