Rewrite by Manuel Novoa III, very compact implimentation.