Comments added, code reworked