fixed various bugs, made script tremendously less elegant