major code rewrite

Change-Id: Ia7dace928d65c403ec88938b67f64b18d3e9dd5b