1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
extern crate flate2;
extern crate xml;
extern crate base64;

use std::str::FromStr;
use std::collections::HashMap;
use std::io::{BufReader, Read, Error};
use std::fmt;
use xml::reader::{EventReader, Error as XmlError};
use xml::reader::XmlEvent;
use xml::attribute::OwnedAttribute;
use base64::{u8de as decode_base64, Base64Error};
use flate2::read::{ZlibDecoder, GzDecoder};

#[derive(Debug)]
pub enum ParseTileError {
    ColourError,
    OrientationError,
}

// Loops through the attributes once and pulls out the ones we ask it to. It
// will check that the required ones are there. This could have been done with
// attrs.find but that would be inefficient.
//
// This is probably a really terrible way to do this. It does cut down on lines
// though which is nice.
macro_rules! get_attrs {
    ($attrs:expr, optionals: [$(($oName:pat, $oVar:ident, $oMethod:expr)),*],
     required: [$(($name:pat, $var:ident, $method:expr)),*], $err:expr) => {
        {
            $(let mut $oVar = None;)*
            $(let mut $var = None;)*
            for attr in $attrs.iter() {
                match attr.name.local_name.as_ref() {
                    $($oName => $oVar = $oMethod(attr.value.clone()),)*
                    $($name => $var = $method(attr.value.clone()),)*
                    _ => {}
                }
            }
            if !(true $(&& $var.is_some())*) {
                return Err($err);
            }
            (($($oVar),*), ($($var.unwrap()),*))
        }
    }
}

// Goes through the children of the tag and will call the correct function for
// that child. Closes the tag
//
// Not quite as bad.
macro_rules! parse_tag {
    ($parser:expr, $close_tag:expr, $($open_tag:expr => $open_method:expr),*) => {
        loop {            
            match try!($parser.next().map_err(TiledError::XmlDecodingError)) {
                XmlEvent::StartElement {name, attributes, ..} => {
                    if false {}
                    $(else if name.local_name == $open_tag {
                        match $open_method(attributes) {
                            Ok(()) => {},
                            Err(e) => return Err(e)
                        };
                    })*
                }
                XmlEvent::EndElement {name, ..} => {
                    if name.local_name == $close_tag {
                        break;
                    }
                }
                XmlEvent::EndDocument => return Err(TiledError::PrematureEnd("Document ended before we expected.".to_string())),
                _ => {}
            }
        }
    }
}

#[derive(Debug, PartialEq, Eq)]
pub struct Colour {
    pub red: u8,
    pub green: u8,
    pub blue: u8
}

impl FromStr for Colour {
    type Err = ParseTileError;

    fn from_str(s: &str) -> Result<Colour, ParseTileError> {
        let s = if s.starts_with("#") {
            &s[1..]
        } else {
            s
        };
        if s.len() != 6 {
            return Err(ParseTileError::ColourError);
        }
        let r = u8::from_str_radix(&s[0..2], 16);
        let g = u8::from_str_radix(&s[2..4], 16);
        let b = u8::from_str_radix(&s[4..6], 16);
        if r.is_ok() && g.is_ok() && b.is_ok() {
            return Ok(Colour {red: r.unwrap(), green: g.unwrap(), blue: b.unwrap()})
        }
        Err(ParseTileError::ColourError)
    }
}

/// Errors which occured when parsing the file
#[derive(Debug)]
pub enum TiledError {
    /// A attribute was missing, had the wrong type of wasn't formated
    /// correctly.
    MalformedAttributes(String),
    /// An error occured when decompressing using the
    /// [flate2](https://github.com/alexcrichton/flate2-rs) crate.
    DecompressingError(Error),
    Base64DecodingError(Base64Error),
    XmlDecodingError(XmlError),
    PrematureEnd(String),
    Other(String)
}

impl fmt::Display for TiledError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        match *self {
            TiledError::MalformedAttributes(ref s) => write!(fmt, "{}", s),
            TiledError::DecompressingError(ref e) => write!(fmt, "{}", e),
            TiledError::Base64DecodingError(ref e) => write!(fmt, "{}", e),
            TiledError::XmlDecodingError(ref e) => write!(fmt, "{}", e),
            TiledError::PrematureEnd(ref e) => write!(fmt, "{}", e),
            TiledError::Other(ref s) => write!(fmt, "{}", s),
        }
    }
}

