Lots of improvements and some util functions