import math
def dis(a,b):
    x1,y1=a
    x2,y2=b
    return (x2-x1)**2+(y2-y1)**2

def rotate(origin, point, angle):
    """
    Rotate a point counterclockwise by a given angle around a given origin.

    The angle should be given in radians.
    """
    angle=math.radians(angle)
    ox, oy = origin
    px, py = point

    qx = round(ox + math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy),2)
    qy = round(oy + math.sin(angle) * (px - ox) + math.cos(angle) * (py - oy),2)
    return [qx, qy]
#print rotate([0,0],[1,1],90)
n=input()
arr=[]
for i in range(4*n):
    arr.append(map(int,raw_input().split()))
for i in range(0,4*n,4):
    #print i
    a,b,c,d=arr[i]
    p1=[]
    angle=0
    for j in range(4):
        p1.append(rotate([c,d],[a,b],angle))
        angle+=90
    a, b, c, d = arr[i+1]
    p2 = []
    angle = 0
    for j in range(4):
        p2.append(rotate([c, d], [a, b], angle))
        angle += 90
    a, b, c, d = arr[i+2]
    p3 = []
    angle = 0
    for j in range(4):
        p3.append(rotate([c, d], [a, b], angle))
        angle += 90
    a, b, c, d = arr[i+3]
    p4 = []
    angle = 0
    for j in range(4):
        p4.append(rotate([c, d], [a, b], angle))
        angle += 90
    s=100
    #if i==12:
        #print p1,p2,p3,p4
    for t in range(4):
        for j in range(4):
            for k in range(4):
                for l in range(4):
                    a=dis(p1[t],p2[j])
                    b=dis(p2[j],p3[k])
                    c=dis(p3[k],p4[l])
                    d=dis(p4[l],p1[t])
                    e=dis(p1[t],p3[k])
                    f=dis(p2[j],p4[l])
                    #if i==12:
                        #print p1[t],p2[j],p3[k],p4[l],a,b,c,d
                    a,b,c,d,e,f=sorted([a,b,c,d,e,f])
                    if a==b==c==d and e==f and a>0:
                        #print a,b,c,d,t,j,k,l
                        s=min(t+j+k+l,s)
    if s==100:
        print -1
    else:
        print s


from __future__ import division, print_function
# import threading
# threading.stack_size(2**27)
# import sys
# sys.setrecursionlimit(10**7)
from sys import stdin, stdout
import bisect            #c++ upperbound
import math
import heapq
i_m=9223372036854775807
def modinv(n,p):
    return pow(n,p-2,p)
def cin():
    return map(int,sin().split())
def ain():                           #takes array as input
    return list(map(int,sin().split()))
def sin():
    return input()
def inin():
    return int(input())
import math
def GCD(x, y):
    x=abs(x)
    y=abs(y)
    if(min(x,y)==0):
        return max(x,y)
    while(y):
        x, y = y, x % y
    return x
def Divisors(n) :
    l = []
    for i in range(1, int(math.sqrt(n) + 1)) :
        if (n % i == 0) :
            if (n // i == i) :
                l.append(i)
            else :
                l.append(i)
                l.append(n//i)
    return l

def SieveOfEratosthenes(n):
    prime = [True for i in range(n+1)]
    p = 2
    while (p * p <= n):
        if (prime[p] == True):
            for i in range(p * p, n+1, p):
                prime[i] = False
        p += 1
    f=[]
    for p in range(2, n):
        if prime[p]:
            f.append(p)
    return f
q=[]
def dfs(n,d,v,c):
    global q
    v[n]=1
    x=d[n]
    q.append(n)
    j=c
    for i in x:
        if i not in v:
            f=dfs(i,d,v,c+1)
            j=max(j,f)
            # print(f)
    return j

def help():
    res = 1000
    l = [list(map(int, input().split())) for _ in range(4)]
    for _1 in range(4):
        for _2 in range(4):
            for _3 in range(4):
                for _4 in range(4):
                    for i in range(_1): rot(l[0])
                    for i in range(_2): rot(l[1])
                    for i in range(_3): rot(l[2])
                    for i in range(_4): rot(l[3])
                    if square(l):
                        res = min(res, _1 + _2 + _3 + _4)
                    for i in range(4-_1): rot(l[0])
                    for i in range(4-_2): rot(l[1])
                    for i in range(4-_3): rot(l[2])
                    for i in range(4-_4): rot(l[3])
    return res

def rot(l):
    x = l[0]
    y = l[1]
    homex = l[2]
    homey = l[3]
    yabove = y - homey
    xright = x - homex
    newx = homex - yabove
    newy = homey + xright
    l[0] = newx
    l[1] = newy
    return l

def square(l):
    distances = list()
    for i in range(4):
        for j in range(i + 1, 4):
            distances.append(dist(l[i], l[j]))
    distances.sort()
    if distances[0] < 0.000001: return False #same point
    different = 0
    for i in range(len(distances) - 1):
        if abs(distances[i] - distances[i+1]) > 0.000001:
            different += 1
    return different == 1

def dist(a, b):
    return (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1])
"""*******************************************************"""
def main():
    n = int(input())
    for _ in range(n):
        t = help()
        print(-1 if t == 1000 else t)

######## Python 2 and 3 footer by Pajenegod and c1729

# Note because cf runs old PyPy3 version which doesn't have the sped up
# unicode strings, PyPy3 strings will many times be slower than pypy2.
# There is a way to get around this by using binary strings in PyPy3
# but its syntax is different which makes it kind of a mess to use.

# So on cf, use PyPy2 for best string performance.

py2 = round(0.5)
if py2:
    from future_builtins import ascii, filter, hex, map, oct, zip
    range = xrange

import os, sys
from io import IOBase, BytesIO

BUFSIZE = 8192
class FastIO(BytesIO):
    newlines = 0

    def __init__(self, file):
        self._file = file
        self._fd = file.fileno()
        self.writable = "x" in file.mode or "w" in file.mode
        self.write = super(FastIO, self).write if self.writable else None

    def _fill(self):
        s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
        self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
        return s

    def read(self):
        while self._fill(): pass
        return super(FastIO,self).read()

    def readline(self):
        while self.newlines == 0:
            s = self._fill(); self.newlines = s.count(b"\n") + (not s)
        self.newlines -= 1
        return super(FastIO, self).readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.getvalue())
            self.truncate(0), self.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        if py2:
            self.write = self.buffer.write
            self.read = self.buffer.read
            self.readline = self.buffer.readline
        else:
            self.write = lambda s:self.buffer.write(s.encode('ascii'))
            self.read = lambda:self.buffer.read().decode('ascii')
            self.readline = lambda:self.buffer.readline().decode('ascii')

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')

# Cout implemented in Python
import sys
class ostream:
    def __lshift__(self,a):
        sys.stdout.write(str(a))
        return self
cout = ostream()
endl = '\n'

# Read all remaining integers in stdin, type is given by optional argument, this is fast
def readnumbers(zero = 0):
    conv = ord if py2 else lambda x:x
    A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read()
    try:
        while True:
            if s[i] >= b'R' [0]:
                numb = 10 * numb + conv(s[i]) - 48
            elif s[i] == b'-' [0]: sign = -1
            elif s[i] != b'\r' [0]:
                A.append(sign*numb)
                numb = zero; sign = 1
            i += 1
    except:pass
    if s and s[-1] >= b'R' [0]:
        A.append(sign*numb)
    return A

# threading.Thread(target=main).start()
if __name__== "__main__":
  main()


import bisect
n = int(raw_input())
for i in xrange(n):
	xy=[]
	for j in range(4):
		xy.append( map(int, raw_input().split() ) )
	mina = 99
	for bmask in xrange(2**8):
		rotatsum = (bmask&3) + ((bmask>>2)&3) + ((bmask>>4)&3) + ((bmask>>6)&3)
		def rotat(a):
			a[0]-=a[2]
			a[1]-=a[3]
			a[0],a[1] = -a[1],a[0]
			a[0]+=a[2]
			a[1]+=a[3]
		distar=[]
		def sqrhypot(a,b):
			return a*a+b*b
		for ii in xrange(3):
			for jj in xrange(ii+1,4):
				distar.append(sqrhypot(xy[ii][0]-xy[jj][0], xy[ii][1]-xy[jj][1]))
		distar = sorted(distar)
		if(distar[0]==distar[3] and distar[4]==distar[5] and distar[3]*2==distar[4]
			and distar[0]!=0 and mina> rotatsum): mina = rotatsum
		rotat(xy[0])
		if(bmask&0x3==3): rotat(xy[1])
		if(bmask&0xF==0xF): rotat(xy[2])
		if(bmask&0x3F==0x3F): rotat(xy[3])
	if mina==99: mina=-1
	print mina


from sys import stdin,stdout,setrecursionlimit,maxint,exit
#setrecursionlimit(2*10**5)
def listInput():
 return map(long,stdin.readline().split())
def printBS(li):
 for i in xrange(len(li)-1):
  stdout.write("%d "%li[i])
 stdout.write("%d\n"%li[-1])
def sin():
 return stdin.readline().rstrip()
def rotate(p,o): return (o[0]+o[1]-p[1],p[0]-o[0]+o[1])
def rotaten(p,o,n):
 #rotate p about o n times by 90deg
 for i in xrange(n):
  p=rotate(p,o)
 return tuple(p)
"""print rotaten([2,2],[0,1],2)
print rotaten([-1,0],[0,-2],0)
print rotaten([3,0],[0,-2],1)
print rotaten([-1,1],[-2,0],0)"""
def check(a,b,c,d):
 s=set([a,b,c,d])
 if len(s)!=4: return False
 d1=(a[0]-b[0])**2+(a[1]-b[1])**2
 d2=(a[0]-c[0])**2+(a[1]-c[1])**2
 d3=(a[0]-d[0])**2+(a[1]-d[1])**2
 #print d1,d2,d3
 t=0
 diag=0
 td=0
 if d1==d2:
  td=d1
  t=3
  diag=d3
 elif d2==d3:
  t=1
  td=d2
  diag=d1
 elif d1==d3:
  t=2
  td=d3
  diag=d2
 else: return False
 pts=[a,b,c,d]
 #print pts[t],td
 diff=0
 oth=[]
 for i in xrange(1,4):
  if i!=t:
   oth.append(pts[i])
   diff=(pts[i][0]-pts[t][0])**2+(pts[i][1]-pts[t][1])**2
   if diff!=td:
    #print "diff",pts[i],diff
    return False
 if td==0 or diag!=((oth[0][0]-oth[1][0])**2+(oth[0][1]-oth[1][1])**2): return False
 return True
#print check((-1,0),(-2,0),(-1,1),(-2,1))
from itertools import product
n=int(sin())
for i in xrange(n):
 pt=[]
 org=[]
 it=[0,1,2,3]
 for j in it:
  inp=listInput()
  pt.append(tuple(inp[:2]))
  org.append(tuple(inp[2:]))
 poss=product(it,it,it,it)
 ans=maxint
 for cnt in poss:
  if check(rotaten(pt[0],org[0],cnt[0]),rotaten(pt[1],org[1],cnt[1]),rotaten(pt[2],org[2],cnt[2]),rotaten(pt[3],org[3],cnt[3])):
   #print cnt
   #print (rotaten(pt[0],org[0],cnt[0]),rotaten(pt[1],org[1],cnt[1]),rotaten(pt[2],org[2],cnt[2]),rotaten(pt[3],org[3],cnt[3]))
   ans=min(ans,sum(cnt))
 if ans==maxint:
  print -1
 else : print ans


