reorganized into subroutines, bugfixes