reorganise code, and minor misc changes