totally rewrited and optimized