from sys import stdin,stdout,setrecursionlimit,maxint,exit
#setrecursionlimit(2*10**5)
def listInput():
 return map(long,stdin.readline().split())
def printBS(li):
 for i in xrange(len(li)-1):
  stdout.write("%d "%li[i])
 stdout.write("%d\n"%li[-1])
def sin():
 return stdin.readline().rstrip()
def rotate(p,o): return (o[0]+o[1]-p[1],p[0]-o[0]+o[1])
def rotaten(p,o,n):
 #rotate p about o n times by 90deg
 for i in xrange(n):
  p=rotate(p,o)
 return tuple(p)
"""print rotaten([2,2],[0,1],2)
print rotaten([-1,0],[0,-2],0)
print rotaten([3,0],[0,-2],1)
print rotaten([-1,1],[-2,0],0)"""
def check(a,b,c,d):
 s=set([a,b,c,d])
 if len(s)!=4: return False
 d1=(a[0]-b[0])**2+(a[1]-b[1])**2
 d2=(a[0]-c[0])**2+(a[1]-c[1])**2
 d3=(a[0]-d[0])**2+(a[1]-d[1])**2
 #print d1,d2,d3
 t=0
 td=0
 if d1==d2:
  td=d1
  t=3
 elif d2==d3:
  t=1
  td=d2
 elif d1==d3:
  t=2
  td=d3
 else: return False
 pts=[a,b,c,d]
 #print pts[t],td
 diff=0
 for i in xrange(1,4):
  if i!=t:
   diff=(pts[i][0]-pts[t][0])**2+(pts[i][1]-pts[t][1])**2
   if diff!=td:
    #print "diff",pts[i],diff
    return False
 if td==0: return False
 return True
#print check((-1,0),(-2,0),(-1,1),(-2,1))
from itertools import product
n=int(sin())
for i in xrange(n):
 pt=[]
 org=[]
 it=[0,1,2,3]
 for j in it:
  inp=listInput()
  pt.append(tuple(inp[:2]))
  org.append(tuple(inp[2:]))
 poss=product(it,it,it,it)
 ans=maxint
 for cnt in poss:
  if check(rotaten(pt[0],org[0],cnt[0]),rotaten(pt[1],org[1],cnt[1]),rotaten(pt[2],org[2],cnt[2]),rotaten(pt[3],org[3],cnt[3])):
   #print cnt
   #print (rotaten(pt[0],org[0],cnt[0]),rotaten(pt[1],org[1],cnt[1]),rotaten(pt[2],org[2],cnt[2]),rotaten(pt[3],org[3],cnt[3]))
   ans=min(ans,sum(cnt))
 if ans==maxint:
  print -1
 else : print ans


#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M=10**9+7
EPS=1e-6
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]

#-------------------------code---------------------------#
# vsInput()

def RotateAntiClockBy90(P,H):
    x,y=P
    a,b=H

    x-=a
    y-=b

    X=-y+a
    Y=x+b
    return (X,Y)

def Dist(p1,p2):
    return (p2[1]-p1[1])**2 + (p2[0]-p1[0])**2

def isSquare(P):

    p1,p2,p3,p4=P
    # print(p1,p2,p3,p4)

    d2 = Dist(p1,p2)
    d3 = Dist(p1,p3)
    d4 = Dist(p1,p4)

    if(d2==0 or d3==0 or d4==0):
        return False
    if(d2==d3 and 2*d2==d4 and 2*Dist(p2,p4)==Dist(p2,p3)):
        return True
    if(d3==d4 and 2*d3==d2 and 2*Dist(p3,p2)==Dist(p3,p4)):
        return True
    if(d2==d4 and 2*d2==d3 and 2*Dist(p2,p3)==Dist(p2,p4)):
        return True
    return False

for _ in range(Int()):

    home=[]
    point=[]
    for i in range(4):
        V=value()
        point.append((V[0],V[1]))
        home.append((V[2],V[3]))
    ans=[inf]
    heapify(ans)

    # print(point)
    # print(home)
    # print()

    for i in range(4):

        point[0]=RotateAntiClockBy90(point[0],home[0])
        cost1=(i+1)%4
        for j in range(4):

            cost2=(j+1)%4
            point[1]=RotateAntiClockBy90(point[1],home[1])
            for k in range(4):

                cost3=(k+1)%4
                point[2]=RotateAntiClockBy90(point[2],home[2])
                for l in range(4):

                    cost4=(l+1)%4
                    point[3]=RotateAntiClockBy90(point[3],home[3])

                    if(isSquare(point)):
                        # print(point,cost1+cost2+cost3+cost4)
                        heappush(ans,cost1+cost2+cost3+cost4)

    ans=heappop(ans)
    if(ans==inf):ans=-1
    print(ans)


n = int(input())

for reg in range(n):
    moles = []
    for i in range(4):
        moles.append([int(x) for x in input().split()])

    pos = []

    for x,y,a,b in moles:
        x -= a
        y -= b
        p = [(x,y)]
        #print(x,y,a,b)
        #print(x,y)
        for bruh in range(3):
            x,y = -y,x
            #print(x,y)
            p.append((x,y))
        pos.append([(c[0]+a, c[1]+b) for c in p])

    low = float('inf')

    for a in range(4):
        for b in range(4):
            for c in range(4):
                for d in range(4):
                    points = [pos[0][a], pos[1][b], pos[2][c], pos[3][d]]
                    points.sort()
                    if (points[0][0] == points[1][0] and points[2][0] == points[3][0]
                        and points[0][1] == points[2][1] and points [1][1] == points[3][1]
                        and points[3][0] - points[0][0] == points[3][1]-points[0][1]
                        and points[3] != points[0]):
                        low = min(low, a+b+c+d)
    if low == float('inf'):
        print(-1)
    else:
        print(low)


n = int(input())

def isSquare(a,b,c,d):
    if 2*((b[0]-a[0])**2+(b[1]-a[1])**2) == 2*((c[0]-a[0])**2+(c[1]-a[1])**2) == (d[0]-a[0])**2+(d[1]-a[1])**2 == (b[0]-c[0])**2+(b[1]-c[1])**2 == 2*((d[0]-c[0])**2+(d[1]-c[1])**2) == 2*((d[0]-b[0])**2+(d[1]-b[1])**2) and a != d:
        return True
    return False

for reg in range(n):
    moles = []
    for i in range(4):
        moles.append([int(x) for x in input().split()])

    pos = []

    for x,y,a,b in moles:
        x -= a
        y -= b
        p = [(x,y)]
        #print(x,y,a,b)
        #print(x,y)
        for bruh in range(3):
            x,y = -y,x
            #print(x,y)
            p.append((x,y))
        pos.append([(c[0]+a, c[1]+b) for c in p])

    low = float('inf')

    for a in range(4):
        for b in range(4):
            for c in range(4):
                for d in range(4):
                    points = [pos[0][a], pos[1][b], pos[2][c], pos[3][d]]
                    points.sort()
                    if isSquare(points[0], points[1], points[2], points[3]):
                        low = min(low, a+b+c+d)
    if low == float('inf'):
        print(-1)
    else:
        print(low)


import sys

inf = float("inf")
# sys.setrecursionlimit(10000000)

# abc='abcdefghijklmnopqrstuvwxyz'
# abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
# mod, MOD = 1000000007, 998244353
# words = {1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine',10:'ten',11:'eleven',12:'twelve',13:'thirteen',14:'fourteen',15:'quarter',16:'sixteen',17:'seventeen',18:'eighteen',19:'nineteen',20:'twenty',21:'twenty one',22:'twenty two',23:'twenty three',24:'twenty four',25:'twenty five',26:'twenty six',27:'twenty seven',28:'twenty eight',29:'twenty nine',30:'half'}
# vow=['a','e','i','o','u']
# dx,dy=[0,1,0,-1],[1,0,-1,0]

# import random
# from collections import deque, Counter, OrderedDict,defaultdict
# from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
# from math import ceil,floor,log,sqrt,factorial,pi,gcd,sin,cos
# from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right

def get_array(): return list(map(int, sys.stdin.readline().strip().split()))
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def input(): return sys.stdin.readline().strip()

def function(x,y):
    if x<0 and y>0:
        lst = [[x,y],[-y,x],[-x,-y],[y,-x]]
    elif x<0 and y<0:
        lst = [[x,y],[-y,x],[-x,-y],[-y,x]]
    elif x>0 and y<0:
        lst = [[x,y],[-y,x],[-x,-y],[y,-x]]
    elif x>0 and y>0:
        lst = [[x,y],[-y,x],[-x,-y],[y,-x]]
    return lst

def give_me(x,y,a,b):
    x,y = x-a,y-b
    lst = function(x,y)
    for i in range(4):
        lst[i][0]+=a
        lst[i][1]+=b
    return lst

def distsq(p,q):
    return (p[0] - q[0]) * (p[0] - q[0]) + (p[1] - q[1]) * (p[1] - q[1])

def is_square(p1,p2,p3,p4):

    if p1==p2==p3==p4:
        return False

    d2 = distsq(p1, p2)
    d3 = distsq(p1, p3)
    d4 = distsq(p1, p4)

    if d2 == d3 and 2*d2 == d4 and 2*distsq(p2,p4) == distsq(p2, p3):
        return True
    if (d3 == d4 and 2 * d3 == d2 and 2*distsq(p3, p2) == distsq(p3, p4)):
        return True
    if (d2 == d4 and 2*d2 == d3 and 2*distsq(p2, p3)==distsq(p2, p4)):
        return True
    return False

n = int(input())
for i in range(n):
    x1,y1,a1,b1 = get_ints()
    x2,y2,a2,b2 = get_ints()
    x3,y3,a3,b3 = get_ints()
    x4,y4,a4,b4 = get_ints()

    lst1 = give_me(x1,y1,a1,b1)
    lst2 = give_me(x2,y2,a2,b2)
    lst3 = give_me(x3,y3,a3,b3)
    lst4 = give_me(x4,y4,a4,b4)

    # print(lst1)
    # print(lst2)
    # print(lst3)
    # print(lst4)

    flag = 0
    mini = inf
    for i,w in enumerate(lst1):
        for j,x in enumerate(lst2):
            for k,y in enumerate(lst3):
                for l,z in enumerate(lst4):
                    if is_square(w,x,y,z):
                        flag = 1
                        curr  = i+j+k+l
                        if curr<mini:
                            mini = curr
                            # print(i,j,k,l)
    if flag==0:
        print(-1)
    else:
        print(mini)


import sys

inf = float("inf")
# sys.setrecursionlimit(10000000)

# abc='abcdefghijklmnopqrstuvwxyz'
# abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
# mod, MOD = 1000000007, 998244353
# words = {1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine',10:'ten',11:'eleven',12:'twelve',13:'thirteen',14:'fourteen',15:'quarter',16:'sixteen',17:'seventeen',18:'eighteen',19:'nineteen',20:'twenty',21:'twenty one',22:'twenty two',23:'twenty three',24:'twenty four',25:'twenty five',26:'twenty six',27:'twenty seven',28:'twenty eight',29:'twenty nine',30:'half'}
# vow=['a','e','i','o','u']
# dx,dy=[0,1,0,-1],[1,0,-1,0]

# import random
# from collections import deque, Counter, OrderedDict,defaultdict
# from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
# from math import ceil,floor,log,sqrt,factorial,pi,gcd,sin,cos
# from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right

