moved code around a bit for neatness