C Programming Assignment Help

C Programming Assignment HelpC was developed at AT&T Bell Labs by Dennis Ritchie in the early 1970’s. It was used to implement Unix on the PDP-11. Dennis Ritchie and Brian Kernigan wrote the definitive book on C, which is known as K&R C. There have been a lot of changes to C since it was first developed, with prototypes in headers being one of the more obvious ones. C++ was an extension to the language developed by Bjarne Stroustrup, it was originally a preprocessor to C called cfront that took in C++ code and output C code that was compiled using the regular compiler. One of the principles of C++ was that it was sesigned to be efficient, so if you didn’t need a feature it wouldn’t add to the runtime costs of using a related feature, and it was designed to be as compatable with C as possible. C# was developed by Microsoft as an alternative to Java (especially after the lawsuit Sun brought against Microsoft’s Java implementation).
C :The original version of the language, it was developed based on the language B and is like a portable assembly language. The basic types supported by C are char, short, int, long, float and double. Unlike Java the sizes of the types are not the same across all platforms, char is used to access strings, short is designed to be used for numbers up to 32767, int is to be used as the most efficient form of variable, it is at least the same size as short. Long is designed when you need larger numbers, it is guaranteed to be at least the same size as int. Float and double are used on platforms with floating point support, float is the smaller format and is less accurate, operations are normally handled in double precision and converted back to float. C does not support classes, but does support struct which allows you to group a series of fields together in a related format. C also supports pointers and arrays, which are almost interchangable. Strings are are zero terminated array of characters.

If you need C Programming Assignment Help/ C Programming Homework Help ,C Project Help or having problems with your C Programming Coursework then we have the solutions you need. We can help you with any Programming Problem you may have. We solve your homework needs, and we guarantee results. You mayneed help with a simple C program or you may need a C Programmer to reimplement a compiler from scratch, we have C Programming Experts who would help you with anything related to coding in C Language..We also provide Online C Programming Tutoring for undergraduate,graduate and Phd level.

For email based C Programming Assignment Help/C Programming Homework Help or Help with C Project,upload your C Programming Assignment/C Programming Homework or C Project at our website or email it to support@locusrags.com

C++ :C++ was developed by Bjarne Stroustrup originally as a preprocessor for C. It added classes which are similar to struct but allow for methods to be associated with the data. Virtual methods allow you to handle related structures with specialized code, operator overloading allows you to write code as though the classes you write were part of the language, so you can use +,-,* and other operators to operate on custom data types. So if you wanted a complex number class, you can mix operations with regular values and it will work as you expect. Templates allow you to write code that handles any type, and are integral to the STL (Standard Template Library). Exceptions were added to the language so that you can handle errors in a more consistent fashion. C++ can be mixed with C code, and will compile most C code with very few modifications.

For C++ Programming Assignment Help/C++ Homework Help and C++ Project Help you can upload your requirements at our website or email it to support@locusrags.com

You can chat on our live chat window to schedule an Online Tutoring session with one of our C Programming Tutors .
C# :Anders Jarlsberg developed C# at Microsoft as part of the .NET framework. It was similar to Java at version 1, but has added more C++ style features as it has progressed and has become a very powerful language with some nice concise syntax and some features that are not even present in C++. C# added generics (similar to C++ templates), anonymous methods, with C# version 2. Auto implemented properties, anonymous types, extension methods, query expressions, lambda expressions were added in C# version 3. C# version 4 added support for named and optional arguements, and C# version 5 added support for asyncronous methods. C# is executed as bytecode in MSIL (Microsoft Intermediate Language), although there is an open source implementation called Mono. The preprocessor support is limited to #define, #ifdef type constructs, which make it less powerful than C/C++ although since it lacks macros it is harder for it to be abused and is still an improvement on Java which does not any built in preprocessor support.

Help on C/C++/C# Programming Basics
C/C++/C# Programming Syntax, How to use an IDE (Visual Studio, CodeBlocks, and Eclipse)

Introduction to Variables : string, int, boolean, byte, char, short, float, double, long, arrays.
Comparison operators: <,>,==,!=,<=,>=
Comments: // and /* */
Operators: +,-,*,/,++,–,%,&,&&,|,||,<<,>>,>>>,!,?,:
Strings: C string library methods char*, strcmp, stricmp, strcpy, strncpy, strstr, strlen, memcpy, strcat, strncat,strcmp, strncmp, strchr, strrchr, memset,
C++ stl string methods size, length, resize, at, append, insert, replace, c_str, find, rfind,find_first_of, substr, compare, find_last_of, copy, erase
C# string methods Length, Compare, CompareOrdinal, Concat, Copy, EndsWith, Format, IndexOf,
IndexOfAny, Insert, Join, LastIndexOf, PadLeft, PadRight, Remove, Replace, Split,StartsWith,Substring, ToCharArray, ToLower, ToString, ToUpper, Trim, TrimEnd, TrimStart
Assistance with Intermediate C/C++/C# Programming.
Using Classes : class, NULL, virtual, fields, enum, abstract, private, protected, public, this, new, const, mutable
Functions : virtual, static, arguements
Exception handling : exception, try, catch, finally
Collections :     deque, list, vector, hash_map, hash_multimap, hash_multiset, hash_set, map, multimap, multiset, set, priority_queue, queue, stack, iterator, for each, begin, end, bitset, size, empty, resize, shrink_to_fit, at, insert, push_back, pop_back, clear, swap, splice, remove, unique, sort, reverse, reserve, count, find, at are present in C++ STL C# offers List, LinkedList, Dictionary, Queue, Stack, HashSet
Sample Codes:

