Majorly refactored and commented code.