refactored and working. Still lots of edge cases it cannot handle though