#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>

#define CHANNEL 4


int main(void) {
	int sock, client, alen;
	struct sockaddr_rc addr;
	struct hci_dev_info di;
	char buf;
	int byte;

	if (hci_devinfo(1, &di) < 0) {
		perror("HCI device info failed");
		exit(1);
	}
	sock = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
	if (sock < 0) {
		perror("socket");
		exit(1);
	}
	addr.rc_family = AF_BLUETOOTH;
	addr.rc_bdaddr = di.bdaddr;
	addr.rc_channel = htobs(CHANNEL);
	alen = sizeof(addr);
	BDADDR_ANY;
	if (bind(sock, (struct sockaddr *)&addr, alen) < 0) {
		perror("bind");
		exit(1);
	}
	listen(sock,QUEUE);
	printf("Waiting for connections...\n\n");
	client = accept(sock, (struct sockaddr *)&addr, &alen);
	if (client < 0) {
		perror("Error while connecting");
		exit(1);
	} else {
		printf("Connection established!\n");
	}
	int i = 0, size = 0;
	 
	// open file
	FILE *file_ptr;
	char filename[67];
	 
	printf("Filename: ");
	gets(filename);
	 
	file_ptr = fopen(filename,"wb");
	if (file_ptr != NULL) {
		printf("File opened\n");
	} else {
		perror("File cannot be opened.");
		exit(2);
	}
	 
	 
	// read data
	printf("Create file:\n");
	while (byte > 0) {
		byte = recv(client,&buf,sizeof(buf),0);
		if (byte > 0){
			i++;
			size += byte;
			//printf("Out:%i : %i = %c\n",i, byte, buf);
			if(i%10000 == 0){
			printf(".");
		}
		// write in file
		fputc(buf,file_ptr);
	}
	}
	// close file
	fclose(file_ptr);
	 
	printf ("\File size: %i\n", size);
	 
	close(client);
	close(sock);
	return 0;
}
