adding output flush and removing redundant code