removed some spurrisous code, moving main body code into subroutines