Refactored code, still not robust