all code: last updated 10.05.14. Needs refactoring