// This is a skeleton implementation, which should probably be extended in the future.
impl std::error::Error for TiledError {
    fn description(&self) -> &str {
        match *self {
            TiledError::MalformedAttributes(ref s) => s.as_ref(),
            TiledError::DecompressingError(ref e) => e.description(),
            TiledError::Base64DecodingError(ref e) => e.description(),
            TiledError::XmlDecodingError(ref e) => e.description(),
            TiledError::PrematureEnd(ref s) => s.as_ref(),
            TiledError::Other(ref s) => s.as_ref(),
        }
    }
    fn cause(&self) -> Option<&std::error::Error> {
        match *self {
            TiledError::MalformedAttributes(_) => None,
            TiledError::DecompressingError(ref e) => Some(e as &std::error::Error),
            TiledError::Base64DecodingError(ref e) => Some(e as &std::error::Error),
            TiledError::XmlDecodingError(ref e) => Some(e as &std::error::Error),
            TiledError::PrematureEnd(_) => None,
            TiledError::Other(_) => None,
        }
    }

}

pub type Properties = HashMap<String, String>;

fn parse_properties<R: Read>(parser: &mut EventReader<R>) -> Result<Properties, TiledError> {
    let mut p = HashMap::new();
    parse_tag!(parser, "properties",
               "property" => |attrs:Vec<OwnedAttribute>| {
                    let ((), (k, v)) = get_attrs!(
                        attrs,
                        optionals: [],
                        required: [("name", key, |v| Some(v)),
                                   ("value", value, |v| Some(v))],
                        TiledError::MalformedAttributes("property must have a name and a value".to_string()));
                    p.insert(k, v);
                    Ok(())
               });
    Ok(p)
}

/// All Tiled files will be parsed into this. Holds all the layers and tilesets
#[derive(Debug, PartialEq)]
pub struct Map {
    pub version: String,
    pub orientation: Orientation,
    pub width: u32,
    pub height: u32,
    pub tile_width: u32,
    pub tile_height: u32,
    pub tilesets: Vec<Tileset>,
    pub layers: Vec<Layer>,
    pub object_groups: Vec<ObjectGroup>,
    pub properties: Properties,
    pub background_colour: Option<Colour>,
}

impl Map {
    fn new<R: Read>(parser: &mut EventReader<R>, attrs: Vec<OwnedAttribute>) -> Result<Map, TiledError>  {
        let (c, (v, o, w, h, tw, th)) = get_attrs!(
            attrs,
            optionals: [("backgroundcolor", colour, |v:String| v.parse().ok())],
            required: [("version", version, |v| Some(v)),
                       ("orientation", orientation, |v:String| v.parse().ok()),
                       ("width", width, |v:String| v.parse().ok()),
                       ("height", height, |v:String| v.parse().ok()),
                       ("tilewidth", tile_width, |v:String| v.parse().ok()),
                       ("tileheight", tile_height, |v:String| v.parse().ok())],
            TiledError::MalformedAttributes("map must have a version, width and height with correct types".to_string()));

        let mut tilesets = Vec::new();
        let mut layers = Vec::new();
        let mut properties = HashMap::new();
        let mut object_groups = Vec::new();
        parse_tag!(parser, "map",
                   "tileset" => | attrs| {
                        tilesets.push(try!(Tileset::new(parser, attrs)));
                        Ok(())
                   },
                   "layer" => |attrs| {
                        layers.push(try!(Layer::new(parser, attrs, w )));
                        Ok(())
                   },
                   "properties" => |_| {
                        properties = try!(parse_properties(parser));
                        Ok(())
                   },
                   "objectgroup" => |attrs| {
                       object_groups.push(try!(ObjectGroup::new(parser, attrs)));
                       Ok(())
                   });
        Ok(Map {version: v, orientation: o,
                width: w, height: h,
                tile_width: tw, tile_height: th,
                tilesets: tilesets, layers: layers, object_groups: object_groups,
                properties: properties,
                background_colour: c,})
    }