def get_array(): return list(map(int, sys.stdin.readline().strip().split()))
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def input(): return sys.stdin.readline().strip()

def function(x,y):
    return [[x,y],[-y,x],[-x,-y],[y,-x]]

def give_me(x,y,a,b):
    x,y = x-a,y-b
    lst = function(x,y)
    for i in range(4):
        lst[i][0]+=a
        lst[i][1]+=b
    return lst

def distsq(p,q):
    return (p[0] - q[0])*(p[0] - q[0]) + (p[1] - q[1])*(p[1] - q[1])

def is_square(p1,p2,p3,p4):

    if p1==p2==p3==p4:
        return False

    d2 = distsq(p1, p2)
    d3 = distsq(p1, p3)
    d4 = distsq(p1, p4)

    if d2 == d3 and 2*d2 == d4 and 2*distsq(p2,p4) == distsq(p2, p3):
        return True
    if (d3 == d4 and 2*d3 == d2 and 2*distsq(p3, p2) == distsq(p3, p4)):
        return True
    if (d2 == d4 and 2*d2 == d3 and 2*distsq(p2, p3)==distsq(p2, p4)):
        return True
    return False

n = int(input())
for m in range(n):
    x1,y1,a1,b1 = get_ints()
    x2,y2,a2,b2 = get_ints()
    x3,y3,a3,b3 = get_ints()
    x4,y4,a4,b4 = get_ints()

    lst1 = give_me(x1,y1,a1,b1)
    lst2 = give_me(x2,y2,a2,b2)
    lst3 = give_me(x3,y3,a3,b3)
    lst4 = give_me(x4,y4,a4,b4)

    flag = 0
    mini = inf
    for i,w in enumerate(lst1):
        for j,x in enumerate(lst2):
            for k,y in enumerate(lst3):
                for l,z in enumerate(lst4):
                    if is_square(w,x,y,z):
                        flag = 1
                        curr  = i+j+k+l
                        if curr<mini:
                            mini = curr
                            # print(i,j,k,l)
    if flag==0:
        print(-1)
    else:
        print(mini)


import sys

inf = float("inf")
# sys.setrecursionlimit(10000000)

# abc='abcdefghijklmnopqrstuvwxyz'
# abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
# mod, MOD = 1000000007, 998244353
# words = {1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine',10:'ten',11:'eleven',12:'twelve',13:'thirteen',14:'fourteen',15:'quarter',16:'sixteen',17:'seventeen',18:'eighteen',19:'nineteen',20:'twenty',21:'twenty one',22:'twenty two',23:'twenty three',24:'twenty four',25:'twenty five',26:'twenty six',27:'twenty seven',28:'twenty eight',29:'twenty nine',30:'half'}
# vow=['a','e','i','o','u']
# dx,dy=[0,1,0,-1],[1,0,-1,0]

# import random
# from collections import deque, Counter, OrderedDict,defaultdict
# from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
# from math import ceil,floor,log,sqrt,factorial,pi,gcd,sin,cos
# from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right

def get_array(): return list(map(int, sys.stdin.readline().strip().split()))
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def input(): return sys.stdin.readline().strip()

def function(x,y):
    if x<0 and y>0:
        lst = [[x,y],[-y,x],[-x,-y],[y,-x]]
    elif x<0 and y<0:
        lst = [[x,y],[-y,x],[-x,-y],[y,-x]]
    elif x>0 and y<0:
        lst = [[x,y],[-y,x],[-x,-y],[y,-x]]
    elif x>0 and y>0:
        lst = [[x,y],[-y,x],[-x,-y],[y,-x]]
    return lst

def give_me(x,y,a,b):
    x,y = x-a,y-b
    lst = function(x,y)
    for i in range(4):
        lst[i][0]+=a
        lst[i][1]+=b
    return lst

def distsq(p,q):
    return (p[0] - q[0]) * (p[0] - q[0]) + (p[1] - q[1]) * (p[1] - q[1])

def is_square(p1,p2,p3,p4):

    if p1==p2==p3==p4:
        return False

    d2 = distsq(p1, p2)
    d3 = distsq(p1, p3)
    d4 = distsq(p1, p4)

    if d2 == d3 and 2*d2 == d4 and 2*distsq(p2,p4) == distsq(p2, p3):
        return True
    if (d3 == d4 and 2*d3 == d2 and 2*distsq(p3, p2) == distsq(p3, p4)):
        return True
    if (d2 == d4 and 2*d2 == d3 and 2*distsq(p2, p3)==distsq(p2, p4)):
        return True
    return False

n = int(input())
for i in range(n):
    x1,y1,a1,b1 = get_ints()
    x2,y2,a2,b2 = get_ints()
    x3,y3,a3,b3 = get_ints()
    x4,y4,a4,b4 = get_ints()

    lst1 = give_me(x1,y1,a1,b1)
    lst2 = give_me(x2,y2,a2,b2)
    lst3 = give_me(x3,y3,a3,b3)
    lst4 = give_me(x4,y4,a4,b4)

    # print(lst1)
    # print(lst2)
    # print(lst3)
    # print(lst4)

    flag = 0
    mini = inf
    for i,w in enumerate(lst1):
        for j,x in enumerate(lst2):
            for k,y in enumerate(lst3):
                for l,z in enumerate(lst4):
                    if is_square(w,x,y,z):
                        flag = 1
                        curr  = i+j+k+l
                        if curr<mini:
                            mini = curr
                            # print(i,j,k,l)
    if flag==0:
        print(-1)
    else:
        print(mini)


import copy
import sys

def solve():
    n = int(input())
    for reg in range(n):
        temp = help()
        print(-1 if temp == 1000 else temp)

def help():
    res = 1000
    read = [list(map(int, input().split())) for _ in range(4)]
    for _1 in range(4):
        for _2 in range(4):
            for _3 in range(4):
                for _4 in range(4):
                    l = copy.deepcopy(read)
                    for i in range(_1): rot(l[0])
                    for i in range(_2): rot(l[1])
                    for i in range(_3): rot(l[2])
                    for i in range(_4): rot(l[3])
                    if square(l):
                        res = min(res, _1 + _2 + _3 + _4)
    return res

def rot(l):
    x = l[0]
    y = l[1]
    homex = l[2]
    homey = l[3]
    yabove = y - homey
    xright = x - homex
    newx = homex - yabove
    newy = homey + xright
    l[0] = newx
    l[1] = newy
    return l

def square(l):
    distances = list()
    for i in range(4):
        for j in range(i + 1, 4):
            distances.append(dist(l[i], l[j]))
    distances.sort()
    if distances[0] < 0.000001: return False #same point
    different = 0
    for i in range(len(distances) - 1):
        if abs(distances[i] - distances[i+1]) > 0.000001:
            different += 1
    return different == 1

def dist(a, b):
    return (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1])

if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
# print(rot(rot(rot(rot([-11, -22, 2, 3])))))
solve()


import copy
import sys

def solve():
    n = int(input())
    for reg in range(n):
        temp = help()
        print(-1 if temp == 1000 else temp)

def help():
    res = 1000
    l = [list(map(int, input().split())) for _ in range(4)]
    for _1 in range(4):
        for _2 in range(4):
            for _3 in range(4):
                for _4 in range(4):
                    for i in range(_1): rot(l[0])
                    for i in range(_2): rot(l[1])
                    for i in range(_3): rot(l[2])
                    for i in range(_4): rot(l[3])
                    if square(l):
                        res = min(res, _1 + _2 + _3 + _4)
                    for i in range(4-_1): rot(l[0])
                    for i in range(4-_2): rot(l[1])
                    for i in range(4-_3): rot(l[2])
                    for i in range(4-_4): rot(l[3])
    return res

def rot(l):
    x = l[0]
    y = l[1]
    homex = l[2]
    homey = l[3]
    yabove = y - homey
    xright = x - homex
    newx = homex - yabove
    newy = homey + xright
    l[0] = newx
    l[1] = newy
    return l

def square(l):
    distances = list()
    for i in range(4):
        for j in range(i + 1, 4):
            distances.append(dist(l[i], l[j]))
    distances.sort()
    if distances[0] < 0.000001: return False #same point
    different = 0
    for i in range(len(distances) - 1):
        if abs(distances[i] - distances[i+1]) > 0.000001:
            different += 1
    return different == 1

def dist(a, b):
    return (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1])

if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
# print(rot(rot(rot(rot([-11, -22, 2, 3])))))
solve()


import collections
import fileinput
import itertools

inp = fileinput.input()

Vect = collections.namedtuple('Vect', ('x', 'y'))
Mole = collections.namedtuple('Mole', ('pos', 'home'))

nullvect = Vect(0, 0)

def subtract(v1, v2):
    return Vect(v2.x - v1.x, v2.y - v1.y)

def add(v1, v2):
    return Vect(v1.x + v2.x, v1.y + v2.y)

def distance_squared(v1, v2):
    r""" Returns the distance without calculating the square root to speed it up a bit."""
    d = subtract(v1, v2)
    l = d.x**2 + d.y**2
    return l

def rotate_cw(m):
    return Vect(m.y, -m.x)

def rotate_ccw(m):
    return Vect(-m.y, m.x)

def move(m, times=1):
    tv = subtract(m.home, m.pos)
    for _ in range(times):
        tv = rotate_ccw(tv)
    return Mole(add(m.home, tv), m.home)

def is_compact(regiment):
    for i in range(3):
        r = regiment[:3]
        m = r.pop(i)
        d1 = subtract(m.pos, r[0].pos)
        d2 = subtract(m.pos, r[1].pos)
        if d1 == nullvect or d2 == nullvect:
            return False

        if rotate_ccw(d1) == d2 or rotate_cw(d1) == d2:
            m4_pos = add(m.pos, d1)
            m4_pos = add(m4_pos, d2)
            if m4_pos == regiment[3].pos:
                return True

    return False

def brute(regiment):
    min_moves = 2**32
    for moves in itertools.product(range(4), repeat=4):
        move_count = sum(moves)
        if move_count >= min_moves:
            continue

        reg = [move(regiment[idx], moves[idx]) for idx in range(len(moves))]
        if is_compact(reg):
            min_moves = move_count

    if min_moves < 2**32:
        return min_moves
    else:
        return -1

def solve():
    n = int(next(inp))
    regiments = [[None]*4 for _ in range(n)]
    for i in range(n):
        for ridx, line in enumerate(itertools.islice(inp, 0, 4)):
            coords = [int(i) for i in line.strip().split()]
            pos = Vect(coords[0], coords[1])
            home = Vect(coords[2], coords[3])
            regiments[i][ridx] = Mole(pos, home)

        res = brute(regiments[i])
        print(res)

if __name__ == '__main__':
    solve()


def r(t): t[0], t[1] = t[2] + t[3] - t[1], t[3] + t[0] - t[2]
f = range(4)
g = lambda u, v: (u[0] - v[0]) ** 2 + (u[1] - v[1]) ** 2
h = [(i, j) for i in f for j in f if i < j]
for i in range(int(input())):
    p = [list(map(int, input().split())) for j in f]
    s = 13
    for a in f:
        for b in f:
            for c in f:
                for d in f:
                    t = sorted(g(p[u], p[v]) for u, v in h)
                    if 0 != t[4] == t[5] == 2 * t[0] == 2 * t[3]: s = min(s, a + b + c + d)
                    r(p[3])
                r(p[2])
            r(p[1])
        r(p[0])
    print(s if s < 13 else -1)


