Removed some bugs and added some functionality

Probably some bugs left though, I haven't debugged all the code yet.