First solution to pass scoring project tests. Warning: very procedural code.