Rewrote almost complete, some bugs left.