how to both crop (with tool) and resize thumbnails having only a max width constrain?

I can’t found my very problem in other threads. I’ll try to explain:

want to use thumbnails MAX 400px width. That means that CAN be 400px, but not always they should be 400px width. They can be even less. So, say, in the same page, one thumb 400px, one 320px and one 350px.
want to crop them using the wordpress crop tool.
Till now, I’ve been able to get the thumbs both correctly cropped and 400px. What I can’t get is a thumb less than 400px (I’ve setted that width in the media options). In other words, wordpress always set the thumb to 400px, despite of how I edited the images. I would like it to consider 400px only the max width instead, so I can edit and image to to have the thumb cropped (I mean with the edit tool) and resized say, to 320px.
Another way to say it: I want wordpress to serve the thumbs 400px width only if I didn’t resized them less than 400px.

Is there any way to do it?

I’m a programmer, and I can eventually use code to filter out content, but still I can’t figure out the exact way of doing it.