using System;
using System.Drawing;
using System.IO;
using System.Text;
namespace Tango.Pulse
{
///
/// Represents a Pulse, twn file reader.
///
public class TwnFileReader
{
///
/// Reads the specified TWN stream.
///
/// The TWN stream.
///
public TwnFile Read(Stream twnStream)
{
TwnFile twnFile = new TwnFile();
BinaryReader reader = new BinaryReader(twnStream);
//Format Version (Default is 1.0).
twnFile.Version = reader.ReadSingle();
//The name of the design or other labeling information as UTF - 8 text padded with white spaces and limited to 50 bytes.
twnFile.Name = Encoding.UTF8.GetString(reader.ReadBytes(50)).Trim();
//The embedded preview image size in byte length as a 32 bit unsigned integer.
UInt32 thumbnail_size = reader.ReadUInt32();
//The total number of brush segments as a 32 bit unsigned integer.
UInt32 segments_count = reader.ReadUInt32();
//Number of copies. (The number 0 will be treated as 1, so the default is 0)
twnFile.NumberOfCopies = (int)reader.ReadUInt32();
//0 - Spool per segment. (default)
//1 - Spool per copy.
//2 - Single spool for all segments.
twnFile.SpoolingMethod = (SpoolingMethods)(int)reader.ReadByte();
//A unique code representing an optional media ID from Twine’s recommended media list.
twnFile.MediaID = (int)reader.ReadUInt32();
//3 ASCII characters representing the embedded embroidery file extension (e.g dst, pes).
twnFile.EmbroideryFileFormat = Encoding.ASCII.GetString(reader.ReadBytes(3));
//The byte array length of the embedded embroidery file.
UInt32 emb_file_size = reader.ReadUInt32();
//Array of bytes representing the design preview image in PNG format(transparent background).
//The size of the PNG byte array must be defined in the header. Recommended image width is 1280
//pixels while maintaining aspect ratio.
MemoryStream ms = new MemoryStream(reader.ReadBytes((int)thumbnail_size));
twnFile.Thumbnail = new Bitmap(ms);
twnFile.ThumbnailData = ms.ToArray();
//Array of Brush Segment. The number of brush segments must be defined in the header.
for (int i = 0; i < segments_count; i++)
{
TwnSegment segment = new TwnSegment();
//Required thread length in centimeters.
segment.Length = reader.ReadSingle();
//Number of brush stops.
UInt32 stop_count = reader.ReadUInt32();
//Array of brush stops.
for (int j = 0; j < stop_count; j++)
{
TwnStop stop = new TwnStop();
//The RGB red component.
stop.R = reader.ReadByte();
//The RGB green component.
stop.G = reader.ReadByte();
//The RGB blue component.
stop.B = reader.ReadByte();
//The Brush stop offset position within the parent brush length in percentage (0-1).
stop.Offset = reader.ReadSingle();
segment.BrushStops.Add(stop);
}
twnFile.Segments.Add(segment);
}
//Byte array representing the standard embroidery file which can be extracted and inserted into an embroidery machine.
twnFile.EmbroideryFile = reader.ReadBytes((int)emb_file_size);
return twnFile;
}
}
}