rewrote it slowly with proper unit tests