improve flexibility of reduce
simplify reduce slightly
fix code formatting