improve and debug the functions