The programming is done in c+ Form a team of a maximum of three students. Develop programs by implementing algorithms MINMAX-A-B (Rich & Knight) and ALPHA-BETA-SEARCH (Russell & Norvig) in C or C++ language. Devise Deep-Enough (use some suggestions as given in Rich and Knight’s book) and Move-Gen functions.Use Kalah game as an example to test your program. The rules of Kalah are given at the end. Devise at least one evaluation function per person.

Execute your programs to play the game and analyze the performance of each algorithm and each evaluation function by tabulating the total length of the game path, total number of nodes generated and expanded, execution time and the size of memory used by the program. Thus for two evaluation functions (assuming two students in a team) and two algorithms, you will be executing programs four times. Five extra points if you develop an interface, so that the programs of team mates play against each other automatically and they can be demonstrated to a Non-AI person.
You are expected to develop the program as a team of a maximum of three students. After the program is developed and tested for a sample example, each member of the team will work separately to do the following.

Choose his/her evaluation function.Execute the programs with all evaluation functions of the team and generate his/her tables.Analyze the results and write the conclusions you draw from these analyses. Write his/her documentation explaining the problem, methodology, programs, description of evaluation functions, any special approaches used, analyses of results, and conclusions. Demonstrate the execution of the programs to the instructor. You should be prepared for discussions of your programs, results, and their analyses at the time of the demo.

Instructions Do the following:

Create class and sequence diagrams for the initial code.Carry out the refactorings below. Create class and sequence diagrams for the refactored code.Make observations on the differences, including any improvements, between the structure before and after.

Original Code

The original code has some deficiencies. The refactoring will fix some of them. A feature that will be
needed (as a motivation for the refactoring that will be done) is an HTML version of the statement,
currently only a text statement is created.

Refactorings Carry out this sequence of refactorings.

1. Bad smell: the statement method (function) is long.Extract the switch from the statement method into a new method and replace the switch with a call to the new method. Name the new method amountFor.
[Extract method]
2. Bad smell: bad formal parameter name Rename each to aRental (if you used that name).
3. Bad smell: amountFor is misplaced, move to Rental No parameters are necessary, do not pass any.
[Move method] Bad smell: bad method name Rename amountFor to getCharge()
Bad smell: unnecessary temp The variable thisAmount in statement is set and never changed. It is used twice. It can be eliminated. Eliminate thisAmount, replace with call.[Replace temp with query] Bad smell: misplaced responsibility Determining the frequent renter points should probably be a responsibility of Rental rather than the statement method in Customer. [Extract method] Create new method getFrequentRenterPoints() in Rental and call it in statement to get the frequent renter points. (Remember behavior should be unchanged.) Bad smell: statement is still a long method. The loop in statement is accumulating the total charge for all movies. Eliminate totalAmount by creating a private method in Customer named getTotalCharge() (will have a loop). Use a call to this method (the query) where totalAmount is being output. Other methods could use this query. [Replace temp with query]

 

8. Bad smell: statement is still a long method. The loop in statement is accumulating the frequent renter points for all movies. Eliminate frequentRenterPoints by creating a private method in Customer named
getTotalFrequentRenterPoints() (will have a loop). Use a call to this method (the query) where frequentRenterPoints is being output. Other methods could use this query. [Replace temp with query]

— Note: At this point a method htmlS tatement could more easily be added than in the original.
It would be similar to statement but with HTML tags in the strings. Having extracted getTotalCharge() and getTotalFrequentRenterPoints() causes these calculations not to be embedded in the two statement methods. The switch in Rental is selecting behavior according to movie category. This behavior
9.
determination would be better elsewhere. There is an opportunity for polymorphism here. Move getCharge() to Movie. Leave the getCharge() in Rental and delegate to Movie (call the new getCharge() in Movie from the one in Rental). It will be necessary to pass thenumber of days rented. getCharge() and getFrequentRenterPoints() both contain things that may vary with
10. type (Movie) and should probably be kept together. Move getFrequentRenterPoints() to Movie. Leave the getFrequentRenterPoints() in Rental and delegate to Movie (call the new getFrequentRenterPoints() in Movie from the one in Rental). As for all refactorings you can do it in small steps:

— getCharge is in Movie. It uses a switch according to the movie’s category in the charge calculation. If a new category is added the switch will need updated. We would like getCharge to behave according to the movie’s category. A problem, movies will change category, a movie will not be a new release forever.
We will add an abstract class Price. Price will be the base class for RegularPrice, ChildrensPrice, and NewReleasePrice. We will do several refactorings to get to our goal. We will need to move from an int price code to one of type Price. Thus only accessors should
11. be used on _price_code in Movie. Make the Movie constructor use a mutator (setter).
[Self encapsulate field] 12. Define new classes. Define in movie.h the following classes with inheritance as indicated: RegularPrice inherits from Price, ChildrensPrice inherits from Price, and NewReleasePrice inherits from
Price.Compile and test.
13. Add getPriceCode() functions. Declare a pure virtual function named getPriceCode() in Price. Define a virtual function getPriceCode() in each of the subclasses that returns the corresponding category (ex.Movie::CHILDREN).Compile and test.

Declare getFrequentRenterPoints() in movie.h, definegetFrequentRenterPoints() in movie.cpp Compile and test Copy function body over Compile and test Fix needed parameter, method calls Compile and test
Comment out code in Rental, add delegation call. Compile and test

14. We now will do the type change for _price_code in Movie.

 

Move the mutator definition for _price_code to the .cpp file (only short functions should be in the .h).
Compile and test. Type change:
o Change _price_code to type Price*
o Change setPriceCode() to set _price_code to an new instance of the correct Price object (use a switch)
o Change getPriceCode() to call getPriceCode() on the Price object and return that value

