}
 // handle flags "as_new" and "is_same_address"
 foreach ($update_fields['address'] as $type => $address) {
     if ($address['as_new']) {
         $update_fields['address'][$type]['address_id'] = 0;
     }
     if (($type == 'current' || $address['address_id'] == 'current') && $update_fields['is_same_address']) {
         unset($update_fields['address'][$type]);
     }
     // Do not check shipping address if it is the same as billing
 }
 // validate profile fields
 if ($is_checkout) {
     $profile_fields = array('basic' => $profile_fields['basic']);
 }
 $fill_error = cw_check_user_field_validate($user, $update_fields, $profile_fields);
 // validate duplicated email
 if ($mode == 'add' && !empty($update_fields['basic']['email']) && Customer\getByEmail($update_fields['basic']['email'])) {
     $fill_error['basic']['email'] = true;
 }
 // validation is OK
 if (!count($fill_error)) {
     $new_profile = cw_check_user_field_build_profile($userinfo, $update_fields, $profile_fields);
     $is_new_profile = false;
     if ($mode == 'add') {
         $new_profile['usertype'] = $usertype;
         $user = cw_user_create_profile($new_profile);
         // Login registered user
         $identifiers =& cw_session_register('identifiers', array());
         $identifiers['C'] = array('customer_id' => $user);
         $is_new_profile = true;
 // make sure we processes array of addresses
 foreach ($update_fields['address'] as $addr_type => $address) {
     if ($is_checkout) {
         $address['address_id'] = $addr_type;
     }
     foreach ($address as $k => $v) {
         if (!is_array($v)) {
             $address[$k] = trim($v);
         }
     }
     foreach (array('city', 'state', 'country', 'zipcode') as $v) {
         if (!$profile_fields['address'][$v]['is_avail'] && empty($address[$v])) {
             $address[$v] = $config['General']['default_' . $v];
         }
     }
     $fill_error = cw_check_user_field_validate($user, array('address' => $address), $profile_fields);
     $prefilled_address = array();
     if (count($fill_error)) {
         $prefilled_address = $address;
         $smarty->assign('address_errors', cw_check_user_get_error($fill_error));
         cw_add_top_message(cw_check_user_get_error($fill_error), 'E');
     } else {
         $address['customer_id'] = $user;
         // Main and current addresses are saved in session only (not in DB)
         if (in_array($address['address_id'], array('main', 'current'))) {
             $user_address[$address['address_id'] . '_address'] = $address;
         }
         // If main is updated and current is defined as "same", then copy address to current
         if ($address['address_id'] == 'main' && $user_address['main_address']['address_id'] == $user_address['current_address']['address_id']) {
             $user_address['current_address'] = $user_address['main_address'];
         }