#a+b-y
#x+b-a
#1 -
import sys
input=sys.stdin.readline
def distSq(p1,p2):
    return (p1[0]-p2[0])*(p1[0]-p2[0])+(p1[1]-p2[1])*(p1[1]-p2[1])
def isSquare(p1, p2, p3, p4):

    d2 = distSq(p1, p2) # from p1 to p2
    d3 = distSq(p1, p3) # from p1 to p3
    d4 = distSq(p1, p4) # from p1 to p4

    # If lengths if (p1, p2) and (p1, p3) are same, then
    # following conditions must be met to form a square.
    # 1) Square of length of (p1, p4) is same as twice
    # the square of (p1, p2)
    # 2) Square of length of (p2, p3) is same
    # as twice the square of (p2, p4)

    if d2 == d3 and 2 * d2 == d4 and  2 * distSq(p2, p4) == distSq(p2, p3):
        return True

    # The below two cases are similar to above case
    if d3 == d4 and 2 * d3 == d2 and  2 * distSq(p3, p2) == distSq(p3, p4):
        return True

    if d2 == d4 and 2 * d2 == d3 and  2 * distSq(p2, p3) == distSq(p2, p4):
        return True

    return False
for _ in range(int(input())):
    l=[]
    for i in range(4):
        x,y,a,b=map(int,input().split())
        for j in range(4):
            l.append([x,y,j])
            x,y=a+b-y,x+b-a
    mini=10**9
    for i in range(4):
        for j in range(4,8):
            for k in range(8,12):
                for z in range(12,16):
                    if i==j or j==k or i==k or i==z or j==z or k==z:
                        continue
                    if isSquare(l[i],l[j],l[k],l[z]):
                       # print(l[i],l[j],l[k],l[z])
                        curr=l[i][2]+l[j][2]+l[k][2]+l[z][2]
                        if curr<mini:
                            mini=curr
    print(mini if mini<10**9 else -1)


#a+b-y
#x+b-a

#1 -
import sys
input=sys.stdin.readline
def distSq(p1,p2):
    return (p1[0]-p2[0])*(p1[0]-p2[0])+(p1[1]-p2[1])*(p1[1]-p2[1])
def isSquare(p1, p2, p3, p4):

    d2 = distSq(p1, p2) # from p1 to p2
    d3 = distSq(p1, p3) # from p1 to p3
    d4 = distSq(p1, p4) # from p1 to p4

    # If lengths if (p1, p2) and (p1, p3) are same, then
    # following conditions must be met to form a square.
    # 1) Square of length of (p1, p4) is same as twice
    # the square of (p1, p2)
    # 2) Square of length of (p2, p3) is same
    # as twice the square of (p2, p4)

    if d2 == d3 and 2 * d2 == d4 and  2 * distSq(p2, p4) == distSq(p2, p3):
        return True

    # The below two cases are similar to above case
    if d3 == d4 and 2 * d3 == d2 and  2 * distSq(p3, p2) == distSq(p3, p4):
        return True

    if d2 == d4 and 2 * d2 == d3 and  2 * distSq(p2, p3) == distSq(p2, p4):
        return True

    return False
for _ in range(int(input())):
    l=[]
    for i in range(4):
        x,y,a,b=map(int,input().split())
        for j in range(4):
            l.append([x,y,j])
            x,y=a+b-y,x+b-a
    mini=10**9
    for i in range(4):
        for j in range(4,8):
            for k in range(8,12):
                for z in range(12,16):
                    if i==j or j==k or i==k or i==z or j==z or k==z:
                        continue
                    if isSquare(l[i],l[j],l[k],l[z]):
                       # print(l[i],l[j],l[k],l[z])
                        curr=l[i][2]+l[j][2]+l[k][2]+l[z][2]
                        if curr<mini:
                            mini=curr
    print(mini if mini<10**9 else -1)


#a+b-y
#x+b-a
#1 -
import sys
input=sys.stdin.readline
def distSq(p1,p2):
    return (p1[0]-p2[0])*(p1[0]-p2[0])+(p1[1]-p2[1])*(p1[1]-p2[1])
def isSquare(p1, p2, p3, p4):

    d2 = distSq(p1, p2) # from p1 to p2
    d3 = distSq(p1, p3) # from p1 to p3
    d4 = distSq(p1, p4) # from p1 to p4

    # If lengths if (p1, p2) and (p1, p3) are same, then
    # following conditions must be met to form a square.
    # 1) Square of length of (p1, p4) is same as twice
    # the square of (p1, p2)
    # 2) Square of length of (p2, p3) is same
    # as twice the square of (p2, p4)

    if d2 == d3 and 2 * d2 == d4 and  2 * distSq(p2, p4) == distSq(p2, p3):
        return True

    # The below two cases are similar to above case
    if d3 == d4 and 2 * d3 == d2 and  2 * distSq(p3, p2) == distSq(p3, p4):
        return True

    if d2 == d4 and 2 * d2 == d3 and  2 * distSq(p2, p3) == distSq(p2, p4):
        return True

    return False
for _ in range(int(input())):
    l=[]
    for i in range(4):
        x,y,a,b=map(int,input().split())
        for j in range(4):
            l.append([x,y,j])
            x,y=a+b-y,x+b-a
    mini=10**9
    for i in range(4):
        for j in range(4,8):
            for k in range(8,12):
                for z in range(12,16):
                    if l[i]==l[j] or l[j]==l[k] or l[i]==l[k] or l[i]==l[z] or l[j]==l[z] or l[k]==l[z]:
                        continue
                    if isSquare(l[i],l[j],l[k],l[z]):
                       # print(l[i],l[j],l[k],l[z])
                        curr=l[i][2]+l[j][2]+l[k][2]+l[z][2]
                        #print(curr)
                        if curr<mini:
                            mini=curr
    print(mini if mini<10**9 else -1)


using System;
using System.Linq;
using System.Text;

namespace CaptainMarmot
{
    partial class CaptainMarmot
    {
        static void Main(string[] args)
        {
            int n, min, total;
            bool foundAnswer = false;
            Mole[] moles = new Mole[4];
            Point[] current = new Point[4];
            StringBuilder answers = new StringBuilder();

            n = NextInt();

            for (int i = 0; i < 4; i++)
            {
                moles[i] = new Mole { Position = new Point(), Home = new Point() };
                current[i] = new Point();
            }

            for (int i = 0; i < n; i++)
            {
                min = int.MaxValue;
                foundAnswer = false;

                for (int j = 0; j < 4; j++)
                {
                    moles[j].Position.X = NextInt();
                    moles[j].Position.Y = NextInt();
                    moles[j].Home.X = NextInt();
                    moles[j].Home.Y = NextInt();

                    current[j].X = moles[j].Position.X;
                    current[j].Y = moles[j].Position.Y;
                }

                for (int a = 0; a < 4; a++)
                {
                    if (a > 0)
                        current[0].Rotate(moles[0].Home.X, moles[0].Home.Y);
                    else
                    {
                        current[0].X = moles[0].Position.X;
                        current[0].Y = moles[0].Position.Y;
                    }

                    for (int b = 0; b < 4; b++)
                    {
                        if (b > 0)
                            current[1].Rotate(moles[1].Home.X, moles[1].Home.Y);
                        else
                        {
                            current[1].X = moles[1].Position.X;
                            current[1].Y = moles[1].Position.Y;
                        }

                        for (int c = 0; c < 4; c++)
                        {
                            if (c > 0)
                                current[2].Rotate(moles[2].Home.X, moles[2].Home.Y);
                            else
                            {
                                current[2].X = moles[2].Position.X;
                                current[2].Y = moles[2].Position.Y;
                            }

                            for (int d = 0; d < 4; d++)
                            {
                                if (d > 0)
                                    current[3].Rotate(moles[3].Home.X, moles[3].Home.Y);
                                else
                                {
                                    current[3].X = moles[3].Position.X;
                                    current[3].Y = moles[3].Position.Y;
                                }

                                total = a + b + c + d;

                                if (IsSquare(current))
                                {
                                    foundAnswer = true;

                                    if (total < min)
                                        min = total;
                                }
                            }
                        }
                    }
                }

                if (foundAnswer)
                    answers.AppendFormat("{0}\n", min);
                else
                    answers.AppendLine("-1");
            }

            Console.Write(answers);
        }

        private static bool IsSquare(Point[] points)
        {
            if (points[0].Equals(points[1]) || points[1].Equals(points[2]) || points[2].Equals(points[3]))
                return false;

            Tuple<Point, long>[] distances = new Tuple<Point, long>[3];
            int ctr = 0;

            foreach (Point point in points.Except(new[] { points[0] }))
                distances[ctr++] = Tuple.Create(point, point.Distance(points[0]));

            distances = distances.OrderBy(d => d.Item2).ToArray();

            if (distances[0].Item2 != distances[1].Item2)
                return false;

            Point origin = distances[0].Item1;
            return origin.Distance(distances[2].Item1) == origin.Distance(points[0]) && origin.Distance(distances[1].Item1) == points[0].Distance(distances[2].Item1);
        }

    }

    public class Point
    {
        public int X { get; set; }
        public int Y { get; set; }

        public long Distance(Point otherPoint)
        {
            return (long)Math.Pow(Math.Abs(X - otherPoint.X), 2) + (long)Math.Pow(Math.Abs(Y - otherPoint.Y), 2);
        }

        public override bool Equals(object obj)
        {
            return X == ((Point)obj).X && Y == ((Point)obj).Y;
        }

        public void Rotate(int x, int y)
        {
            double angle = 90.0 * Math.PI / 180;
            double cos = Math.Cos(angle);
            double sin = Math.Sin(angle);
            int dx = X - x;
            int dy = Y - y;
            double cx = cos * dx - sin * dy + x;
            double cy = sin * dx + cos * dy + y;

            X = (int)Math.Round(cx);
            Y = (int)Math.Round(cy);
        }
    }

    public class Mole
    {
        public Point Position { get; set; }
        public Point Home { get; set; }
    }

    partial class CaptainMarmot
    {
        static string[] tokens = new string[0];
        static int cur_token = 0;

        static void ReadArray(char sep)
        {
            cur_token = 0;
            tokens = Console.ReadLine().Split(sep);
        }

        static int ReadInt()
        {
            return int.Parse(Console.ReadLine());
        }

        static long ReadLong()
        {
            return long.Parse(Console.ReadLine());
        }

        static int NextInt()
        {
            if (cur_token == tokens.Length)
                ReadArray(' ');
            return int.Parse(tokens[cur_token++]);
        }

        static long NextLong()
        {
            if (cur_token == tokens.Length)
                ReadArray(' ');
            return long.Parse(tokens[cur_token++]);
        }

        static double NextDouble()
        {
            if (cur_token == tokens.Length)
                ReadArray(' ');
            return double.Parse(tokens[cur_token++]);
        }

        static decimal NextDecimal()
        {
            if (cur_token == tokens.Length)
                ReadArray(' ');
            return decimal.Parse(tokens[cur_token++]);
        }

        static string NextToken()
        {
            if (cur_token == tokens.Length)
                ReadArray(' ');
            return tokens[cur_token++];
        }

        static string ReadLine()
        {
            return Console.ReadLine();
        }
    }
}


using System;
using System.Linq;
using System.Text;

