refactored printing and fixed bug