added and started refactoring code from eloncatod