fixed invalid optimization, added test cases
removed unused functions