Merging GSOC2012 contributions from Sreenatha, after some modifications made to fix minor bugs -- jpye.