optimized
changed logic slightly to avoid unneccary lookup
checks implemented