improved speed and correct output