Hi there. Patch is attached. Also I've added Ilya Perminov's fix for result-type with at beginning.
Sorry this is one large patch... I know it is hard to read.