Transfered some ideas from a branch