All of this logic is cut and pasted from the framework grade and was always very poor.... I guess there's not much to be done about it before gingerness, but see if it can be better organised.