/* ***************************************************************************+
 * ITX package (cnrg.itx) for telephony application programming.              *
 * Copyright (c) 1999  Cornell University, Ithaca NY.                         *
 * A copy of the license is distributed with this package.  Look in the docs  *
 * directory, filename GPL.  Contact information: bergmark@cs.cornell.edu     *
 ******************************************************************************/
package cnrg.itx.ds;

import java.io.*;

/**
 * This class provides an abstraction to digits
 */
public class Digits implements Serializable{
	private int[] m_Number;

	/**
	 * Constructor for string of digits.  The constructor does nothing if the input string is not in digits form.
	 * @param num string of digits
	 */
	public Digits (String num) {
		try {
			int nVal = Integer.parseInt(num);
			m_Number = new int[num.length()];
			for (int i=0; i<num.length(); i++)
				m_Number[i] = num.charAt(i) - '0';
		}catch (NumberFormatException ae) {
			// does nothing
		}
	}

	/**
	 * Constructor for integer. The constructor does nothing if the input integer is less than 1.
	 * @param num integer value
	 */
	public Digits (int num) {
		if (num > 0) {
			String nVal = String.valueOf(num);
			m_Number = new int[nVal.length()];
			for (int i=0; i<nVal.length(); i++)
				m_Number[i] = nVal.charAt(i) - '0';
		}
	}
	
	/**
	 * Constructor for integer array
	 * @param n array of int
	 */
	public Digits (int[] n) {
		m_Number = clone(n);
	}

	/**
	 * Get the digits value
	 * @return integer value of this Digits object
	 */
	public int getValue() {
		return Integer.parseInt(toString());
	}
	
	/**
	 * Count the number of digits in this digits object
	 * @return the number of digits in this object
	 */
	public int count() {
		return m_Number.length;
	}
	
	/**
	 * Returns a duplicate copy 
	 * @param n array of int
	 * @return array of int
	 */
	private int [] clone(int [] n) {
		int i;
		int [] newArray = new int[n.length];
		for (i=0; i<n.length; i++)
			newArray[i] = n[i];
		return newArray;
	}

	/**
	 * Returns itself represented as an array of int 
	 * @return array of int
	 */
	public int [] getArray () {
		return clone(m_Number);
	}

	/**
	 * Returns itself represented as a string 
	 * @return string of digits
	 */
	public String toString() {
		String result = "";
		int i;
		for (i = 0; i < m_Number.length; i++)
			result = result + m_Number[i];
		return result;
	}

	/**
	 * Compare with other digits instance to determine if they are identical 
	 * @param digits another digits object to be compared
	 * @return true if identical; false otherwise
	 */
	public boolean equals(Digits digits) {
		int i;
		if (m_Number.length != digits.count())
			return false;
		
		for (i = 0; i < m_Number.length; i++){
			if (m_Number[i] != digits.m_Number[i])
				return false;
		}
		return true;
	}
}
