Finalized code, pieced together from diff ideas