    /// This function will return the correct Tileset given a GID.
    pub fn get_tileset_by_gid(&self, gid: u32) -> Option<&Tileset> {
        let mut maximum_gid: i32 = -1;
        let mut maximum_ts = None;
        for tileset in self.tilesets.iter() {
            if tileset.first_gid as i32 > maximum_gid && tileset.first_gid < gid {
                maximum_gid = tileset.first_gid as i32;
                maximum_ts = Some(tileset);
            }
        }
        maximum_ts
    }
}

#[derive(Debug, PartialEq, Eq)]
pub enum Orientation {
    Orthogonal,
    Isometric,
    Staggered,
    Hexagonal
}

impl FromStr for Orientation {
    type Err = ParseTileError;

    fn from_str(s: &str) -> Result<Orientation, ParseTileError> {
        match s {
            "orthogonal" => Ok(Orientation::Orthogonal),
            "isometric" => Ok(Orientation::Isometric),
            "staggered" => Ok(Orientation::Staggered),
            "hexagonal" => Ok(Orientation::Hexagonal),
            _ => Err(ParseTileError::OrientationError)
        }
    }
}

/// A tileset, usually the tilesheet image.
#[derive(Debug, PartialEq, Eq)]
pub struct Tileset {
    /// The GID of the first tile stored
    pub first_gid: u32,
    pub name: String,
    pub tile_width: u32,
    pub tile_height: u32,
    pub spacing: u32,
    pub margin: u32,
    /// The Tiled spec says that a tileset can have mutliple images so a `Vec`
    /// is used. Usually you will only use one.
    pub images: Vec<Image>,
    pub tiles: Vec<Tile>
}

impl Tileset {
    fn new<R: Read>(parser: &mut EventReader<R>, attrs: Vec<OwnedAttribute>) -> Result<Tileset, TiledError> {
        let ((s, m), (g, n, w, h)) = get_attrs!(
           attrs,
           optionals: [("spacing", spacing, |v:String| v.parse().ok()),
                       ("margin", margin, |v:String| v.parse().ok())],
           required: [("firstgid", first_gid, |v:String| v.parse().ok()),
                      ("name", name, |v| Some(v)),
                      ("tilewidth", width, |v:String| v.parse().ok()),
                      ("tileheight", height, |v:String| v.parse().ok())],
           TiledError::MalformedAttributes("tileset must have a firstgid, name tile width and height with correct types".to_string()));

        let mut images = Vec::new();
        let mut tiles = Vec::new();
        parse_tag!(parser, "tileset",
                   "image" => |attrs| {
                        images.push(try!(Image::new(parser, attrs)));
                        Ok(())
                   },
                   "tile" => |attrs| {
                        tiles.push(try!(Tile::new(parser, attrs)));
                        Ok(())
                   });

        Ok(Tileset {first_gid: g,
                    name: n,
                    tile_width: w, tile_height: h,
                    spacing: s.unwrap_or(0),
                    margin: m.unwrap_or(0),
                    images: images,
                    tiles: tiles})
   }
}

#[derive(Debug, PartialEq, Eq)]
pub struct Tile {
    pub id: u32,
    pub images: Vec<Image>
}

impl Tile {
    fn new<R: Read>(parser: &mut EventReader<R>, attrs: Vec<OwnedAttribute>) -> Result<Tile, TiledError> {
        let (_, i) = get_attrs!(
            attrs,
            optionals: [],
            required: [("id", id, |v:String| v.parse().ok())],
            TiledError::MalformedAttributes("tile must have an id with the correct type".to_string()));

        let mut images = Vec::new();
        parse_tag!(parser, "tile",
                   "image" => |attrs| {
                        images.push(try!(Image::new(parser, attrs)));
                        Ok(())
        });
        Ok(Tile {id: i, images: images})
    }
}

#[derive(Debug, PartialEq, Eq)]
pub struct Image {
    /// The filepath of the image
    pub source: String,
    pub width: i32,
    pub height: i32,
    pub transparent_colour: Option<Colour>,
}

