Refined code

(reinsert comments where necessary)