cleaned up context detection code