Improved code efficiency

Thanks to theodore from IRC for contributing.