moved some repeated i/o to a subroutine