partially refactored, doesn't work yet