Refined original rough cut. This probably has errors because i don't know js.