Made a lot of changes. Added a lot of utils, some not tested.