refactored; minor optimizations