Fixed various issues but still pretty inefficient