Code cleanup and fixing for timeout based terminal detection