/*
 * Msf.java
 *
 * Copyright (c) 2007  Vreixo Formoso
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * See COPYING file for details.
 */

package org.pykix.libburnia.libburn;

/**
 * Represent a minute-second-frame (MSF) address.
 * 
 * @author Vreixo Formoso
 * @since 0.1
 */
/*
 * Due its simplicity, the functions here are implemented in pure Java,
 * without really wrapping underlying libburn C functions.
 */
public class Msf {

	/*
	 * I make this vars public, maybe a get/set would be a better option.
	 */
	
	/** Minute component. */
	public int m;
	
	/** Second component. */
	public int s;
	
	/** Frame component. */
	public int f;

	public Msf(int m, int s, int f) {
		super();
		this.m = m;
		this.s = s;
		this.f = f;
	}
	
	/**
	 * Get the sector count for this MSF.
	 */
	public int getSectors() {
		return msf2Sectors(m, s, f);
	}

	/**
	 * Get the lba for this MSF.
	 */
	public int getLba() {
		return msf2Lba(m, s, f);
	}

	/**
	 * Convert a minute-second-frame (MSF) value to sector count.
	 * 
	 * @param m
	 * 		Minute component.
	 * @param s
	 * 		Second component.
	 * @param f
	 * 		Frame component.
	 * @return
	 * 		The sector count.
	 */
	public static int msf2Sectors(int m, int s, int f) {
		return (m * 60 + s) * 75 + f;
	}
	
	/**
	 * Convert a sector count to minute-second-frame (MSF).
	 * 
	 * @param sectors
	 * 		The sector count.
	 * @return
	 * 		The MSF.
	 */
	public static Msf sectors2Msf(int sectors) {
		
		int m = sectors / (60 * 75);
		int s = (sectors - m * 60 * 75) / 75;
		int f = sectors - m * 60 * 75 - s * 75;
		
		return new Msf(m, s, f);
	}
	
	/**
	 * Convert a minute-second-frame (MSF) value to a lba.
	 * 
	 * @param m
	 * 		Minute component.
	 * @param s
	 * 		Second component.
	 * @param f
	 * 		Frame component.
	 * @return
	 * 		The lba.
	 */
	public static int msf2Lba(int m, int s, int f) {
		if (m < 90)
			return (m * 60 + s) * 75 + f - 150;
		else
			return (m * 60 + s) * 75 + f - 450150;
	}
	
	/**
	 * Convert an lba to minute-second-frame (MSF).
	 * 
	 * @param lba
	 * 		The lba.
	 * @return
	 * 		The MSF.
	 */
	public static Msf lba2Msf(int lba) {
		
		int m, s, f;
		
		if (lba >= -150) {
			m = (lba + 150) / (60 * 75);
			s = (lba + 150 - m * 60 * 75) / 75;
			f = lba + 150 - m * 60 * 75 - s * 75;
		} else {
			m = (lba + 450150) / (60 * 75);
			s = (lba + 450150 - m * 60 * 75) / 75;
			f = lba + 450150 - m * 60 * 75 - s * 75;
		}
		
		return new Msf(m, s, f);
	}
		
		
	
}
