Fixed crash and makes class more robust