rewrote most of the code