Small improvements

 * Use isset instead of compating to NULL
 * Removed some code cuplication by exctracting logic to function