<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def CreateSubsetFile(in_drainage_line, river_id, out_riv_bas_id_file, file_geodatabase=None):
 """ Creates River Basin ID subset input CSV file for RAPID based on the Drainage Line shapefile with river ID and next downstream ID fields Parameters in_drainage_line: str Path to the stream network (i.e. Drainage Line) shapefile. river_id: str The name of the field with the river ID (Ex. 'HydroID', 'COMID', or 'LINKNO'). out_riv_bas_id_file: str The path to the output river basin ID subset file. file_geodatabase: str, optional Path to the file geodatabase. If you use this option, in_drainage_line is the name of the stream network feature class (WARNING: Not always stable with GDAL). Example:: from RAPIDpy.gis.network import CreateSubsetFile CreateSubsetFile( in_drainage_line='/path/to/drainageline.shp', river_id='LINKNO', out_riv_bas_id_file='/path/to/riv_bas_id.csv') """

    ogr_drainage_line_shapefile_lyr, ogr_drainage_line_shapefile = \
        open_shapefile(in_drainage_line, file_geodatabase)

    ogr_drainage_line_definition = \
        ogr_drainage_line_shapefile_lyr.GetLayerDefn()

    orig_field_names = []
    for idx in xrange(ogr_drainage_line_definition.GetFieldCount()):
        orig_field_names.append(
            ogr_drainage_line_definition.GetFieldDefn(idx).GetName())

    upper_field_names = [field.upper() for field in orig_field_names]
    sort_field = None

    # Sort by HYDROSEQ order if the option exists
    if 'HYDROSEQ' in upper_field_names:
        # with this method, smaller is downstream
        sort_field = orig_field_names[upper_field_names.index('HYDROSEQ')]
        log("Sorting by {0}".format(sort_field))

    hydroseq_list = []
    hydroid_list = []
    # The script line below makes sure that rows in the subset file are
    # arranged in descending order of NextDownID of stream segements
    for drainage_line_feature in ogr_drainage_line_shapefile_lyr:
        hydroid_list.append(drainage_line_feature.GetField(river_id))
        if sort_field:
            hydroseq_list.append(drainage_line_feature.GetField(sort_field))

    del ogr_drainage_line_shapefile

    hydroid_list = np.array(hydroid_list, dtype=np.int32)
    if hydroseq_list:
        hydroseq_list = np.array(hydroseq_list, dtype=np.int32)
        sort_order = hydroseq_list.argsort()[::-1]
        hydroid_list = hydroid_list[sort_order]
    else:
        hydroid_list = np.sort(hydroid_list)

    with open_csv(out_riv_bas_id_file, 'w') as csvfile:
        connectwriter = csv_writer(csvfile)
        for hydroid in hydroid_list:
            connectwriter.writerow([hydroid])