15. For the polymorphism we want getCharge() to be in Price. Move getCharge() from Movie to Price. (Don’t forget to make it virtual.) Delegate in Movie to the getCharge() in Price.Compile and test.
[Move method]
16. We can now begin to utilize polymorphism. Override getCharge() in RegularPrice. Use the logic from the switch, comment out thecase in the switch, then remove from the switch. Compile and test. Override getCharge() in ChildrensPrice. Use the logic from the switch, comment out the case in the switch, then remove from the switch. Compile and test. Override getCharge() in NewReleasePrice. Use the logic from the switch, comment out the case in the switch, then remove from the switch. Compile and test. We no longer call getCharge() in Price, make it abstract.Compile and test. We will keep getFrequentRenterPoints() together with getCharge() and move it to
17.
Price also. Move getFrequentRenterPoints() to Price. Compile and test. [Move method]
18. Only new releases treat frequent renter points differently. Override getFrequentRenterPoints() in NewReleasePrice. (Copy the function, test, simplify each, test.) Compile and test.
19. Done.

And here is a sample answer for one of the questions (not one that was submitted by a student):

Requirements:
Priority A:
-It should follow with a makefile that compiles the program with the-std = C99-Wall-Werror.
-Program will take the name of a. Tga file as a parameter.
-The application must store an 8bit uncompressed black and white version. It should not overwrite the original image.
-The algorithm that converts to black and white must use all color channels.
-The algorithm that converts to black and white is elective, but must be named and documented.
-The program must handle 24bit RGB uncompressed tga.
-The program must operate independently of the size of the image.

Priority B:
-The program shall evaluate whether this file is of a type that it handles.
-Does not handle application file shall terminate with an error message about why it did not work.
-The program must handle 16bit RGB uncompressed tga.
-The program must handle 32bit uncompressed RGBA tga.
-The program must print the contents of the Image Identification field.
-The program must handle an Image Identification field regardless of length.
-This field must be copied to the new image.
-The program must accept command line parameters that allow to flip the image horizontally and vertically.
-Flipping is implemented by changing the header, not the actual image data.
-The program must cope with a footer and print the same for the new image.
-Makefile must support “clean” and “remake” with standard functionality.

Priority C:
-The program must cope with color mapped TGA files.
-The program must handle compressed TGA files.

//tga.cpp
//Load and Save tga files

#include <stddef.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <malloc.h>
#include “tga.h”

enum TGACompressionType
{
NO_IMAGE = 0,
UNCOMPRESSED_COLOR_MAPPED = 1,
UNCOMPRESSED_TRUE_COLOR = 2,
UNCOMPRESSED_BLACK_AND_WHITE = 3, //Or GreyScale
RLE_COLOR_MAPPED = 9,
RLE_TRUE_COLOR = 10,
RLE_BLACK_AND_WHITE = 11,
};

enum TGAAttributesType
{
NO_ALPHA = 0, //Bits 3-0 of image descriptor should be 0 as well
UNDEFINED_IGNORE = 1, //Alpha data can be ignored
UNDEFINED_RETAIN = 2, //Alpha data should be retained
ALPHA_PRESENT = 3, //Alpha data is present
ALPHA_PREMULTIPLIED = 4, //Alpha channel is premultiplied
};

enum TGAReturn
{
OK = 0,
UNABLE_TO_LOAD = -1,
NOT_TGA = -2,
UNABLE_TO_SAVE = -3,
FILE_NOT_FOUND = -4,
OUT_OF_MEMORY = -5,
};

enum Flags
{
FLIP_X = 1,
FLIP_Y = 2,
};

#ifdef GCC
#define PACKED __attribute__((__packed__))
#else
#define PACKED
#pragma pack(1) //These structures should be laid out as written without alignment
#endif

struct TGAHeader_struct
{
u8 id_length; //Length of image id field
u8 color_map_type; //0 = None, 1 = Present, 2-127 = Reserved, 128-255 = User
u8 image_type; //TGACompressionType
u16 color_map_first_entry; //Which is the first value stored
//if you only used colors 128-255, you can just save those colors
u16 color_map_length; //Number of color map entries
u8 color_map_entry_size; //Number of bits per pixel
u16 xorigin; //Absolute coordinates of lower left
u16 yorigin; //Absolute coordinates of lower left
u16 image_width; //Width in pixels
u16 image_height; //Height in pixels
u8 pixel_depth; //Bits per pixel
u8 image_descriptor; //Bits 3-0 give the alpha channel depth, Bits 5-4 give direction
} PACKED;

typedef struct TGAHeader_struct TGAHeader;

struct TGADateTime_struct
{
u16 month; //1-12
u16 day; //1-31
u16 year; //4 digit year
u16 hour; //0-23
u16 minute; //0-59
u16 second; //0-59
} PACKED;

typedef struct TGADateTime_struct TGADateTime;

