Ast improvements

OK I think I've done all the work I wanted on this branch, written tests and documentation - it's ready to go!