	.section	.text
	.intel_syntax
	.global	nanosleep
	.type	nanosleep, @function
nanosleep:
	push	%ebp
	mov	%ebp, %esp
	push	%ebx
	sub	%esp, 24		# Allocate space for a new records
	mov	%ebx, [%ebp + 8]	# Store first record in %ebx
	mov	%eax, [%ebx]		# %eax = ts.sec
	mov	%ecx, 1908874354	# %ecx = 1908874354
	imul	%ecx			# %edx:%eax = %eax * %ecx
	shrd	%eax, %edx, 30
	shr	%edx, 30
	mov	[%ebp - 20], %eax
	mov	[%ebp - 16], %edx	# Store 64-bit value in new record
	mov	%eax, [%ebx + 4]	# %eax = ts.usec
	imul	%ecx			# %edx:%eax = %eax * %ecx
	shrd	%eax, %edx, 30
	shr	%edx, 30
	cmp	%eax, 1000000000
	jl	nanosleep.fits
	mov	%edx, [%ebp - 20]
	add	%edx, 1
	mov	[%ebp - 20], %edx
	sub	%eax, 1000000000
nanosleep.fits:
	mov	[%ebp - 12], %eax	# Store %eax in new record
	mov	%ebx, 0			# CLOCK_REALTIME
	mov	%ecx, 0			# Absolute value
	lea	%edx, [%ebp - 20]	# Store new record in %eax
	mov	%esi, [%ebp + 12]	# %esi = second record
	cmp	%esi, 0
	je	nanosleep.system_call	# Do nothing if second record is null
	lea	%esi, [%ebp - 8]	# Address of space for second local record
nanosleep.system_call:
	mov	%eax, 407		# clock_nanosleep_time64 system call
	int	128
	je	nanosleep.end		# Do nothing if second record is null
	# TODO: convert legacy time to heximal time in second local record
	# then copy it to second record, if it isn't null
nanosleep.end:
	pop	%ebx
	mov	%esp, %ebp		# Deallocate space
	pop	%ebp
	ret