struct TGAExtension_struct
{
u16 extension_size; //Size of the extension area (495 bytes)
char author[41]; //Author name (0 terminated)
char comment[324]; //4 lines of 80 characters (0 terminated)
TGADateTime datetime; //12 bytes
char jobname[41]; //Description of job (0 terminated)
u16 hours; //Time spent working on image (for billing etc)
u16 minutes; //Time spent working on image (for billing etc)
u16 seconds; //Time spent working on image (for billing etc)
char software[41]; //Software the generated file (0 terminated)
u16 softwave_version; //Software version times 100, so 3.14 would be 314 (Set to 0 if not used)
char software_letter; //And version A (set to space if not used)
u8 color_key_a; //Transparent color
u8 color_key_r;
u8 color_key_g;
u8 color_key_b;
u16 pixel_ratio_numerator; //For example 4/3 16/9
u16 pixel_ratio_denominator; //If denominator is 0, then no ratio specified
u16 gamma_numerator; //Should be in the range 0.0-10.0
u16 gamma_denominator; //If denominator is 0, then no ratio specified
u32 color_correction_offset; //Number of bytes to the color correction data
u32 postage_stamp_offset; //Offset to the image thumbnail
u32 scanline_offset; //Offset to the scanlines
u8 attributes_type; //Specifies the alpha channel
} PACKED;

typedef struct TGAExtension_struct TGAExtension;

struct TGAFooter_struct
{
u32 extension_offset; //Offset to the TGAExtension
u32 developer_area_offset; //Offset to developer area
char signature[18]; //”TRUEVISION-XFILE.” (0 terminated)
} PACKED;

typedef struct TGAFooter_struct TGAFooter;

#ifdef GCC
#else
#pragma pack() //Restore default alignment
#endif

u8 (*RGBToGray)(int r,int g,int b); //Function pointer that remaps RGB to Gray
int (*writePixel)(u32 argb,u8 *dst); //Function pointer that writes a pixel

//http://www.johndcook.com/blog/2009/08/24/algorithms-convert-color-grayscale/

static u8 RGB2GrayLuminosity(int r,int g,int b)
{
// return g * .59 + r * .3 + g * .11; //The actual code, but we avoid floating point
int gray = ((g * 150) >> 8) + ((r * 153) >> 9) + ((g * 28) >> 8);
if (gray < 0) gray = 0;
if (gray > 255) gray = 255;
return (u8)gray;
}

static u8 RGB2GrayAverage(int r,int g,int b)
{
int gray = (r + g + b) / 3;
if (gray < 0) gray = 0;
if (gray > 255) gray = 255;
return (u8)gray;
}

static u8 RGB2GrayLightness(int r,int g,int b)
{
int min = r < g ? r : g;
int max = r > g ? r : g;
int gray;
min = min < b ? min : b;
max = max > b ? max : b;
gray = (max + min) / 2;
if (gray < 0) gray = 0;
if (gray > 255) gray = 255;
return (u8)gray;
}

//http://www.tannerhelland.com/3643/grayscale-image-algorithm-vb6/
static u8 RGB2GrayMin(int r,int g,int b)
{
int min = r < g ? r : g;
min = min < b ? min : b;
return (u8)min;
}

static u8 RGB2GrayMax(int r,int g,int b)
{
int max = r > g ? r : g;
max = max > b ? max : b;
return (u8)max;
}

static u8 RGB2GrayRed(int r,int g,int b)
{
return (u8)r;
}

static u8 RGB2GrayGreen(int r,int g,int b)
{
return (u8)g;
}

static u8 RGB2GrayBlue(int r,int g,int b)
{
return (u8)b;
}

static int WriteGreyPixel(u32 argb,u8 *dst)
{
u8 r,g,b;
b = (u8)(argb >> 24);
g = (u8)(argb >> 16);
r = (u8)(argb >> 8);
*dst = (*RGBToGray)(r,g,b);
return 1;
}

static int Write32BitPixel(u32 argb,u8 *dst)
{
u8 a,r,g,b;
a = (u8)(argb >> 24);
r = (u8)(argb >> 16);
g = (u8)(argb >> 8);
b = (u8)argb;
*dst++ = b;
*dst++ = g;
*dst++ = r;
*dst++ = a;
return 4;
}

//Read a short from an unaligned address in little endian format
static u16 TGAReadUShort(u16* val)
{
//This is inefficient (but it is safe on all architectures, including endian)
u8* mem = (u8*)val;
return mem[0] + (mem[1] << 8);
}

//Read an int from an unaligned address in little endian format
static u32 TGAReadUInt(u32* val)
{
//This is inefficient (but it is safe on all architectures, including endian)
u8* mem = (u8*)val;
return mem[0] + (mem[1] << 8) + (mem[2] << 16) + (mem[3] << 24);
}

//Write a short to an unaligned address in little endian format
static void TGAWriteUShort(u16 val,u16 *address)
{
//This is inefficient (but it is safe on all architectures, including endian)
u8* mem = (u8*)address;
mem[0] = (u8)val;
mem[1] = (u8)(val >> 8);
}

//Write an int to an unaligned address in little endian format
static void TGAWriteUInt(u32 val,u32 *address)
{
//This is inefficient (but it is safe on all architectures, including endian)
u8* mem = (u8*)address;
mem[0] = (u8)val;
mem[1] = (u8)(val >> 8);
mem[2] = (u8)(val >> 16);
mem[3] = (u8)(val >> 24);
}

//Convert value to grey (duplicate in RGB)
static u32 grey(int col,int alpha)
{
return col + (col << 8) + (col << 16) + (alpha << 24);
}

//Read a color value, with 15, 16, 24, or 32 bits per pixel
static u32 color(u8 *data,int bitsPerPixel,u8 alpha)
{
int rgba = TGAReadUInt((u32*)data); //only true for 32 bit, but the others can be extracted
//and this makes the code, endian independant
u8 r,g,b;

assert(bitsPerPixel == 15 || bitsPerPixel == 16 || bitsPerPixel == 24 || bitsPerPixel == 32);

switch (bitsPerPixel)
{
case 15:
case 16:
r = (u8)((rgba >> 10)<<3);
g = (u8)((rgba >> 5)<<3);
b = (u8)(rgba<<3);
break;
case 24:
r = (u8)(rgba >> 16);
g = (u8)(rgba >> 8);
b = (u8)rgba;
break;
case 32:
alpha = (u8)(rgba >> 24);
r = (u8)(rgba >> 16);
g = (u8)(rgba >> 8);
b = (u8)rgba;
break;
}

return (alpha << 24) + (r << 16) + (g << 8) + b;
}

