Refactored code to have less repetition.

Change-Id: I5e96b72cc8ac3a714ab728c1c362963000919d79
Merge pull request #3 from superaktieboy/master

code refactoring