using System;
using OpenTK;

namespace SharpQuake
{
	internal class MsgReader
	{
		public bool IsBadRead
		{
			get
			{
				return this._IsBadRead;
			}
		}

		public int Position
		{
			get
			{
				return this._Count;
			}
		}

		public void Reset()
		{
			this._IsBadRead = false;
			this._Count = 0;
		}

		public int ReadChar()
		{
			if (!this.HasRoom(1))
			{
				return -1;
			}
			byte[] data = this._Source.Data;
			int count = this._Count;
			this._Count = count + 1;
			return (int)data[count];
		}

		public int ReadByte()
		{
			if (!this.HasRoom(1))
			{
				return -1;
			}
			byte[] data = this._Source.Data;
			int count = this._Count;
			this._Count = count + 1;
			return data[count];
		}

		public int ReadShort()
		{
			if (!this.HasRoom(2))
			{
				return -1;
			}
			int result = (int)((short)((int)this._Source.Data[this._Count] + ((int)this._Source.Data[this._Count + 1] << 8)));
			this._Count += 2;
			return result;
		}

		public int ReadLong()
		{
			if (!this.HasRoom(4))
			{
				return -1;
			}
			int result = (int)this._Source.Data[this._Count] + ((int)this._Source.Data[this._Count + 1] << 8) + ((int)this._Source.Data[this._Count + 2] << 16) + ((int)this._Source.Data[this._Count + 3] << 24);
			this._Count += 4;
			return result;
		}

		public float ReadFloat()
		{
			if (!this.HasRoom(4))
			{
				return 0f;
			}
			this._Val.b0 = this._Source.Data[this._Count];
			this._Val.b1 = this._Source.Data[this._Count + 1];
			this._Val.b2 = this._Source.Data[this._Count + 2];
			this._Val.b3 = this._Source.Data[this._Count + 3];
			this._Count += 4;
			this._Val.i0 = common.LittleLong(this._Val.i0);
			return this._Val.f0;
		}

		public string ReadString()
		{
			int num = 0;
			do
			{
				int num2 = this.ReadChar();
				if (num2 == -1 || num2 == 0)
				{
					break;
				}
				this._Tmp[num] = (char)num2;
				num++;
			}
			while (num < this._Tmp.Length - 1);
			return new string(this._Tmp, 0, num);
		}

		public float ReadCoord()
		{
			return (float)this.ReadShort() * 0.125f;
		}

		public float ReadAngle()
		{
			return (float)this.ReadChar() * 1.40625f;
		}

		public Vector3 ReadCoords()
		{
			Vector3 result;
			result.X = this.ReadCoord();
			result.Y = this.ReadCoord();
			result.Z = this.ReadCoord();
			return result;
		}

		public Vector3 ReadAngles()
		{
			Vector3 result;
			result.X = this.ReadAngle();
			result.Y = this.ReadAngle();
			result.Z = this.ReadAngle();
			return result;
		}

		private bool HasRoom(int bytes)
		{
			if (this._Count + bytes > this._Source.Length)
			{
				this._IsBadRead = true;
				return false;
			}
			return true;
		}

		public MsgReader(MsgWriter source)
		{
			this._Source = source;
			this._Val = Union4b.Empty;
			this._Tmp = new char[2048];
		}

		private MsgWriter _Source;

		private bool _IsBadRead;

		private int _Count;

		private Union4b _Val;

		private char[] _Tmp;
	}
}
