Major refactoring and error correction. Sucessfull test.