First version of code
Refactorized code. Several improvements and bug fixes.