refactor and bugfixes -hugh & sean