generalized visibility code. general bug fixes and optimized code