Modified code - works properly