in reply to A more efficient way to do this?

One simple improvement would be to change your if-if-if... to if-elsif-elsif... so you stop testing after the first truth.