Rewrite and some bug fixes. Should be refactored more though.