cleaned up a lot and ported it from tornado to flask