Fixed some bugs (but not fully tested).