/*
Copyright (C) 2006 Evan Teran
                   eteran@alum.rit.edu

This program 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.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#include "Instruction.h"
#include <iostream>
#include <stdint.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc, char *argv[]) {

	if(argc == 2) {
		int fd = open(argv[1], O_RDONLY);
		if(fd != -1) {
			off_t size = lseek(fd, 0, SEEK_END);
			lseek(fd, 0, SEEK_SET);
			void *const p = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);

			if(p != 0) {

				const uint8_t *ptr = reinterpret_cast<const uint8_t *>(p);
				const uint8_t *const end_ptr = ptr + size;

				while(ptr < end_ptr) {
				
					Instruction instruction(ptr, end_ptr - ptr, 0x80400000, Instruction::MODE_32BIT);

					if(instruction.valid()) {
//						std::cout << instruction.size() << " - ";
						std::cout << instruction.format() << std::endl;
						ptr += instruction.size();
					} else {
						std::cout << "(bad)";
						ptr += 1;
					}

				}

			}

			close(fd);
		}
	} else {
		std::cout << argv[0] << " <file>" << std::endl;
	}
	return 0;
}
