lot of fixes, optimization, refactor