Merged in changes form Riad's code.