Completely updated Brian's code
merging with phil