uprav skript, aby na vstupu misto formatu
cislo,cislo
prijimal format 
(cislo, cislo)

dale uprav skript tak, ze v garfickem okne bude pod napis Geometricky program ....
uveden počet usecek.
napis bude takovy -
Celkem je cislo usecek.


import matplotlib.pyplot as plt
from shapely.geometry import LineString, Point
import math
import itertools

def get_circle_points(N):
    points = []
    for i in range(N):
        angle = 2 * math.pi * i / N
        x = math.cos(angle)
        y = math.sin(angle)
        points.append((x, y))
    return points

def input_line_segments():
    print("Enter the initial line segments as pairs of point indices (comma-separated).")
    print("For example: 1,3")
    print("Enter 'done' when finished.")
    segments = []
    while True:
        s = input("Enter line segment: ")
        if s.lower() == 'done':
            break
        try:
            idx1, idx2 = map(int, s.strip().split(','))
            segments.append((idx1 - 1, idx2 - 1))  # Adjusting for zero-based indexing
        except:
            print("Invalid input. Please enter two integers separated by a comma.")
    return segments

def plot_segments(ax, points, segments, color='blue', linewidth=1, linestyle='-'):
    for idx1, idx2 in segments:
        x1, y1 = points[idx1]
        x2, y2 = points[idx2]
        ax.plot([x1, x2], [y1, y2], color=color, linewidth=linewidth, linestyle=linestyle)

def plot_circle(ax, points):
    circle = plt.Circle((0, 0), 1, fill=False, color='black', linestyle='dashed')
    ax.add_artist(circle)
    for idx, (x, y) in enumerate(points):
        ax.plot(x, y, 'ko')
        ax.text(x * 1.05, y * 1.05, str(idx + 1), fontsize=12, ha='center', va='center')

def compute_intersections(points, segments):
    lines = []
    for idx1, idx2 in segments:
        x1, y1 = points[idx1]
        x2, y2 = points[idx2]
        line = LineString([(x1, y1), (x2, y2)])
        lines.append({'indices': (idx1, idx2), 'line': line})

    # Find all intersection points
    intersections = {}
    for i, line1 in enumerate(lines):
        for line2 in lines[i+1:]:
            if line1['line'].intersects(line2['line']):
                intersect_pt = line1['line'].intersection(line2['line'])
                if isinstance(intersect_pt, Point):
                    x, y = intersect_pt.x, intersect_pt.y
                    # Add to dictionary to avoid duplicates
                    key = (round(x, 8), round(y, 8))
                    intersections[key] = (x, y)
    return intersections

def subdivide_lines(points, segments, intersections):
    all_points = points.copy()
    # Map to store point indices for intersection points
    intersection_indices = {}
    for key, (x, y) in intersections.items():
        all_points.append((x, y))
        idx = len(all_points) - 1
        intersection_indices[key] = idx

    new_segments = []
    # For each original line segment, subdivide if there are intersections
    for idx1, idx2 in segments:
        x1, y1 = points[idx1]
        x2, y2 = points[idx2]
        line = LineString([(x1, y1), (x2, y2)])
        # Find all intersections on this line
        intersect_pts = []
        for key, idx in intersection_indices.items():
            xi, yi = intersections[key]
            if line.distance(Point(xi, yi)) < 1e-8 and not ((xi == x1 and yi == y1) or (xi == x2 and yi == y2)):
                # Avoid endpoints
                intersect_pts.append((xi, yi, idx))
        # Sort the points along the line
        if intersect_pts:
            pts = [(x1, y1, idx1)] + intersect_pts + [(x2, y2, idx2)]
            # Calculate parameter t along the line for sorting
            x0, y0 = x1, y1
            dx, dy = x2 - x1, y2 - y1
            def param_t(pt):
                px, py = pt[0], pt[1]
                return ((px - x0) * dx + (py - y0) * dy) / (dx**2 + dy**2)
            pts.sort(key=param_t)
            # Create segments between consecutive points
            for i in range(len(pts) - 1):
                idx_start = pts[i][2]
                idx_end = pts[i+1][2]
                new_segments.append((idx_start, idx_end))
        else:
            # No intersection, keep original segment
            new_segments.append((idx1, idx2))
    return new_segments, all_points

def main():
    N = int(input("Enter the number of points on the circle: "))
    points = get_circle_points(N)
    segments = input_line_segments()

    # Plot original segments
    fig1, ax1 = plt.subplots()
    plot_circle(ax1, points)
    plot_segments(ax1, points, segments)
    ax1.set_aspect('equal')
    ax1.set_title('Original Line Segments')

    # Compute intersections
    intersections = compute_intersections(points, segments)

    # Subdivide lines at intersections
    new_segments, all_points = subdivide_lines(points, segments, intersections)

    # Remove duplicate segments (if any)
    new_segments = list(set(tuple(sorted(seg)) for seg in new_segments))

    # Output the new line segments
    print("\nNew Line Segments (between points):")
    segment_data = []
    for idx, (idx1, idx2) in enumerate(new_segments, start=1):
        x1, y1 = all_points[idx1]
        x2, y2 = all_points[idx2]
        print(f"Segment {idx}: Point {idx1 + 1} ({x1:.3f}, {y1:.3f}) to Point {idx2 + 1} ({x2:.3f}, {y2:.3f})")
        segment_data.append({
            'segment_number': idx,
            'start_index': idx1 + 1,
            'end_index': idx2 + 1,
            'start_point': (x1, y1),
            'end_point': (x2, y2)
        })

    # Output total number of new line segments
    total_segments = len(new_segments)
    print(f"\nTotal number of new line segments: {total_segments}")

    # Save to text database (text file)
    with open('line_segments.txt', 'w') as f:
        f.write("Segment_Number,Start_Index,End_Index,Start_X,Start_Y,End_X,End_Y\n")
        for seg in segment_data:
            f.write(f"{seg['segment_number']},{seg['start_index']},{seg['end_index']},"
                    f"{seg['start_point'][0]},{seg['start_point'][1]},"
                    f"{seg['end_point'][0]},{seg['end_point'][1]}\n")
    print("\nLine segments have been saved to 'line_segments.txt'.")

    # Plot new segments
    fig2, ax2 = plt.subplots()
    plot_circle(ax2, points)
    # Number the points, including intersection points
    for idx, (x, y) in enumerate(all_points):
        ax2.plot(x, y, 'ko')
        ax2.text(x * 1.05, y * 1.05, str(idx + 1), fontsize=8, ha='center', va='center')
    for idx, (idx1, idx2) in enumerate(new_segments, start=1):
        x1, y1 = all_points[idx1]
        x2, y2 = all_points[idx2]
        ax2.plot([x1, x2], [y1, y2], color='red')
        # Label the segment at its midpoint
        xm, ym = (x1 + x2) / 2, (y1 + y2) / 2
        ax2.text(xm, ym, f"{idx}", color='blue', fontsize=8)
    ax2.set_aspect('equal')
    ax2.set_title('Subdivided Line Segments with Numbers')

    plt.show()

if __name__ == "__main__":
    main()