Some refactoring and renaming of functions and variables to make more logical. Added documentation.