Added rest of old code to scratchpad. Still it needs some refactoring.