fixes #368 - merge from FB and some re-factoring