Fixed errors and added safety checks