Rm duplicate code and bugfixes