This REALLY needs a cleanup.  Or a rewrite.