Finished code rewrite, most parts working now