Refactored logic part, converted as much as could to LINQ, improved tests