Cleaned up code based on pwendell's suggestions