reimplemented some parts in functional style