namespace CaptainMarmot
{
    partial class CaptainMarmot
    {
        static void Main(string[] args)
        {
            int n, min, total;
            bool foundAnswer = false;
            Mole[] moles = new Mole[4];
            Point[] current = new Point[4];
            StringBuilder answers = new StringBuilder();

            n = NextInt();

            for (int i = 0; i < 4; i++)
            {
                moles[i] = new Mole { Position = new Point(), Home = new Point() };
                current[i] = new Point();
            }

            for (int i = 0; i < n; i++)
            {
                min = int.MaxValue;
                foundAnswer = false;

                for (int j = 0; j < 4; j++)
                {
                    moles[j].Position.X = NextInt();
                    moles[j].Position.Y = NextInt();
                    moles[j].Home.X = NextInt();
                    moles[j].Home.Y = NextInt();

                    current[j].X = moles[j].Position.X;
                    current[j].Y = moles[j].Position.Y;
                }

                for (int a = 0; a < 4; a++)
                {
                    if (a > 0)
                        current[0].Rotate(moles[0].Home.X, moles[0].Home.Y);
                    else
                    {
                        current[0].X = moles[0].Position.X;
                        current[0].Y = moles[0].Position.Y;
                    }

                    for (int b = 0; b < 4; b++)
                    {
                        if (b > 0)
                            current[1].Rotate(moles[1].Home.X, moles[1].Home.Y);
                        else
                        {
                            current[1].X = moles[1].Position.X;
                            current[1].Y = moles[1].Position.Y;
                        }

                        for (int c = 0; c < 4; c++)
                        {
                            if (c > 0)
                                current[2].Rotate(moles[2].Home.X, moles[2].Home.Y);
                            else
                            {
                                current[2].X = moles[2].Position.X;
                                current[2].Y = moles[2].Position.Y;
                            }

                            for (int d = 0; d < 4; d++)
                            {
                                if (d > 0)
                                    current[3].Rotate(moles[3].Home.X, moles[3].Home.Y);
                                else
                                {
                                    current[3].X = moles[3].Position.X;
                                    current[3].Y = moles[3].Position.Y;
                                }

                                total = a + b + c + d;

                                if (IsSquare(current))
                                {
                                    foundAnswer = true;

                                    if (total < min)
                                        min = total;
                                }
                            }
                        }
                    }
                }

                if (foundAnswer)
                    answers.AppendFormat("{0}\n", min);
                else
                    answers.AppendLine("-1");
            }

            Console.Write(answers);
        }

        private static bool IsSquare(Point[] points)
        {
            if (points[0].Equals(points[1]) || points[1].Equals(points[2]) || points[2].Equals(points[3]))
                return false;

            Tuple<Point, int>[] distances = new Tuple<Point, int>[3];
            int ctr = 0;

            foreach (Point point in points.Except(new[] { points[0] }))
                distances[ctr++] = Tuple.Create(point, point.Distance(points[0]));

            distances = distances.OrderBy(d => d.Item2).ToArray();

            if (distances[0].Item2 != distances[1].Item2)
                return false;

            Point origin = distances[0].Item1;
            return origin.Distance(distances[2].Item1) == origin.Distance(points[0]) && origin.Distance(distances[1].Item1) == points[0].Distance(distances[2].Item1);
        }

    }

    public class Point
    {
        public int X { get; set; }
        public int Y { get; set; }

        public int Distance(Point otherPoint)
        {
            return (int)Math.Pow(Math.Abs(X - otherPoint.X), 2) + (int)Math.Pow(Math.Abs(Y - otherPoint.Y), 2);
        }

        public override bool Equals(object obj)
        {
            return X == ((Point)obj).X && Y == ((Point)obj).Y;
        }

        public void Rotate(int x, int y)
        {
            double angle = 90.0 * Math.PI / 180;
            double cos = Math.Cos(angle);
            double sin = Math.Sin(angle);
            int dx = X - x;
            int dy = Y - y;
            double cx = cos * dx - sin * dy + x;
            double cy = sin * dx + cos * dy + y;

            X = (int)Math.Round(cx);
            Y = (int)Math.Round(cy);
        }
    }

    public class Mole
    {
        public Point Position { get; set; }
        public Point Home { get; set; }
    }

    partial class CaptainMarmot
    {
        static string[] tokens = new string[0];
        static int cur_token = 0;

        static void ReadArray(char sep)
        {
            cur_token = 0;
            tokens = Console.ReadLine().Split(sep);
        }

        static int ReadInt()
        {
            return int.Parse(Console.ReadLine());
        }

        static long ReadLong()
        {
            return long.Parse(Console.ReadLine());
        }

        static int NextInt()
        {
            if (cur_token == tokens.Length)
                ReadArray(' ');
            return int.Parse(tokens[cur_token++]);
        }

        static long NextLong()
        {
            if (cur_token == tokens.Length)
                ReadArray(' ');
            return long.Parse(tokens[cur_token++]);
        }

        static double NextDouble()
        {
            if (cur_token == tokens.Length)
                ReadArray(' ');
            return double.Parse(tokens[cur_token++]);
        }

        static decimal NextDecimal()
        {
            if (cur_token == tokens.Length)
                ReadArray(' ');
            return decimal.Parse(tokens[cur_token++]);
        }

        static string NextToken()
        {
            if (cur_token == tokens.Length)
                ReadArray(' ');
            return tokens[cur_token++];
        }

        static string ReadLine()
        {
            return Console.ReadLine();
        }
    }
}


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

class C
{
    private static string NextToken()
    {
        StringBuilder result = new StringBuilder();
        while (true)
        {
            int c = Console.Read();
            if (c == -1)
                return result.ToString();
            if (char.IsWhiteSpace((char)c))
            {
                if (result.Length > 0)
                {
                    return result.ToString();
                }
            }
            else
            {
                result.Append((char)c);
            }
        }
    }

    private static int NextInt()
    {
        return int.Parse(NextToken());
    }

    private static long NextLong()
    {
        return long.Parse(NextToken());
    }

    private static double NextDouble()
    {
        return double.Parse(NextToken());
    }

    private static int n;

    struct Vector
    {
        public int X;
        public int Y;

        public static Vector operator +(Vector a, Vector b)
        {
            return new Vector() { X = a.X + b.X, Y = a.Y + b.Y };
        }

        public static Vector operator -(Vector a, Vector b)
        {
            return new Vector() { X = a.X - b.X, Y = a.Y - b.Y };
        }

        public int LengthSquared
        {
            get { return X*X + Y*Y; }
        }

        public static int CrossProduct(Vector a, Vector b)
        {
            return a.X*b.Y - a.Y*b.X;
        }

        public static int ScalarProduct(Vector a, Vector b)
        {
            return a.X*b.X + a.Y*b.Y;
        }
    }

    class AngleComparer : IComparer<Vector>
    {
        private Vector v;

        public AngleComparer(Vector v)
        {
            this.v = v;
        }

        public int Compare(Vector x, Vector y)
        {
            return Vector.CrossProduct(x - v, y - v).CompareTo(0);
        }
    }

    static int[] Unpack(int rotationCode)
    {
        var result = new int[4];
        for (int i = 0; i < 4; i++)
        {
            result[i] = rotationCode % 4;
            rotationCode >>= 2;
        }
        return result;
    }

    static Vector Rotate(Vector original, Vector center, int angle)
    {
        var result = original - center;
        for (int i = 0; i < angle; i++)
        {
            result = new Vector() {X = -result.Y, Y = result.X} ;
        }
        return center + result;
    }

    static bool CheckFormation(Vector[] molePositions, Vector[] moleHomes, int formationCode)
    {
        int[] rotations = Unpack(formationCode);
        var rp = new Vector[4];
        for (int i = 0; i < RegimentSize; i++)
        {
            rp[i] = Rotate(molePositions[i], moleHomes[i], rotations[i]);
        }
        Array.Sort(rp, 0, rp.Length, new AngleComparer(rp[0]));
        var sides = new Vector[RegimentSize];
        for (int i = 0; i < RegimentSize; i++)
        {
            sides[i] = rp[i] - rp[(i - 1 + RegimentSize) % RegimentSize];
        }
        var squaredLengths = new int[RegimentSize];
        for (int i = 0; i < RegimentSize; i++)
        {
            squaredLengths[i] = sides[i].LengthSquared;
        }
        return squaredLengths[0] > 0 &&
            squaredLengths[0] == squaredLengths[1] &&
            squaredLengths[1] == squaredLengths[2] &&
            squaredLengths[2] == squaredLengths[3] &&
            Vector.ScalarProduct(sides[0], sides[1]) == 0 &&
            Vector.ScalarProduct(sides[1], sides[2]) == 0 &&
            Vector.ScalarProduct(sides[2], sides[3]) == 0;
    }

    static int CountRotations(int formationCode)
    {
        return Unpack(formationCode).Sum();
    }

    private const int RegimentSize = 4;
    private const int MaxFormationCode = 1 << (RegimentSize * 2) - 1;

    static void Solve()
    {
        n = NextInt();
        for (int i = 0; i < n; i++)
        {
            var molePositions = new Vector[RegimentSize];
            var moleHomes = new Vector[RegimentSize];
            for (int j = 0; j < 4; j++)
            {
                molePositions[j].X = NextInt();
                molePositions[j].Y = NextInt();
                moleHomes[j].X = NextInt();
                moleHomes[j].Y = NextInt();
            }
            int answer = -1;
            for (int formationCode = 0; formationCode < MaxFormationCode; formationCode++)
            {
                var rotations = CountRotations(formationCode);
                if (answer != -1 && rotations >= answer)
                {
                    continue;
                }
                if (CheckFormation(molePositions, moleHomes, formationCode))
                {
                    answer = rotations;
                }
            }
            Console.WriteLine(answer);
        }
    }

    static void Main(string[] args)
    {
        #if ONLINE_JUDGE
        Solve();
        #else
        using (var reader = new StreamReader(new FileStream("c.in", FileMode.OpenOrCreate, FileAccess.Read)))
        {
            Console.SetIn(reader);
            using (var writer = new StreamWriter(new FileStream("c.out", FileMode.Create, FileAccess.Write)))
            {
                Console.SetOut(writer);
                Solve();
            }
        }
        #endif
    }
}


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

class C
{
    private static string NextToken()
    {
        StringBuilder result = new StringBuilder();
        while (true)
        {
            int c = Console.Read();
            if (c == -1)
                return result.ToString();
            if (char.IsWhiteSpace((char)c))
            {
                if (result.Length > 0)
                {
                    return result.ToString();
                }
            }
            else
            {
                result.Append((char)c);
            }
        }
    }

    private static int NextInt()
    {
        return int.Parse(NextToken());
    }

    private static long NextLong()
    {
        return long.Parse(NextToken());
    }

    private static double NextDouble()
    {
        return double.Parse(NextToken());
    }

    private static int n;

    struct Vector
    {
        public int X;
        public int Y;

        public static Vector operator +(Vector a, Vector b)
        {
            return new Vector() { X = a.X + b.X, Y = a.Y + b.Y };
        }

        public static Vector operator -(Vector a, Vector b)
        {
            return new Vector() { X = a.X - b.X, Y = a.Y - b.Y };
        }

        public int LengthSquared
        {
            get { return X*X + Y*Y; }
        }

        public static int CrossProduct(Vector a, Vector b)
        {
            return a.X*b.Y - a.Y*b.X;
        }

        public static int ScalarProduct(Vector a, Vector b)
        {
            return a.X*b.X + a.Y*b.Y;
        }
    }

