fix #505
fix #506
fixes and refactor
cleanup