impl Image {
    fn new<R: Read>(parser: &mut EventReader<R>, attrs: Vec<OwnedAttribute>) -> Result<Image, TiledError> {
        let (c, (s, w, h)) = get_attrs!(
            attrs,
            optionals: [("trans", trans, |v:String| v.parse().ok())],
            required: [("source", source, |v| Some(v)),
                       ("width", width, |v:String| v.parse().ok()),
                       ("height", height, |v:String| v.parse().ok())],
            TiledError::MalformedAttributes("image must have a source, width and height with correct types".to_string()));

        parse_tag!(parser, "image", "" => |_| Ok(()));
        Ok(Image {source: s, width: w, height: h, transparent_colour: c})
    }
}

#[derive(Debug, PartialEq)]
pub struct Layer {
    pub name: String,
    pub opacity: f32,
    pub visible: bool,
    /// The tiles are arranged in rows. Each tile is a number which can be used
    ///  to find which tileset it belongs to and can then be rendered.
    pub tiles: Vec<Vec<u32>>,
    pub properties: Properties
}

impl Layer {
    fn new<R: Read>(parser: &mut EventReader<R>, attrs: Vec<OwnedAttribute>, width: u32) -> Result<Layer, TiledError> {
        let ((o, v), n) = get_attrs!(
            attrs,
            optionals: [("opacity", opacity, |v:String| v.parse().ok()),
                        ("visible", visible, |v:String| v.parse().ok().map(|x:i32| x == 1))],
            required: [("name", name, |v| Some(v))],
            TiledError::MalformedAttributes("layer must have a name".to_string()));
        let mut tiles = Vec::new();
        let mut properties = HashMap::new();
        parse_tag!(parser, "layer",
                   "data" => |attrs| {
                        tiles = try!(parse_data(parser, attrs, width));
                        Ok(())
                   },
                   "properties" => |_| {
                        properties = try!(parse_properties(parser));
                        Ok(())
                   });
        Ok(Layer {name: n, opacity: o.unwrap_or(1.0), visible: v.unwrap_or(true), tiles: tiles,
                  properties: properties})
    }
}

#[derive(Debug, PartialEq)]
pub struct ObjectGroup {
    pub name: String,
    pub opacity: f32,
    pub visible: bool,
    pub objects: Vec<Object>,
    pub colour: Option<Colour>,
}

impl ObjectGroup {
    fn new<R: Read>(parser: &mut EventReader<R>, attrs: Vec<OwnedAttribute>) -> Result<ObjectGroup, TiledError> {
        let ((o, v, c), n) = get_attrs!(
            attrs,
            optionals: [("opacity", opacity, |v:String| v.parse().ok()),
                        ("visible", visible, |v:String| v.parse().ok().map(|x:i32| x == 1)),
                        ("color", colour, |v:String| v.parse().ok())],
            required: [("name", name, |v| Some(v))],
            TiledError::MalformedAttributes("object groups must have a name".to_string()));
        let mut objects = Vec::new();
        parse_tag!(parser, "objectgroup",
                   "object" => |attrs| {
                        objects.push(try!(Object::new(parser, attrs)));
                        Ok(())
                   });
        Ok(ObjectGroup {name: n,
                        opacity: o.unwrap_or(1.0), visible: v.unwrap_or(true),
                        objects: objects,
                        colour: c})
    }
}

#[derive(Debug, PartialEq)]
pub enum Object {
      Rect { id: u32, gid: u32, name: String, obj_type: String, x: f32,  y: f32, width: f32, height: f32,   visible: bool},
      Ellipse {id: u32, gid: u32, name: String, obj_type: String, x: f32,  y: f32,  width: f32,  height: f32,  visible: bool},
      Polyline {id: u32, gid: u32, name: String, obj_type: String, x: f32,  y: f32,  points: Vec<(f32, f32)>,  visible: bool},
      Polygon {id: u32, gid: u32, name: String, obj_type: String, x: f32,  y: f32,  points: Vec<(f32, f32)>,  visible: bool}
}

