final version, big optimalization