Rewrote from scratch. Cleaner code now.