there is a bug in here, but mostly working, need to check the outputs