final code works perfectly