Completed ugly implementetion. Seems to be working now