Refactored script with optimization and extensibility in mind.

This change has not been thoroughly tested yet, and more improvements
are coming soon.