Added handling of some boundary cases.
Cleaned up obsolete code.