Added optimizer and fixed some bugs.