added some checks in if statements, still a nil pointer dereference bug