Final solution. With comments and everything