lots of js fixes. made functions more generic with more loop/less repition