structured code a bit, added unit tests