Fixed several bugs and improved some logic