Replaced code with implementation from Alan Thorn