Function for creating thumbnails in php

It took me long time to create an universal function which would create thumbnails from pictures and suit all my needs.
The base for this function, I took from here.
But I modified it slightly.

So, if you want to create a thumbnail, so that the thumbnail size will be base on smallest side, then do the following:

In this case the smallest part will become 170px and the biggest proportionally bigger. Otherwise:

In this case the biggest part will become 170px and the smallest proportionally less.