Refactored a bit and added documentation