split out logic into clj file. Fix stackoverflow recursion bug