working version, some code clean-up in progress