Cleans up the groovy code and made it a bit more robust.