//Write a value
void write(int val,u32 *image)
{
u8* bytes = (u8*)image;
bytes[0] = (u8)(val & 0xff);
bytes[1] = (u8)((val >> 8) & 0xff);
bytes[2] = (u8)((val >> 16) & 0xff);
bytes[3] = (u8)((val >> 24) & 0xff);
}

//Reads a TGA file from memory, and returns pointer to ARGB data
u32* TGARead(int *width,int *height,u8 *memory,int size,int *error)
{
TGAHeader* header;
u8* colorMap = NULL; //For paletted files
int bytesPerColor = 0; //How many bytes per pixel in color map table
u8* imageData; //The raw pixel data
u32* image; //The output ARGB buffer
u32* writeImage; //Used to write to the ARGB buffer
u8 alpha = 255; //Alpha value to put into ARGB buffer if none present in file
// u8 readAlpha; //How many bytes will we be reading from file
int rle; //Are we processing RLE file
u32 rleVal; //Last RLE value
int rleCount; //How many instances of RLE value left
int rleUnique; //How many unique values do we need to read
int colorMapped;
int greyScale;
int bitsPerPixel;

//Can’t be valid if too small, this check also stops accesses to memory that was not allocated
if (size < sizeof(TGAFooter))
{
*error = NOT_TGA;
return NULL;
}
header = (TGAHeader*)memory; //Provide easy access to the header

if (header->color_map_type > 1 ||
header->image_type > RLE_BLACK_AND_WHITE ||
header->pixel_depth > 32 ||
header->image_descriptor > 63) //Check for invalid values (no signature on TGA 1 files)
{
*error = NOT_TGA;
return NULL; //Doesn’t appear to be a TGA file
}

rle = header->image_type >= RLE_COLOR_MAPPED; //Compressed files are stored in RLE format
colorMapped = (header->image_type & 3) == UNCOMPRESSED_COLOR_MAPPED;
greyScale = (header->image_type & 3) == UNCOMPRESSED_BLACK_AND_WHITE;
// readAlpha = ((header->image_descriptor & 15) + 7) >> 3; //How many bytes of alpha are present

*width = TGAReadUShort(&header->image_width); //Stored as little endian
*height = TGAReadUShort(&header->image_height);

bitsPerPixel = header->pixel_depth; //Is this set, on true color images? Specs imply it isn’t but the information does not occur elsewhere

size = *width * *height; //Total number of pixels

if (size <= 0) //If width or height is 0 (or too large > 46000 pixels in x & y)
{
*error = NOT_TGA;
return NULL; //Not a TGA file
}

if (colorMapped) //If we have color
{
bytesPerColor = (header->color_map_entry_size + 7) >> 3;
colorMap = memory + sizeof(TGAHeader) + header->id_length; //colorMap starts here
imageData = colorMap + (TGAReadUShort(&header->color_map_length) * bytesPerColor); //And ends with image data
// imageData = colorMap + TGAReadUShort(&header->color_map_length); //And ends with image data
colorMap -= bytesPerColor * TGAReadUShort(&header->color_map_first_entry); //Colors below color_map_first_entry are invalid
bitsPerPixel = header->color_map_entry_size;
}
else
{
bytesPerColor = (bitsPerPixel + 7) >> 3; //1 byte for grayscale, 2 bytes for 15/16 bits, 3 bytes for 24 bits, 4 bytes for 32 bits
imageData = memory + sizeof(TGAHeader) + header->id_length; //Image data starts here
}

image = (u32*)malloc(size * 4); //4 bytes per pixel (ARGB)

if (!image)
{
*error = OUT_OF_MEMORY;
return NULL; //say the malloc files due to lack of memory
}

writeImage = image; //We will write ARGB here, but we need to return the start

rleCount = 0;
rleUnique = 0;
if (!rle) rleUnique = size; //Treat the entire image as rle unique

while (size) //If there are pixels left, keep processing
{
if (rleUnique) //If were are processing unique then we read data
{
size–;
rleUnique–;
if (colorMapped)
{
u8* colorTable = colorMap + *imageData++ * bytesPerColor;
// if (readAlpha) alpha = *imageData++;
rleVal = color(colorTable,bitsPerPixel,alpha);
}
else if (greyScale)
{
int greyVal = *imageData++;
// if (readAlpha) alpha = *imageData++;
rleVal = grey(greyVal,alpha);
}
else //RGB, or RGBA (16 bit, 24 bit, 32 bit)
{
rleVal = color(imageData,bitsPerPixel,alpha);
imageData += bytesPerColor;
}
write(rleVal,writeImage++);
}
else if (rleCount)
{
size–;
rleCount–;
write(rleVal,writeImage++);
}
else
{
if (*imageData >= 128)
{
rleCount = *imageData++ & 0x7f;
rleUnique = 1; //Just so we read the rleVal (we rleCount 1 less than actual)
}
else
{
rleUnique = *imageData++ + 1;
}
}
}

return image;
}

