solve a few bugs and duplicate code