Refactored a bit and prepared for lambdas