impl Object {
    fn new<R: Read>(parser: &mut EventReader<R>, attrs: Vec<OwnedAttribute>) -> Result<Object, TiledError> {
        let ((id,gid,n,t,w, h, v), (x, y)) = get_attrs!(
            attrs,
            optionals: [("id", id, |v:String| v.parse().ok()),
                        ("gid", gid, |v:String| v.parse().ok()),
                        ("name", name, |v:String| v.parse().ok()),
                        ("type", obj_type, |v:String| v.parse().ok()),
                        ("width", width, |v:String| v.parse().ok()),
                        ("height", height, |v:String| v.parse().ok()),
                        ("visible", visible, |v:String| v.parse().ok())],
            required: [("x", x, |v:String| v.parse().ok()),
                       ("y", y, |v:String| v.parse().ok())],
            TiledError::MalformedAttributes("objects must have an x and a y number".to_string()));
        let mut obj = None;
        let v = v.unwrap_or(true);
        let w = w.unwrap_or(0f32);
        let h = h.unwrap_or(0f32);
        let id = id.unwrap_or(0u32);
        let gid = gid.unwrap_or(0u32);
        let n = n.unwrap_or(String::new());
        let t = t.unwrap_or(String::new());
        
        parse_tag!(parser, "object",
                   "ellipse" => |_| {
                        obj = Some(Object::Ellipse {id: id, gid: gid, name: n.clone(), obj_type: t.clone(),x: x, y: y,
                                            width: w , height: h ,
                                            visible: v});
                        Ok(())
                    },
                    "polyline" => |attrs| {
                        obj = Some(try!(Object::new_polyline(id, gid,  n.clone(), t.clone(),x, y, v, attrs)));
                        Ok(())
                    },
                    "polygon" => |attrs| {
                        obj = Some(try!(Object::new_polygon(id, gid,  n.clone(),  t.clone(),x, y, v, attrs)));
                        Ok(())
                    });
        if obj.is_some() {
            Ok(obj.unwrap())
        } else {
            Ok(Object::Rect {id: id, gid: gid, name: n.clone(), obj_type: t.clone(),x: x, y: y, width: w, height: h, visible: v})
        }
    }

    fn new_polyline(id: u32, gid: u32, name: String, obj_type: String, x: f32, y: f32, v: bool, attrs: Vec<OwnedAttribute>) -> Result<Object, TiledError> {
        let ((), s) = get_attrs!(
            attrs,
            optionals: [],
            required: [("points", points, |v| Some(v))],
            TiledError::MalformedAttributes("A polyline must have points".to_string()));
       let points = try!(Object::parse_points(s));
       Ok(Object::Polyline {id: id, gid: gid, name: name, obj_type: obj_type,x: x, y: y, points: points, visible: v})
    }

    fn new_polygon(id: u32, gid: u32, name: String, obj_type: String, x: f32, y: f32, v: bool, attrs: Vec<OwnedAttribute>) -> Result<Object, TiledError> {
        let ((), s) = get_attrs!(
            attrs,
            optionals: [],
            required: [("points", points, |v| Some(v))],
            TiledError::MalformedAttributes("A polygon must have points".to_string()));
       let points = try!(Object::parse_points(s));
       Ok(Object::Polygon {id: id, gid: gid, name: name, obj_type: obj_type,x: x, y: y, points: points, visible: v})
    }

    fn parse_points(s: String) -> Result<Vec<(f32, f32)>, TiledError> {
        let pairs = s.split(' ');
        let mut points = Vec::new();
        for v in pairs.map(|p| p.split(',')) {
            let v: Vec<&str> = v.collect();
            if v.len() != 2 {
                return Err(TiledError::MalformedAttributes("one of a polyline's points does not have an x and y coordinate".to_string()));
            }
            let (x, y) = (v[0].parse().ok(), v[1].parse().ok());
            if x.is_none() || y.is_none() {
                return Err(TiledError::MalformedAttributes("one of polyline's points does not have i32eger coordinates".to_string()));
            }
            points.push((x.unwrap(), y.unwrap()));
        }
        Ok(points)
    }
}

