Cleaned up code, added branch handling