non optimized version
median diagonal optimization