(moved some code fragments into subroutines)