initial commit of complete rewrite code. more flexible