Incorporating many fixes from @siawyoung