#include <stdio.h>
#include <stdlib.h>
#include <math.h>

// Storing two 2D points and their distance.
typedef struct PointPair_t
{
    double x1, y1, x2, y2, dist;
}PointPair, *PPointPair;

// Storing pointer to PointPair in a linked list.
typedef struct PointPairNode_t
{
	PPointPair value;
	struct PointPairNode_t *next;
}PointPairNode, *PPointPairNode;

double distance(double x1, double y1, double x2, double y2)
{
	double dx = x2 - x1;
	double dy = y2 - y1;
	return sqrt((dx * dx) + (dy * dy));
}

// Sort array of pointer to PointPair using insertion sort.
void sortPointPairByDistance(PPointPair *arr, unsigned int count)
{
	int top = count - 2;
	int i;

	while(top >= 0)
	{
		PPointPair temp = arr[top];
		for(i = top; i < count - 1; ++i)
		{
			if(arr[i + 1]->dist >= temp->dist)
				break;
			arr[i] = arr[i + 1];
		}
		arr[i] = temp;
		--top;
	}
}

int main(int argc, char *argv[])
{
	PPointPairNode list = NULL;
	unsigned int pointPairCount = 0;
	PPointPair *arr = NULL;
	int i;
	PPointPairNode listPtr;

	FILE *fp;

	//fp = fopen("point.txt", "r");
	fp = stdin;
	if(fp)
	{
		while(!feof(fp))
		{
			double x1, y1, x2, y2;
			if(fscanf(fp, "%lf %lf %lf %lf", &x1, &y1, &x2, &y2) == 4)
			{
				// Allocate a node and a PointPair to store points and distances.
				PPointPairNode node = (PPointPairNode)malloc(sizeof(PointPairNode));
				node->value = (PPointPair)malloc(sizeof(PointPair));
				node->value->x1 = x1;
				node->value->y1 = y1;
				node->value->x2 = x2;
				node->value->y2 = y2;
				node->value->dist = distance(x1, y1, x2, y2);
				node->next = list;
				list = node;
				++pointPairCount;
				printf("Pair %u : { (%5.2lf, %5.2lf), (%5.2lf, %5.2lf) }  distance : %9.6lf\n",
					pointPairCount, x1, y1, x2, y2, node->value->dist);
			}
		}
		fclose(fp);
	}

	// Allocate an array and copy pointers into it for sorting.
	arr = (PPointPair *)malloc(pointPairCount * sizeof(PPointPair));
	for(i = pointPairCount - 1, listPtr = list; i >= 0; --i, listPtr = listPtr->next)
	{
		arr[i] = listPtr->value;
	}

	sortPointPairByDistance(arr, pointPairCount);

	//fp = fopen("point2.txt", "w");
	fp = stdout;
	if(fp)
	{
		for(i = 0; i < pointPairCount; ++i)
		{
			fprintf(fp, "%lf %lf %lf %lf\n", arr[i]->x1, arr[i]->y1, arr[i]->x2, arr[i]->y2);
		}
		fclose(fp);
	}

	// Free memory.
	free(arr);
	while(list)
	{
		listPtr = list->next;
		free(list->value);
		free(list);
		list = listPtr;
	}

	return 0;
}
