Fixed some bugs. Roughly tested.