added safety checks. thanks @walkman for the idea