Reworked a lot, code is still ugly though.