Fixed some bugs and rewrote some functions