This is terrible way of doing this and should be replaced anyway.  I wouldn't worry to much about making it nice, pretty, or fast.