//Saves a TGA file in memory, colors gives the format (0 = Gray Scale)
//and returns pointer to TGA file, sets size to the size of the data
//Only colors = 0 is supported at the moment
//Returns NULL if unable to write the file
u8* TGAWrite(int width,int height,int *size,int colors,u8 *memory,u32 *data,int *error,int flags)
{
u8* newTGA;
TGAHeader* header;
TGAHeader* newHeader;
TGAFooter* footer;
TGAFooter* newFooter;
TGAExtension* extension = NULL; //Only present in TGA 2.0+ file
TGAExtension* newExtension;
u8* newImage;
int tga2;
int left;
int bytesPerPixel;

// colors = -1; //Force TRUE COLOR, useful for testing
assert(colors == 0 || colors == -1); //So we can add extra support later

header = (TGAHeader*)memory; //Provide easy access to the header
footer = (TGAFooter*)(memory+*size-sizeof(TGAFooter));

bytesPerPixel = (colors + 255) >> 8; //1,2,3 for Color Indexed, 16 bit, 24 bit
if (colors < 0) bytesPerPixel = 4; //Handle the case of 32 bit
if (!colors) bytesPerPixel = 1; //1 byte per pixel for Gray

*size = sizeof(TGAHeader) + sizeof(TGAFooter) + width * height * bytesPerPixel + header->id_length;

tga2 = !strcmp((const char*)footer->signature,”TRUEVISION-XFILE.”);
if (tga2)
{
int extension_offset = TGAReadUInt(&footer->extension_offset);
if (extension_offset)
{
extension = (TGAExtension*)(memory + extension_offset);
*size += TGAReadUShort(&extension->extension_size);
}
}

newTGA = (u8*)malloc(*size);
newHeader = (TGAHeader*)newTGA;
memcpy(newHeader,header,sizeof(TGAHeader) + header->id_length);
newHeader->color_map_entry_size = 0;
newHeader->color_map_first_entry = 0;
newHeader->color_map_length = 0;
newHeader->color_map_type = 0;

if (flags & FLIP_X)
{
newHeader->image_descriptor ^= 0x10;
}
if (flags & FLIP_Y)
{
newHeader->image_descriptor ^= 0x20;
}

switch (colors)
{
case 0:
newHeader->pixel_depth = 8;
newHeader->image_type = UNCOMPRESSED_BLACK_AND_WHITE;
writePixel = &WriteGreyPixel;
break;
case -1:
newHeader->pixel_depth = 32;
newHeader->image_type = UNCOMPRESSED_TRUE_COLOR;
writePixel = &Write32BitPixel;
break;
}
newFooter = (TGAFooter*)(newTGA + *size – sizeof(TGAFooter));
strcpy(newFooter->signature,”TRUEVISION-XFILE.”);
newFooter->developer_area_offset = 0;
newFooter->extension_offset = 0;
if (extension)
{
newExtension = (TGAExtension*)((u8*)newFooter – sizeof(TGAExtension));
memcpy(newExtension,extension,TGAReadUShort(&extension->extension_size));
newFooter->extension_offset = ((u8*)newExtension – newTGA);
}

newImage = newTGA + sizeof(TGAHeader) + header->id_length;

left = width * height;
while (left)
{
newImage += writePixel(*data++,newImage);
left–;
}

return newTGA;
}

u8* readFile(const char* src, int* size)
{
FILE *file;
u8 *buffer;
unsigned long fileLen;

//Open file
file = fopen(src, “rb”);
if (!file)
{
fprintf(stderr, “Unable to open file %s”, src);
return NULL;
}

//Get file length
fseek(file, 0, SEEK_END);
fileLen=ftell(file);
*size = (int)fileLen;
fseek(file, 0, SEEK_SET);

//Allocate memory
buffer=(u8*)malloc(fileLen+1);
if (!buffer)
{
fprintf(stderr, “Memory error!”);
fclose(file);
return NULL;
}

//Read file contents into buffer
fread(buffer, fileLen, 1, file);
fclose(file);

return buffer;
}

void writeFile(const char *dst, u8* memory, int size)
{
FILE *file;

//Open file
file = fopen(dst, “wb”);
if (!file)
{
fprintf(stderr, “Unable to open file %s”, dst);
return;
}

//Read file contents into buffer
fwrite(memory, size, 1, file);
fclose(file);
}

int convert(const char* src, const char* dst,int colors,int flags)
{
int width, height,size;
u8* memory;
u32* image = NULL;
u8* tga = NULL;
int returnCode = OK;

// memory = NULL; size = 0; //Set these from read file
memory = readFile(src, &size);

if (memory)
{
image = TGARead(&width,&height,memory,size,&returnCode);
if (image)
{
tga = TGAWrite(width,height,&size,colors,memory,image,&returnCode,flags);
if (tga)
{
writeFile(dst,tga,size);
}
else
{
returnCode = UNABLE_TO_SAVE;
}
}
}
else
{
returnCode = UNABLE_TO_LOAD; //File not found
}

free(memory);
free(tga);
free(image);

switch (returnCode)
{
case UNABLE_TO_LOAD:
printf(“Unable to load %s\n”,src);
break;
case NOT_TGA:
printf(“%s is not a TGA file\n”,src);
break;
case UNABLE_TO_SAVE:
printf(“Unable to save %s\n”,dst);
break;
case FILE_NOT_FOUND:
printf(“File %s not found\n”,src);
break;
case OUT_OF_MEMORY:
printf(“Not enough memory\n”,src);
break;
}
return returnCode;
}

