sub bug fix and main rewrite