Fixed some bugs. Code simplified.