Fixed res variable, added checking logic