heavy refactoring, combined code from another project