Major code rewrite and refactor (still not perfect)