fix code; add optimizations