Removed duplicate code. Simplified tricuoic code and improved out-of-bounds handling.