    class AngleComparer : IComparer<Vector>
    {
        private Vector v;

        public AngleComparer(Vector v)
        {
            this.v = v;
        }

        public int Compare(Vector x, Vector y)
        {
            return Vector.CrossProduct(x - v, y - v).CompareTo(0);
        }
    }

    static int[] Unpack(int rotationCode)
    {
        var result = new int[4];
        for (int i = 0; i < 4; i++)
        {
            result[i] = rotationCode % 4;
            rotationCode >>= 2;
        }
        return result;
    }

    static Vector Rotate(Vector original, Vector center, int angle)
    {
        var result = original - center;
        for (int i = 0; i < angle; i++)
        {
            result = new Vector() {X = -result.Y, Y = result.X} ;
        }
        return center + result;
    }

    static bool CheckFormation(Vector[] molePositions, Vector[] moleHomes, int formationCode)
    {
        int[] rotations = Unpack(formationCode);
        var rp = new Vector[4];
        for (int i = 0; i < RegimentSize; i++)
        {
            rp[i] = Rotate(molePositions[i], moleHomes[i], rotations[i]);
        }
        Array.Sort(rp, 0, rp.Length, new AngleComparer(rp[0]));
        var sides = new Vector[RegimentSize];
        for (int i = 0; i < RegimentSize; i++)
        {
            sides[i] = rp[i] - rp[(i - 1 + RegimentSize) % RegimentSize];
        }
        var squaredLengths = new int[RegimentSize];
        for (int i = 0; i < RegimentSize; i++)
        {
            squaredLengths[i] = sides[i].LengthSquared;
        }
        return squaredLengths[0] > 0 &&
            squaredLengths[0] == squaredLengths[1] &&
            squaredLengths[1] == squaredLengths[2] &&
            squaredLengths[2] == squaredLengths[3] &&
            Vector.ScalarProduct(sides[0], sides[1]) == 0 &&
            Vector.ScalarProduct(sides[1], sides[2]) == 0 &&
            Vector.ScalarProduct(sides[2], sides[3]) == 0;
    }

    static int CountRotations(int formationCode)
    {
        //Console.WriteLine(Unpack(formationCode).Aggregate(string.Empty, (s, i) => s + " " + i));
        return Unpack(formationCode).Sum();
    }

    private const int RegimentSize = 4;
    private const int MaxFormationCode = (1 << (RegimentSize * 2)) - 1;

    static void Solve()
    {
        n = NextInt();
        for (int i = 0; i < n; i++)
        {
            var molePositions = new Vector[RegimentSize];
            var moleHomes = new Vector[RegimentSize];
            for (int j = 0; j < 4; j++)
            {
                molePositions[j].X = NextInt();
                molePositions[j].Y = NextInt();
                moleHomes[j].X = NextInt();
                moleHomes[j].Y = NextInt();
            }
            int answer = -1;
            for (int formationCode = 0; formationCode <= MaxFormationCode; formationCode++)
            {
                var rotations = CountRotations(formationCode);
                if (answer != -1 && rotations >= answer)
                {
                    continue;
                }
                if (CheckFormation(molePositions, moleHomes, formationCode))
                {
                    answer = rotations;
                }
            }
            Console.WriteLine(answer);
        }
    }

