package com.nickww.finitefield;

import static com.nickww.finitefield.FiniteByteField.*;

final class XorChecksumVector extends ChecksumVector
{
	@Override
	public byte[] withChecksums(byte[] data)
	{
		if(data.length < 1)
			throw new IllegalArgumentException("Data array must have at least one element");
		
		byte[] checksummed = new byte[data.length + 1];
		System.arraycopy(data, 0, checksummed, 0, data.length);
		checksummed[checksummed.length-1] = add(data);
		return checksummed;
	}
	
	@Override
	public byte[] solveMissingValues(Byte[] dataWithChecksums)
	{
		if(dataWithChecksums.length < 2)
			throw new IllegalArgumentException("Array too small to include both data and checksums.");
		
		byte[] data = new byte[dataWithChecksums.length - 1];
		byte checksum = 0;
		int indexOfNull = -1;
		for(int i = 0; i < dataWithChecksums.length; i++)
		{
			if(dataWithChecksums[i] == null)
			{
				if(indexOfNull != -1)
					throw new IllegalArgumentException("Too many nulls - can only handle 1");
				indexOfNull = i;
			}
			else
			{
				checksum = add(checksum, dataWithChecksums[i]);
				if(i < data.length)
					data[i] = dataWithChecksums[i];
			}
		}
		
		if(indexOfNull >= data.length)
			return data;
		data[indexOfNull] = checksum;
		return data;
	}
}

@@ -87,16 +87,42 @@
 d.*;%0D%0A%0D%0A
+import java.util.List;%0D%0A%0D%0A
 final cl
@@ -483,17 +483,19 @@
 d.length
--
+ - 
 1%5D = add
@@ -761,25 +761,46 @@
  data = 
-new byte%5B
+super.copy(dataWithChecksums, 
 dataWith
@@ -823,163 +823,159 @@
  - 1
-%5D
+)
 ;%0D%0A%09%09
-byte checksum = 0;%0D%0A%09%09int indexOfNull = -1;%0D%0A%09%09for(int i = 0; i %3C dataWithChecksums.length; i++)%0D%0A%09%09%7B%0D%0A%09%09%09if(dataWithChecksums%5Bi%5D == null
+List%3CInteger%3E nullIndices = super.missingIndices(dataWithChecksums);%0D%0A%09%09if(!nullIndices.isEmpty() && nullIndices.get(0) != data.length
 )%0D%0A
-%09
 %09%09%7B%0D%0A%09%09%09
 %09if(
@@ -974,36 +974,40 @@
 %0A%09%09%09
-%09
 if(
-indexOfNull != -
+nullIndices.size() %3E 
 1)%0D%0A%09%09%09%09
 %09thr
@@ -1002,17 +1002,16 @@
 1)%0D%0A%09%09%09%09
-%09
 throw ne
@@ -1047,20 +1047,29 @@
 oo many 
-null
+missing value
 s - can 
@@ -1093,261 +1093,114 @@
 %0A%09%09%09
-%09indexOfNull = i;%0D%0A%09%09%09%7D%0D%0A%09%09%09else%0D%0A%09%09%09%7B%0D%0A%09%09%09%09checksum = add(checksum, dataWithChecksums%5Bi%5D);%0D%0A%09%09%09%09if(i %3C data.length)%0D%0A%09%09%09%09%09data%5Bi%5D = dataWithChecksums%5Bi%5D;%0D%0A%09%09%09%7D%0D%0A%09%09%7D%0D%0A%09%09%0D%0A%09%09if(indexOfNull %3E= data.length)%0D%0A%09%09%09return 
+else%0D%0A%09%09%09%09data%5BnullIndices.get(0)%5D = add(dataWithChecksums%5BdataWithChecksums.length - 1%5D, add(
 data
+))
 ;%0D%0A%09%09
-data%5BindexOfNull%5D = checksum;
+%7D
 %0D%0A%09%09

Refactor to simplify logic using new superclass methods