Fixed random port logic to stay within valid range

Fixes #59. Also math.