Rewrite in more functional way. Need to refactor names and code!