program giving the correct output now - need to optimize it