Added remaining code from upstream and started to refactor