Finished. It's ugly code but it works.