package io;

import java.util.HexFormat;

/**
 * Work with checksums
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class Checksum
{
    //[0
    /**
     * Add a string to a checksum
     *
     * @param s          The string
     * @param checksum   The original checksum 
     * @returns          The new checksum
     */
    protected static int addToChecksum(String s, int checksum)
    {
	int current, i, length;
	
	length = s.length();
	for (i=0; i <= length-1; i++) {
	    
	    current = (int)(s.charAt(i));  // Get a char
	    checksum ^= current;           // xor the char into the checksum
	}
	
	return checksum;
    }
    

    
    /**
     * Determine the checksum for a string
     *
     * @param s          The string
     * @returns          The checksum
     */
    protected static int calculateChecksum(String s)
    {
	return addToChecksum(s, 0);
    }
    //]0
    


    //[1
    /**
     * Determine if a String has the proper checksum
     *
     * @param s          The string
     * @param crcString  The proper checksum (in hex)
     * @returns          true if proper and false otherwise
     */
    public static boolean check(String s, String crcString)
    {
	int   actual, desired;

	actual  = calculateChecksum(s);
	desired = HexFormat.fromHexDigits(crcString);

	return (actual == desired);
    }
    //]1
}

