Rewrote some of the backend

It was pretty ugly so I rewrote some of the backend.