lots of changes to fix bugs