Cleaned up redundant code with while loop