add more checks
simplify the code