main rewrite with new features and new tests