Working code, need optimization