Working, fully-tested (accuracy and speed), commented version