Added type detection, a lot of debug code in place.