Fixed crash problems.  Refactored to improve performance and code maintenance.