refactored the code from matt hassel