general bug fix and refractoring