rewrote most of code