fixed algorithm to handle crapy SGS implementation