re-implementation in java, inspired by http://www.elmerproductions.com/sp/peterb/