Fixed several bugs. Te be thoroughly tested