Merged with Omid's code.