added more checks, simplify code