Partially imported Eloe's code, still doing some indentation cleanup.