complete rewrite of core algorithm
previous version made too many queries to DOM