use bit operations and cahced values where possible, clean up code a bit