source code is messy, but it works.