modularize
debugged modular version