very complicated version. not very elegant but it does everything with minimal changes.