Fixed tail -> head problem. Lots of other fixes.