Restructure code so that the same can work for ST2 and ST3.

I tested it on ST2 and ST3 both, it seems to be working fine. @vanrijn Please have a look, if it works fine we can merge this into ST3 and then probably merge ST3 into ST2. @ageekymonk, it would be great if you could have a look at this change too.