fixing bugs and optimization 1