more refactoring and fixed defect
clean up and moved some globals into classes