void help()
{
printf(“Welcome to TGA convert.\n”);
printf(“Syntax: tga [option] source destination\n”);
printf(“Options:”);
printf(“-h,-?: These instructions:\n”);
printf(“-32: Save as 32 bit color\n”);
printf(“-L: Use luminosity (default) to convert to gray\n”);
printf(“-a: Use avergage of r,g,b to convert to gray\n”);
printf(“-l: Use lightness of r,g,b to convert to gray\n”);
printf(“-m: Use minimum of r,g,b to convert to gray\n”);
printf(“-M: Use maximum of r,g,b to convert to gray\n”);
printf(“-r: Use red component to convert to gray\n”);
printf(“-g: Use green component to convert to gray\n”);
printf(“-b: Use blue component to convert to gray\n”);
printf(“-x: Flip the image in X\n”);
printf(“-y: Flip the image in Y\n”);
}

int main(int argc, const char* argv[])
{
int colors = 0;
int src = 1;
int dst = 2;
int flags = 0;
RGBToGray = RGB2GrayLuminosity;
//If we have command line parameter
if (argc > 1)
{
if (argv[1][0] == ‘-‘)
{
src++;
dst++;
switch (argv[1][1])
{
case ‘?’:
case ‘h’:
help();
return 0;
case ‘3’:
colors = -1;
break;
case ‘a’:
RGBToGray = RGB2GrayAverage;
break;
case ‘l’:
RGBToGray = RGB2GrayLightness;
break;
case ‘m’:
RGBToGray = RGB2GrayMin;
break;
case ‘M’:
RGBToGray = RGB2GrayMax;
break;
case ‘r’:
RGBToGray = RGB2GrayRed;
break;
case ‘g’:
RGBToGray = RGB2GrayGreen;
break;
case ‘b’:
RGBToGray = RGB2GrayBlue;
break;
case ‘x’:
flags |= FLIP_X;
break;
case ‘y’:
flags |= FLIP_Y;
break;
}
}
}
else
{
help();
return 0;
}

if (argc > dst)
{
convert(argv[src],argv[dst],colors,flags);
return 0;
}

convert(“samples\\CBW8.TGA”,”out\\CBW8.TGA”,colors,flags);
convert(“samples\\CCM8.TGA”,”out\\CCM8.TGA”,colors,flags);
convert(“samples\\CTC16.TGA”,”out\\CTC16.TGA”,colors,flags);
convert(“samples\\CTC24.TGA”,”out\\CTC24.TGA”,colors,flags);
convert(“samples\\CTC32.TGA”,”out\\CTC32.TGA”,colors,flags);
convert(“samples\\earth.tga”,”out\\earth.tga”,colors,flags);
convert(“samples\\earth_UTP32.tga”,”out\\earth_UTP32.tga”,colors,flags);
convert(“samples\\FLAG_B16.TGA”,”out\\FLAG_B16.TGA”,colors,flags);
convert(“samples\\FLAG_B24.TGA”,”out\\FLAG_B24.TGA”,colors,flags);
convert(“samples\\FLAG_B32.TGA”,”out\\FLAG_B32.TGA”,colors,flags);
convert(“samples\\FLAG_T16.TGA”,”out\\FLAG_T16.TGA”,colors,flags);
convert(“samples\\FLAG_T32.TGA”,”out\\FLAG_T32.TGA”,colors,flags);
convert(“samples\\MARBLES.TGA”,”out\\MARBLES.TGA”,colors,flags);
convert(“samples\\shuttle.tga”,”out\\shuttle.tga”,colors,flags);
convert(“samples\\UBW8.TGA”,”out\\UBW8.TGA”,colors,flags);
convert(“samples\\UBW8_002.TGA”,”out\\UBW8_002.TGA”,colors,flags);
convert(“samples\\UCM8.TGA”,”out\\UCM8.TGA”,colors,flags);
convert(“samples\\UTC16.TGA”,”out\\UTC16.TGA”,colors,flags);
convert(“samples\\UTC24.TGA”,”out\\UTC24.TGA”,colors,flags);
convert(“samples\\UTC32.TGA”,”out\\UTC32.TGA”,colors,flags);
convert(“samples\\XING_B16.TGA”,”out\\XING_B16.TGA”,colors,flags);
convert(“samples\\XING_B24.TGA”,”out\\XING_B24.TGA”,colors,flags);
convert(“samples\\XING_B32.TGA”,”out\\XING_B32.TGA”,colors,flags);
convert(“samples\\XING_B_UCM8.tga”,”out\\XING_B_UCM8.tga”,colors,flags);
convert(“samples\\XING_T16.TGA”,”out\\XING_T16.TGA”,colors,flags);
convert(“samples\\XING_T24.TGA”,”out\\XING_T24.TGA”,colors,flags);
convert(“samples\\XING_T32.TGA”,”out\\XING_T32.TGA”,colors,flags);
convert(“samples\\XING_T_UCM8.tga”,”out\\XING_T_UCM8.tga”,colors,flags);

convert(“tga8\\25_color.tga”,”out\\tga8\\25_color.tga”,colors,flags);
convert(“tga8\\155_5572_jpg.tga”,”out\\tga8\\155_5572_jpg.tga”,colors,flags);
convert(“tga8\\34445.tga”,”out\\tga8\\34445.tga”,colors,flags);
convert(“tga8\\arctichare.tga”,”out\\tga8\\arctichare.tga”,colors,flags);
convert(“tga8\\balls0_color.tga”,”out\\tga8\\balls0_color.tga”,colors,flags);
convert(“tga8\\butterfly.tga”,”out\\tga8\\butterfly.tga”,colors,flags);
convert(“tga8\\C8TZ7768.tga”,”out\\tga8\\C8TZ7768.tga”,colors,flags);
convert(“tga8\\ColorsPastel.tga”,”out\\tga8\\ColorsPastel.tga”,colors,flags);
convert(“tga8\\ColorWheelEqLum200.tga”,”out\\tga8\\ColorWheelEqLum200.tga”,colors,flags);
convert(“tga8\\DSCN9952.tga”,”out\\tga8\\DSCN9952.tga”,colors,flags);
convert(“tga8\\fruits.tga”,”out\\tga8\\fruits.tga”,colors,flags);
convert(“tga8\\girl.tga”,”out\\tga8\\girl.tga”,colors,flags);
convert(“tga8\\IM2-color.tga”,”out\\tga8\\IM2-color.tga”,colors,flags);
convert(“tga8\\impatient_color.tga”,”out\\tga8\\impatient_color.tga”,colors,flags);
convert(“tga8\\kodim03.tga”,”out\\tga8\\kodim03.tga”,colors,flags);
convert(“tga8\\monarch.tga”,”out\\tga8\\monarch.tga”,colors,flags);
convert(“tga8\\portrait_4v.tga”,”out\\tga8\\portrait_4v.tga”,colors,flags);
convert(“tga8\\ramp.tga”,”out\\tga8\\ramp.tga”,colors,flags);
convert(“tga8\\serrano.tga”,”out\\tga8\\serrano.tga”,colors,flags);
convert(“tga8\\Ski_TC8-03_sRGB.tga”,”out\\tga8\\Ski_TC8-03_sRGB.tga”,colors,flags);
convert(“tga8\\Sunrise312.tga”,”out\\tga8\\Sunrise312.tga”,colors,flags);
convert(“tga8\\text.tga”,”out\\tga8\\text.tga”,colors,flags);
convert(“tga8\\tree_color.tga”,”out\\tga8\\tree_color.tga”,colors,flags);
convert(“tga8\\tulips.tga”,”out\\tga8\\tulips.tga”,colors,flags);
convert(“tga8\\watch.tga”,”out\\tga8\\watch.tga”,colors,flags);

convert(“tga24\\25_color.tga”,”out\\tga24\\25_color.tga”,colors,flags);
convert(“tga24\\155_5572_jpg.tga”,”out\\tga24\\155_5572_jpg.tga”,colors,flags);
convert(“tga24\\34445.tga”,”out\\tga24\\34445.tga”,colors,flags);
convert(“tga24\\arctichare.tga”,”out\\tga24\\arctichare.tga”,colors,flags);
convert(“tga24\\balls0_color.tga”,”out\\tga24\\balls0_color.tga”,colors,flags);
convert(“tga24\\butterfly.tga”,”out\\tga24\\butterfly.tga”,colors,flags);
convert(“tga24\\C8TZ7768.tga”,”out\\tga24\\C8TZ7768.tga”,colors,flags);
convert(“tga24\\ColorsPastel.tga”,”out\\tga24\\ColorsPastel.tga”,colors,flags);
convert(“tga24\\ColorWheelEqLum200.tga”,”out\\tga24\\ColorWheelEqLum200.tga”,colors,flags);
convert(“tga24\\DSCN9952.tga”,”out\\tga24\\DSCN9952.tga”,colors,flags);
convert(“tga24\\fruits.tga”,”out\\tga24\\fruits.tga”,colors,flags);
convert(“tga24\\girl.tga”,”out\\tga24\\girl.tga”,colors,flags);
convert(“tga24\\IM2-color.tga”,”out\\tga24\\IM2-color.tga”,colors,flags);
convert(“tga24\\impatient_color.tga”,”out\\tga24\\impatient_color.tga”,colors,flags);
convert(“tga24\\kodim03.tga”,”out\\tga24\\kodim03.tga”,colors,flags);
convert(“tga24\\monarch.tga”,”out\\tga24\\monarch.tga”,colors,flags);
convert(“tga24\\portrait_4v.tga”,”out\\tga24\\portrait_4v.tga”,colors,flags);
convert(“tga24\\ramp.tga”,”out\\tga24\\ramp.tga”,colors,flags);
convert(“tga24\\serrano.tga”,”out\\tga24\\serrano.tga”,colors,flags);
convert(“tga24\\Ski_TC8-03_sRGB.tga”,”out\\tga24\\Ski_TC8-03_sRGB.tga”,colors,flags);
convert(“tga24\\Sunrise312.tga”,”out\\tga24\\Sunrise312.tga”,colors,flags);
convert(“tga24\\text.tga”,”out\\tga24\\text.tga”,colors,flags);
convert(“tga24\\tree_color.tga”,”out\\tga24\\tree_color.tga”,colors,flags);
convert(“tga24\\tulips.tga”,”out\\tga24\\tulips.tga”,colors,flags);
convert(“tga24\\watch.tga”,”out\\tga24\\watch.tga”,colors,flags);

return 0;
}

//tga.h
//Load and Save tga files

#ifndef TGA_H
#define TGA_H

typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned int u32;
typedef short s16;
typedef int s32;

//Read a short from an unaligned address in little endian format
u16 TGAReadUShort(u16* val);
//Read an int from an unaligned address in little endian format
u32 TGAReadUInt(u32* val);
//Write a short to an unaligned address in little endian format
void TGAWriteUShort(u16 val,u16 *address);
//Write an int to an unaligned address in little endian format
void TGAWriteUInt(u32 val,u32 *address);
//Reads a TGA file from memory, and returns pointer to ARGB data
//Returns NULL if not a valid TGA file
u32* TGARead(int *width,int *height,u8 *memory,int size,int *error);
//Saves a TGA file in memory, colors gives the format (0 = Gray Scale)
//and returns pointer to TGA file, sets size to the size of the data
u8* TGAWrite(int width,int height,int *size,int colors,u8 *memory,u32 *data,int *error);

#endif //TGA_H