massive restructure; add sorting and cutting functions