<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def _service_url(request, redirect_to=None, gateway=False):
 """ Generates application service URL for CAS :param: request Request Object :param: redirect_to URL to redriect to :param: gateway Should this be a gatewayed pass through """


    if settings.CAS_FORCE_SSL_SERVICE_URL:
        protocol = 'https://'
    else:
        protocol = ('http://', 'https://')[request.is_secure()]
    host = request.get_host()
    service = protocol + host + request.path
    if redirect_to:
        if '?' in service:
            service += '&'
        else:
            service += '?'

        if gateway:
            """ If gateway, capture params and reencode them before returning a url """
            gateway_params = [(REDIRECT_FIELD_NAME, redirect_to), ('gatewayed', 'true')]
            query_dict = request.GET.copy()

            try:
                del query_dict['ticket']
            except:
                pass
            query_list = query_dict.items()

            # remove duplicate params
            for item in query_list:
                for index, item2 in enumerate(gateway_params):
                    if item[0] == item2[0]:
                        gateway_params.pop(index)
            extra_params = gateway_params + query_list

            #Sort params by key name so they are always in the same order.
            sorted_params = sorted(extra_params, key=itemgetter(0))

            service += urlencode(sorted_params)
        else:
            service += urlencode({REDIRECT_FIELD_NAME: redirect_to})

    return service