added docs, improved corner cases and algorithms