fn parse_data<R: Read>(parser: &mut EventReader<R>, attrs: Vec<OwnedAttribute>, width: u32) -> Result<Vec<Vec<u32>>, TiledError> {
    let ((e, c), ()) = get_attrs!(
        attrs,
        optionals: [("encoding", encoding, |v| Some(v)),
                   ("compression", compression, |v| Some(v))],
        required: [],
        TiledError::MalformedAttributes("data must have an encoding and a compression".to_string()));

    match (e,c) {
        (None,None) => return Err(TiledError::Other("XML format is currently not supported".to_string())),
        (Some(e),None) =>
            match e.as_ref() {
                "base64" => return parse_base64(parser).map(|v| convert_to_u32(&v,width)),
                "csv" => return decode_csv(parser),
                e => return Err(TiledError::Other(format!("Unknown encoding format {}",e))),
            },
        (Some(e),Some(c)) =>
            match (e.as_ref(),c.as_ref()) {
                ("base64","zlib") => return parse_base64(parser).and_then(decode_zlib).map(|v| convert_to_u32(&v,width) ),
                ("base64","gzip") => return parse_base64(parser).and_then(decode_gzip).map(|v| convert_to_u32(&v,width)),
                (e,c) => return Err(TiledError::Other(format!("Unknown combination of {} encoding and {} compression",e,c)))
            },
        _ => return Err(TiledError::Other("Missing encoding format".to_string())),
    };
}

fn parse_base64<R: Read>(parser: &mut EventReader<R>) -> Result<Vec<u8>, TiledError> {
    loop {
        match try!(parser.next().map_err(TiledError::XmlDecodingError)) {
            XmlEvent::Characters(s) => return decode_base64(s.trim().as_bytes())
                                    .map_err(TiledError::Base64DecodingError),
            XmlEvent::EndElement {name, ..} => {
                if name.local_name == "data" {
                    return Ok(Vec::new());
                }
            }
            _ => {}
        }
    }
}

fn decode_zlib(data: Vec<u8>) -> Result<Vec<u8>, TiledError> {
    let mut zd = ZlibDecoder::new(BufReader::new(&data[..]));
    let mut data = Vec::new();
    match zd.read_to_end(&mut data) {
        Ok(_v) => {},
        Err(e) => return Err(TiledError::DecompressingError(e))
    }
    Ok(data)
}

fn decode_gzip(data: Vec<u8>) -> Result<Vec<u8>, TiledError> {
    let mut gzd = match GzDecoder::new(BufReader::new(&data[..])) {
        Ok(gzd) => gzd,
        Err(e) => return Err(TiledError::DecompressingError(e))
    };
    let mut data = Vec::new();
    match gzd.read_to_end(&mut data) {
        Ok(_v) => {},
        Err(e) => return Err(TiledError::DecompressingError(e))
    }
    Ok(data)
}

fn decode_csv<R: Read>(parser: &mut EventReader<R>) -> Result<Vec<Vec<u32>>, TiledError> {
    loop {
        match try!(parser.next().map_err(TiledError::XmlDecodingError)) {
            XmlEvent::Characters(s) => {
                let mut rows: Vec<Vec<u32>> = Vec::new();
                for row in s.split('\n') {
                    if row.trim() == "" {
                        continue;
                    }
                    rows.push(row.split(',').filter(|v| v.trim() != "").map(|v| v.replace('\r', "").parse().unwrap()).collect());
                }
                return Ok(rows);
            }
            XmlEvent::EndElement {name, ..} => {
                if name.local_name == "data" {
                    return Ok(Vec::new());
                }
            }
            _ => {}
        }
    }
}

fn convert_to_u32(all: &Vec<u8>, width: u32) -> Vec<Vec<u32>> {
    let mut data = Vec::new();
    for chunk in all.chunks((width * 4) as usize) {
        let mut row = Vec::new();
        for i in 0 .. width {
            let start: usize = i as usize * 4;
            let n = ((chunk[start + 3] as u32) << 24) +
                    ((chunk[start + 2] as u32) << 16) +
                    ((chunk[start + 1] as u32) <<  8) +
                    chunk[start] as u32;
            row.push(n);
        }
        data.push(row);
    }
    data
}

/// Parse a buffer hopefully containing the contents of a Tiled file and try to
/// parse it.
pub fn parse<R: Read>(reader: R) -> Result<Map, TiledError> {
    let mut parser = EventReader::new(reader);
    loop {
        match try!(parser.next().map_err(TiledError::XmlDecodingError)) {
            XmlEvent::StartElement {name, attributes, ..}  => {
                if name.local_name == "map" {
                    return Map::new(&mut parser, attributes);
                }
            }
            XmlEvent::EndDocument => return Err(TiledError::PrematureEnd("Document ended before map was parsed".to_string())),
            _ => {}
        }
    }
}