    static void Main(string[] args)
    {
        #if ONLINE_JUDGE
        Solve();
        #else
        using (var reader = new StreamReader(new FileStream("c.in", FileMode.OpenOrCreate, FileAccess.Read)))
        {
            Console.SetIn(reader);
            using (var writer = new StreamWriter(new FileStream("c.out", FileMode.Create, FileAccess.Write)))
            {
                Console.SetOut(writer);
                Solve();
            }
        }
        #endif
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using Solver.Ex;
using Watch = System.Diagnostics.Stopwatch;
using StringBuilder = System.Text.StringBuilder;
using BitVector = System.Collections.Specialized.BitVector32;
namespace Solver
{
    public class Solver
    {
        public void Solve()
        {
            var n = sc.Integer();
            for (int i = 0; i < n; i++)
            {
                var ar = 4.Enumerate(x => new Point64[2]);
                for (int k = 0; k < 4; k++)
                    for (int j = 0; j < 2; j++)
                        ar[k][j] = new Point64(sc.Integer(), sc.Integer());
                var count = 50;
                for (int a = 0; a < 4; a++)
                {
                    for (int b = 0; b < 4; b++)
                    {
                        for (int c = 0; c < 4; c++)
                        {
                            for (int d = 0; d < 4; d++)
                            {
                                if (Shape64.IsSquare(ar[0][0], ar[1][0], ar[2][0], ar[3][0]))
                                    count = Math.Min(count, a + b + c + d);
                                Rotate(ar[3]);
                            }
                            Rotate(ar[2]);
                        }
                        Rotate(ar[1]);
                    }
                    Rotate(ar[0]);
                }
                if (count == 50)
                    IO.Printer.Out.PrintLine(-1);
                else IO.Printer.Out.PrintLine(count);

            }
        }

        internal IO.StreamScanner sc;
        void Rotate(Point64[] pq)
        {
            var p = pq[0];
            var q = pq[1];
            var dx = p.x - q.x;
            var dy = p.y - q.y;
            pq[0] = new Point64(q.x - dy, q.y + dx);
        }
    }

    #region Main and Settings
    static class Program
    {
        static void Main(string[] arg)
        {
#if DEBUG
            var errStream = new System.IO.FileStream(@"..\..\dbg.out", System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite);
            System.Diagnostics.Debug.Listeners.Add(new System.Diagnostics.TextWriterTraceListener(errStream, "debugStream"));
            System.Diagnostics.Debug.AutoFlush = false;
            var sw = new Watch();
            sw.Start();
            try
            {
#endif
                var solver = new Solver();
                solver.sc = new IO.StreamScanner(Console.OpenStandardInput());
                IO.Printer.Out = new IO.Printer(new System.IO.StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
                solver.Solve();
                IO.Printer.Out.Flush();
#if DEBUG
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
                Console.Error.WriteLine(ex.StackTrace);
            }
            finally
            {
                sw.Stop();
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Error.WriteLine("Time:{0}ms", sw.ElapsedMilliseconds);
                System.Diagnostics.Debug.Close();
                System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
            }
#endif
        }

    }
    #endregion
}
#region IO Helper
namespace Solver.IO
{
    public class Printer
    {
        static Printer()
        {
            Out = new Printer(Console.Out);
        }
        public static Printer Out { get; set; }
        private readonly System.IO.TextWriter writer;
        private readonly System.Globalization.CultureInfo info;
        public string Separator { get; set; }
        public string NewLine { get { return writer.NewLine; } set { writer.NewLine = value ?? "\n"; } }
        public Printer(System.IO.TextWriter tw = null, System.Globalization.CultureInfo ci = null, string separator = null, string newLine = null)
        {
            writer = tw ?? System.IO.TextWriter.Null;
            info = ci ?? System.Globalization.CultureInfo.InvariantCulture;
            NewLine = newLine;
            Separator = separator ?? " ";
        }
        public void Print(int num) { writer.Write(num.ToString(info)); }
        public void Print(int num, string format) { writer.Write(num.ToString(format, info)); }
        public void Print(long num) { writer.Write(num.ToString(info)); }
        public void Print(long num, string format) { writer.Write(num.ToString(format, info)); }
        public void Print(double num) { writer.Write(num.ToString("F12", info)); }
        public void Print(double num, string format) { writer.Write(num.ToString(format, info)); }
        public void Print(string str) { writer.Write(str); }
        public void Print(string format, params object[] arg) { writer.Write(string.Format(info, format, arg)); }
        public void Print<T>(string format, IEnumerable<T> sources) { writer.Write(format, sources.OfType<object>().ToArray()); }
        public void Print(IEnumerable<char> sources) { writer.Write(sources.AsString()); }
        public void Print<T>(IEnumerable<T> sources)
        {
            var res = new System.Text.StringBuilder();
            foreach (var x in sources)
            {
                res.AppendFormat(info, "{0}", x);
                if (string.IsNullOrEmpty(Separator))
                    res.Append(Separator);
            }
            writer.Write(res.ToString(0, res.Length - Separator.Length));
        }
        public void PrintLine() { writer.WriteLine(); }
        public void PrintLine(int num) { writer.WriteLine(num.ToString(info)); }
        public void PrintLine(int num, string format) { writer.WriteLine(num.ToString(format, info)); }
        public void PrintLine(long num) { writer.WriteLine(num.ToString(info)); }
        public void PrintLine(long num, string format) { writer.WriteLine(num.ToString(format, info)); }
        public void PrintLine(double num) { writer.WriteLine(num.ToString("F12", info)); }
        public void PrintLine(double num, string format) { writer.WriteLine(num.ToString(format, info)); }
        public void PrintLine(string str) { writer.WriteLine(str); }
        public void PrintLine(string format, params object[] arg) { writer.WriteLine(string.Format(info, format, arg)); }
        public void PrintLine<T>(string format, IEnumerable<T> sources) { writer.WriteLine(format, sources.OfType<object>().ToArray()); }
        public void PrintLine<T>(IEnumerable<T> sources)
        {
            var res = new StringBuilder();
            foreach (var x in sources)
            {
                res.AppendFormat(info, "{0}", x);
                if (!string.IsNullOrEmpty(Separator))
                    res.Append(Separator);
            }
            writer.WriteLine(res.ToString(0, res.Length - Separator.Length));
        }
        public void Flush() { writer.Flush(); }
    }
    public class StreamScanner
    {
        public StreamScanner(System.IO.Stream stream)
        {
            iStream = stream;
        }
        private readonly System.IO.Stream iStream;
        private readonly byte[] buf = new byte[1024];
        private int len, ptr;
        private bool eof = false;
        public bool EndOfStream { get { return eof; } }
        private byte readByte()
        {
            if (eof) throw new System.IO.EndOfStreamException();
            if (ptr >= len)
            {
                ptr = 0;
                len = iStream.Read(buf, 0, 1024);
                if (len <= 0)
                {
                    eof = true;
                    return 0;
                }
            }
            return buf[ptr++];
        }
        private bool inSpan(byte c)
        {
            const byte lb = 33, ub = 126;
            return !(c >= lb && c <= ub);
        }
        private byte skip()
        {
            byte b = 0;
            do b = readByte();
            while (!eof && inSpan(b));
            return b;
        }
        public char Char()
        {
            return (char)skip();
        }
        public char[] Char(int n)
        {
            var a = new char[n];
            for (int i = 0; i < n; i++)
                a[i] = (char)skip();
            return a;
        }
        public char[][] Char(int n, int m)
        {
            var a = new char[n][];
            for (int i = 0; i < n; i++)
                a[i] = Char(m);
            return a;
        }
        public string Scan()
        {

            const byte lb = 33, ub = 126;
            if (eof) throw new System.IO.EndOfStreamException();

            do
            {
                while (ptr < len && (buf[ptr] < lb || ub < buf[ptr]))
                {
                    ptr++;
                }
                if (ptr < len)
                    break;
                ptr = 0;
                len = iStream.Read(buf, 0, 1024);
                if (len <= 0)
                {
                    eof = true;
                    return null;
                }
                continue;
            } while (true);

            StringBuilder sb = null;
            do
            {
                var i = ptr;
                while (i < len)
                {
                    if (buf[i] < lb || ub < buf[i])
                    {
                        string s;
                        if (sb != null)
                        {
                            sb.Append(System.Text.UTF8Encoding.Default.GetChars(buf, ptr, i - ptr));
                            s = sb.ToString();
                        }
                        else s = new string(System.Text.UTF8Encoding.Default.GetChars(buf, ptr, i - ptr));
                        ptr = i + 1;
                        return s;
                    }
                    i++;
                }
                i = len - ptr;
                if (sb == null) sb = new StringBuilder(i + 32);
                sb.Append(System.Text.UTF8Encoding.Default.GetChars(buf, ptr, i));
                ptr = 0;
            } while ((len = iStream.Read(buf, 0, 1024)) > 0);
            eof = true;
            return sb.ToString();
        }
        public string[] Scan(int n)
        {
            var a = new string[n];
            for (int i = 0; i < n; i++)
                a[i] = Scan();
            return a;
        }
        public string ScanLine()
        {
            const byte el = 10, cr = 13;
            if (eof) throw new System.IO.EndOfStreamException();
            StringBuilder sb = null;
            do
            {
                var i = ptr;
                while (i < len)
                {
                    if (buf[i] == cr || buf[i] == el)
                    {
                        string s;
                        if (sb != null)
                        {
                            sb.Append(System.Text.UTF8Encoding.Default.GetChars(buf, ptr, i - ptr));
                            s = sb.ToString();
                        }
                        else s = new string(System.Text.UTF8Encoding.Default.GetChars(buf, ptr, i - ptr));
                        if (buf[i] == cr) i++;
                        if (buf[i] == el) i++;
                        ptr = i;
                        return s;
                    }
                    i++;
                }
                i = len - ptr;
                if (sb == null) sb = new StringBuilder(i + 32);
                sb.Append(System.Text.UTF8Encoding.Default.GetChars(buf, ptr, i));
                ptr = 0;
            } while ((len = iStream.Read(buf, 0, 1024)) > 0);
            eof = true;
            return sb.ToString();
        }
        public double Double()
        {
            return double.Parse(Scan(), System.Globalization.CultureInfo.InvariantCulture);
        }
        public double[] Double(int n)
        {
            var a = new double[n];
            for (int i = 0; i < n; i++)
                a[i] = Double();
            return a;
        }
        public int Integer()
        {
            var ret = 0;
            byte b = 0;
            bool isMynus = false;
            const byte zero = 48, nine = 57, mynus = 45;
            do b = readByte();
            while (!eof && !((b >= zero && b <= nine) || b == mynus));

            if (b == mynus)
            {
                isMynus = true;
                b = readByte();
            }
            while (true)
            {
                if (b >= zero && b <= nine)
                {
                    ret = ret * 10 + b - zero;
                }
                else return isMynus ? -ret : ret;
                b = readByte();
            }

        }
        public int[] Integer(int n)
        {
            var a = new int[n];
            for (int i = 0; i < n; i++)
                a[i] = Integer();
            return a;
        }
        public long Long()
        {
            long ret = 0;
            byte b = 0;
            bool isMynus = false;
            const byte zero = 48, nine = 57, mynus = 45;
            do b = readByte();
            while (!eof && !((b >= zero && b <= nine) || b == mynus));
            if (b == '-')
            {
                isMynus = true;
                b = readByte();
            }
            while (true)
            {
                if (b >= zero && b <= nine)
                    ret = ret * 10 + (b - zero);
                else return isMynus ? -ret : ret;
                b = readByte();
            }

        }
        public long[] Long(int n)
        {
            var a = new long[n];
            for (int i = 0; i < n; i++)
                a[i] = Long();
            return a;
        }
        public void Flush()
        {
            iStream.Flush();
        }

    }

}
#endregion
#region Extension
namespace Solver.Ex
{
    static public partial class EnumerableEx
    {
        static public string AsString(this IEnumerable<char> source)
        {
            return new string(source.ToArray());
        }
        static public string AsJoinedString<T>(this IEnumerable<T> source, string separator = " ")
        {
            return string.Join(separator, source);
        }
        static public T[] Enumerate<T>(this int n, Func<int, T> selector)
        {
            var res = new T[n];
            for (int i = 0; i < n; i++)
                res[i] = selector(i);
            return res;
        }
    }
}
#endregion

#region LongGeometry
public struct Point64
{
    public long x, y;
    public Point64(long u, long v)
        : this()
    {
        x = u; y = v;
    }
    public long Distance(Point64 other)
    {
        var dx = this.x - other.x;
        var dy = this.y - other.y;
        return dx * dx + dy * dy;
    }
}
#endregion
#region LongGeometry
static public class Shape64
{
    static public bool IsSquare(Point64 a, Point64 b, Point64 c, Point64 d)
    {
        var m = new Point64(a.x + b.x + c.x + d.x, a.y + b.y + c.y + d.y);
        var p = new Point64[] { a, b, c, d };
        for (int i = 0; i < 4; i++)
        {
            p[i].x *= 4;
            p[i].y *= 4;
        }
        if (m.Distance(p[0]) == 0)
            return false;
        for (int i = 0; i < 4; i++)
            if (m.Distance(p[i]) != m.Distance(p[0]))
                return false;
        for (int i = 0; i < 4; i++)
            for (int j = i + 1; j < 4; j++)
            {
                if (p[i].Distance(p[j]) == 0)
                    return false;
                var smul = (p[i].x - m.x) * (p[j].x - m.x) + (p[i].y - m.y) * (p[j].y - m.y);
                var vmul = (p[i].x - m.x) * (p[j].y - m.y) - (p[i].y - m.y) * (p[j].x - m.x);
                if (smul != 0 && vmul != 0)
                    return false;
            }
        return true;
    }

}
#endregion


using System;
using System.Collections.Generic;
using System.Linq;
using Solver.Ex;
using Debug = System.Diagnostics.Debug;
using Watch = System.Diagnostics.Stopwatch;
using StringBuilder = System.Text.StringBuilder;
namespace Solver
{
    public class Solver
    {
        public void Solve()
        {
            var n = sc.Integer();
            for (int i = 0; i < n; i++)
            {
                var ar = 4.Enumerate(x => new Point64[2]);
                for (int k = 0; k < 4; k++)
                    for (int j = 0; j < 2; j++)
                        ar[k][j] = new Point64(sc.Integer(), sc.Integer());
                var count = 50;
                for (int a = 0; a < 4; a++, rot(ar[0]))
                    for (int b = 0; b < 4; b++, rot(ar[1]))
                        for (int c = 0; c < 4; c++, rot(ar[2]))
                            for (int d = 0; d < 4; d++, rot(ar[3]))
                                if (Shape64.IsSquare(ar[0][0], ar[1][0], ar[2][0], ar[3][0]))
                                    count = Math.Min(count, a + b + c + d);
                if (count == 50)
                    IO.Printer.Out.WriteLine(-1);
                else IO.Printer.Out.WriteLine(count);

            }
        }
        void rot(Point64[] pq)
        {
            var p = pq[0];
            var q = pq[1];
            var dx = p.x - q.x;
            var dy = p.y - q.y;
            pq[0] = new Point64(q.x - dy, q.y + dx);
        }
        internal IO.StreamScanner sc;
    }

    #region Main and Settings
    static class Program
    {
        static void Main(string[] arg)
        {
#if DEBUG
            var errStream = new System.IO.FileStream(@"..\..\dbg.out", System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite);
            Debug.Listeners.Add(new System.Diagnostics.TextWriterTraceListener(errStream, "debugStream"));
            Debug.AutoFlush = false;
            var sw = new Watch(); sw.Start();
            try
            {
#endif
                var solver = new Solver();
                solver.sc = new IO.StreamScanner(Console.OpenStandardInput());
                solver.Solve();
                IO.Printer.Out.Flush();
#if DEBUG
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
                Console.Error.WriteLine(ex.StackTrace);
            }
            finally
            {
                sw.Stop();
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Error.WriteLine("Time:{0}ms", sw.ElapsedMilliseconds);
                Debug.Close();
                System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
            }
#endif
        }

    }
    #endregion
}
#region IO Helper
namespace Solver.IO
{
    public class Printer : System.IO.StreamWriter
    {
        static Printer() { Out = new Printer(Console.OpenStandardOutput()) { AutoFlush = false }; }
        public static Printer Out { get; set; }
        public override IFormatProvider FormatProvider { get { return System.Globalization.CultureInfo.InvariantCulture; } }
        public Printer(System.IO.Stream stream) : base(stream, new System.Text.UTF8Encoding(false, true)) { }
        public Printer(System.IO.Stream stream, System.Text.Encoding encoding) : base(stream, encoding) { }
        public void Write<T>(string format, IEnumerable<T> source) { Write(format, source.OfType<object>().ToArray()); }
        public void WriteLine<T>(string format, IEnumerable<T> source) { WriteLine(format, source.OfType<object>().ToArray()); }
    }
    public class StreamScanner
    {
        public StreamScanner(System.IO.Stream stream) { iStream = stream; }
        private readonly System.IO.Stream iStream;
        private readonly byte[] buf = new byte[1024];
        private int len, ptr;
        private bool eof = false;
        public bool IsEndOfStream { get { return eof; } }
        const byte lb = 33, ub = 126, el = 10, cr = 13;
        public byte read()
        {
            if (eof) throw new System.IO.EndOfStreamException();
            if (ptr >= len) { ptr = 0; if ((len = iStream.Read(buf, 0, 1024)) <= 0) { eof = true; return 0; } }
            return buf[ptr++];
        }
        public char Char() { byte b = 0; do b = read(); while (b < lb || ub < b);            return (char)b; }
        public char[] Char(int n) { var a = new char[n]; for (int i = 0; i < n; i++) a[i] = Char(); return a; }
        public char[][] Char(int n, int m) { var a = new char[n][]; for (int i = 0; i < n; i++) a[i] = Char(m); return a; }
        public string Scan()
        {
            if (eof) throw new System.IO.EndOfStreamException();
            StringBuilder sb = null;
            var enc = System.Text.UTF8Encoding.Default;
            do
            {
                for (; ptr < len && (buf[ptr] < lb || ub < buf[ptr]); ptr++) ;
                if (ptr < len) break;
                ptr = 0;
                if ((len = iStream.Read(buf, 0, 1024)) <= 0) { eof = true; return ""; }
            } while (true);
            do
            {
                var f = ptr;
                for (; ptr < len; ptr++)
                    if (buf[ptr] < lb || ub < buf[ptr])
                    //if(buf[i]==cr||buf[i]==el)
                    {
                        string s;
                        if (sb == null) s = enc.GetString(buf, f, ptr - f);
                        else { sb.Append(enc.GetChars(buf, f, ptr - f)); s = sb.ToString(); }
                        ptr++; return s;
                    }
                if (sb == null) sb = new StringBuilder(enc.GetString(buf, f, len - f));
                else sb.Append(enc.GetChars(buf, ptr, len - ptr));
                ptr = 0;

            }
            while (!eof && (len = iStream.Read(buf, 0, 1024)) > 0);
            eof = true; return (sb != null) ? sb.ToString() : "";
        }
        public long Long()
        {
            long ret = 0; byte b = 0; bool isMynus = false;
            const byte zr = 48, nn = 57, my = 45;
            do b = read();
            while (b != my && (b < zr || nn < b));
            if (b == my) { isMynus = true; b = read(); }
            for (; true; b = read())
                if (b < zr || nn < b)
                    return isMynus ? -ret : ret;
                else ret = ret * 10 + b - zr;
        }
        public int Integer()
        {
            int ret = 0; byte b = 0; bool isMynus = false;
            const byte zr = 48, nn = 57, my = 45;
            do b = read();
            while (b != my && (b < zr || nn < b));
            if (b == my) { isMynus = true; b = read(); }
            for (; true; b = read())
                if (b < zr || nn < b)
                    return isMynus ? -ret : ret;
                else ret = ret * 10 + b - zr;
        }
        public double Double() { return double.Parse(Scan(), System.Globalization.CultureInfo.InvariantCulture); }
        public string[] Scan(int n) { var a = new string[n]; for (int i = 0; i < n; i++) a[i] = Scan(); return a; }
        public double[] Double(int n) { var a = new double[n]; for (int i = 0; i < n; i++) a[i] = Double(); return a; }
        public int[] Integer(int n) { var a = new int[n]; for (int i = 0; i < n; i++) a[i] = Integer(); return a; }
        public long[] Long(int n) { var a = new long[n]; for (int i = 0; i < n; i++)a[i] = Long(); return a; }
        public void Flush() { iStream.Flush(); }
    }
}
#endregion
#region Extension
namespace Solver.Ex
{
    static public partial class EnumerableEx
    {
        static public string AsString(this IEnumerable<char> ie) { return new string(ie.ToArray()); }
        static public string AsJoinedString<T>(this IEnumerable<T> ie, string st = " ") { return string.Join(st, ie); }
        static public T[] Enumerate<T>(this int n, Func<int, T> f) { var a = new T[n]; for (int i = 0; i < n; i++) a[i] = f(i); return a; }
    }
}
#endregion
#region LongGeometry
public struct Point64
{
    public long x, y;
    public Point64(long u, long v)
        : this()
    {
        x = u; y = v;
    }
    public long Distance(Point64 other)
    {
        var dx = this.x - other.x;
        var dy = this.y - other.y;
        return dx * dx + dy * dy;
    }
}
#endregion
#region LongGeometry
static public class Shape64
{
    static public bool IsSquare(Point64 p, Point64 q, Point64 u, Point64 v)
    {
        var d = new long[6];
        var a = new Point64[] { p, q, u, v };
        var k = 0;
        for (int i = 0; i < 4; i++)
            for (int j = i + 1; j < 4; j++)
                d[k++] = a[i].Distance(a[j]);
        Array.Sort(d);
        if (d[0] > 0 && d[0] == d[3] && d[4] == d[5] && d[0] * 2 == d[4])
            return true;
        return false;
    }

}
#endregion


using System;
using System.Collections.Generic;
using System.Linq;
class Solver
{
    void Solve()
    {
        var n = sc.Integer();
        var sz = 4 * n;
        var a = new int[sz][];
        for (int i = 0; i < sz; i++)
            a[i] = sc.IntArray(4);
        for (int i = 0; i < sz; i += 4)
        {
            var count = 100;
            for (int f = 0; f < 4; f++)
            {
                for (int s = 0; s < 4; s++)
                {
                    for (int t = 0; t < 4; t++)
                    {
                        for (int rth = 0; rth < 4; rth++)
                        {
                            if (Check(a, i))
                                count = Math.Min(count, f + s + t + rth);
                            Rotate(a[i + 3]);
                        }
                        Rotate(a[i + 2]);
                    }

                    Rotate(a[i + 1]);
                }
                Rotate(a[i]);
            }
            if (count == 100)
                Printer.PrintLine(-1);
            else Printer.PrintLine(count);
        }

    }
    void Rotate(int[] a)
    {
        var dx = a[0] - a[2];
        var dy = a[1] - a[3];
        a[0] = a[2] - dy;
        a[1] = a[3] + dx;
    }
    bool Check(int[][] a, int i)
    {
       for (int k = 0; k < 4; k++)
           for (int l = k + 1; l < 4; l++)
               if (a[i + k][0] == a[i + l][0] && a[i + k][1] == a[i + l][1])
                   return false;

        var d = new long[3];
        long x = a[i][0];
        long y = a[i][1];
        for (int j = 1; j <= 3; j++)
        {
            long p = a[i + j][0];
            long q = a[i + j][1];
            d[j - 1] = (p - x) * (p - x) + (q - y) * (q - y);
        }
        Array.Sort(d);
        if (d[0] > 0 && d[0] == d[1] && d[0] << 1 == d[2])
            return true;
        return false;

    }
    static void Main()
    {
#if DEBUG
        var ostream = new System.IO.FileStream("debug.txt", System.IO.FileMode.Create, System.IO.FileAccess.Write);
        var iStream = new System.IO.FileStream("input.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
        Console.SetIn(new System.IO.StreamReader(iStream));
        System.Diagnostics.Debug.AutoFlush = true;
        System.Diagnostics.Debug.Listeners.Add(new System.Diagnostics.TextWriterTraceListener(new System.IO.StreamWriter(ostream, System.Text.Encoding.UTF8)));
        System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
        sw.Start();
        try
        {
#endif
            var solver = new Solver();
            solver.Solve();
#if DEBUG
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine(ex.StackTrace);
            Console.ReadKey(true);
            return;
        }
        sw.Stop();
        Console.ForegroundColor = ConsoleColor.Green;
        Printer.PrintLine("Time:{0}ms", sw.ElapsedMilliseconds);
        Console.ReadKey(true);
#endif
    }
    _Scanner sc = new _Scanner();

}

static public class Printer
{
    static readonly private System.IO.TextWriter writer;
    static readonly private System.Globalization.CultureInfo info;
    static string Separator { get; set; }
    static Printer()
    {
        writer = Console.Out;
        info = System.Globalization.CultureInfo.InvariantCulture;
        Separator = " ";
    }

    static public void Print(int num) { writer.Write(num.ToString(info)); }
    static public void Print(int num, string format) { writer.Write(num.ToString(format, info)); }
    static public void Print(long num) { writer.Write(num.ToString(info)); }
    static public void Print(long num, string format) { writer.Write(num.ToString(format, info)); }
    static public void Print(double num) { writer.Write(num.ToString(info)); }
    static public void Print(double num, string format) { writer.Write(num.ToString(format, info)); }
    static public void Print(string str) { writer.Write(str); }
    static public void Print(string format, params object[] arg) { writer.Write(format, arg); }
    static public void Print<T>(string format, IEnumerable<T> sources) { writer.Write(format, sources.OfType<object>().ToArray()); }
    static public void Print(IEnumerable<char> sources) { writer.Write(sources.AsString()); }
    static public void Print(params object[] arg)
    {
        var res = new System.Text.StringBuilder();
        foreach (var x in arg)
        {
            res.AppendFormat(info, "{0}", x);
            if (!string.IsNullOrEmpty(Separator))
                res.Append(Separator);
        }
        writer.Write(res.ToString(0, res.Length - Separator.Length));
    }
    static public void Print<T>(IEnumerable<T> sources)
    {
        var res = new System.Text.StringBuilder();
        foreach (var x in sources)
        {
            res.AppendFormat(info, "{0}", x);
            if (string.IsNullOrEmpty(Separator))
                res.Append(Separator);
        }
        writer.Write(res.ToString(0, res.Length - Separator.Length));
    }
    static public void PrintLine(int num) { writer.WriteLine(num.ToString(info)); }
    static public void PrintLine(int num, string format) { writer.WriteLine(num.ToString(format, info)); }
    static public void PrintLine(long num) { writer.WriteLine(num.ToString(info)); }
    static public void PrintLine(long num, string format) { writer.WriteLine(num.ToString(format, info)); }
    static public void PrintLine(double num) { writer.WriteLine(num.ToString(info)); }
    static public void PrintLine(double num, string format) { writer.WriteLine(num.ToString(format, info)); }
    static public void PrintLine(string str) { writer.WriteLine(str); }
    static public void PrintLine(string format, params object[] arg) { writer.WriteLine(format, arg); }
    static public void PrintLine<T>(string format, IEnumerable<T> sources) { writer.WriteLine(format, sources.OfType<object>().ToArray()); }

    static public void PrintLine(params object[] arg)
    {
        var res = new System.Text.StringBuilder();
        foreach (var x in arg)
        {
            res.AppendFormat(info, "{0}", x);
            if (!string.IsNullOrEmpty(Separator))
                res.Append(Separator);
        }
        writer.WriteLine(res.ToString(0, res.Length - Separator.Length));
    }
    static public void PrintLine<T>(IEnumerable<T> sources)
    {
        var res = new System.Text.StringBuilder();
        foreach (var x in sources)
        {
            res.AppendFormat(info, "{0}", x);
            if (!string.IsNullOrEmpty(Separator))
                res.Append(Separator);
        }
        writer.WriteLine(res.ToString(0, res.Length - Separator.Length));
    }
    static public void PrintLine(System.Linq.Expressions.Expression<Func<string, object>> ex)
    {
        var res = ex.Parameters[0];
        writer.WriteLine(res.Name);
    }
}
public class _Scanner
{
    readonly private System.Globalization.CultureInfo info;
    readonly System.IO.TextReader reader;
    string[] buffer = new string[0];
    int position;

    public char[] Separator { get; set; }
    public _Scanner(System.IO.TextReader reader = null, string separator = null, System.Globalization.CultureInfo info = null)
    {

        this.reader = reader ?? Console.In;
        if (string.IsNullOrEmpty(separator))
            separator = " ";
        this.Separator = separator.ToCharArray();
        this.info = info ?? System.Globalization.CultureInfo.InvariantCulture;
    }
    public string Scan()
    {
        if (this.position < this.buffer.Length)
            return this.buffer[this.position++];
        do this.buffer = this.reader.ReadLine().Split(this.Separator, StringSplitOptions.RemoveEmptyEntries);
        while (this.buffer.Length == 0);
        this.position = 0;
        return this.buffer[this.position++];
    }

    public string ScanLine()
    {
        if (this.position >= this.buffer.Length)
            return this.reader.ReadLine();
        else
        {
            var sb = new System.Text.StringBuilder();
            for (; this.position < buffer.Length; this.position++)
            {
                sb.Append(this.buffer[this.position]);
                sb.Append(' ');
            }
            return sb.ToString();
        }
    }
    public string[] ScanArray(int length)
    {
        var ar = new string[length];
        for (int i = 0; i < length; i++)
            ar[i] = this.Scan();
        return ar;
    }

    public int Integer()
    {
        return int.Parse(this.Scan(), info);
    }
    public long Long()
    {
        return long.Parse(this.Scan(), info);
    }
    public double Double()
    {
        return double.Parse(this.Scan(), info);
    }
    public double Double(string str)
    {
        return double.Parse(str, info);
    }

    public int[] IntArray(int length)
    {
        var a = new int[length];
        for (int i = 0; i < length; i++)
            a[i] = this.Integer();
        return a;
    }
    public long[] LongArray(int length)
    {
        var a = new long[length];
        for (int i = 0; i < length; i++)
            a[i] = this.Long();
        return a;
    }
    public double[] DoubleArray(int length)
    {
        var a = new double[length];
        for (int i = 0; i < length; i++)
            a[i] = this.Double();
        return a;
    }

}
static public partial class EnumerableEx
{
    static public string AsString(this IEnumerable<char> source)
    {
        return new string(source.ToArray());
    }
    static public T[] Enumerate<T>(this int n, Func<int, T> selector)
    {
        var res = new T[n];
        for (int i = 0; i < n; i++)
            res[i] = selector(i);
        return res;
    }
}