Lots of fixes and rearranging code