Adding tests and improving some bits of code