removed spagetti code and fixed a major performance issue