Added some safety checks
Safer, more readable code