bug fixes, some rewrite