updated code - works better