fixed bug in optimize, few minor bugfixes