Refactored to simplify code, avoid problems