Friday, 12 October 2018

Worldbuilding - part 01

World building is somehow simultaneously the best thing and the worst thing about writing a fantasy, in my experience. I've spent a good few years developing the world where my novels are set (It's a shared universe where I have based two series to this date). It's fun, but it's also vexing, trying to keep all the various details in your head.
In this post, I will point out a few things you might need to consider when trying to build a world from scratch. Here, the main focus on getting the geography and locations down, and I will talk about the rest of the process in a later article.

1. Names!

If you're creating a world (or, let's be realistic, a country and its nearest neighbours), you need to refer to that country in some way. There are a few ways to go about this. 
  1. Postpone the problem until you're older and hopefully wiser (guilty!), and use a placeholder in its place. While this may speed up the writing process, it also means you're dropping a crucial detail, and you may lose some nuance it could have added to the story. 
  2. Option two is to look for inspiration in foreign languages. This tends to work better if you pick a language that is not too close to the language you're working with. A less widely understood language probably works better than one that everybody knows. Google translate is very useful for this. However, there is one major drawback to this - words tend to have multiple meanings, or mean something else in the particular language's slang. So, tread carefully.
  3. The third alternative is to create the name you want from scratch. You could either create a language from scratch first, or use the phonology of the language that your characters use to come up with a word that sounds plausible enough. If you create the language first, you could use words from that language to come up with a name, but it's not strictly necessary - not all countries have names that make sense, immediately, in their own language.
One more thing - you might be tempted to worry about whether the name of the place means something else in a another language. Don't worry - there are so many words that mean one thing in one language and something completely different in another. If it didn't, we'd all be speaking versions of the same language.

2. More names

You will also need to figure out what the people call themselves, and whether they have a different name for their ethnic group and for the nationality. Also, you might need to come up with a name for the continent if your country is in a continent, but that probably won't be necessary in every case.

3. Geography

What is your setting?Is it a country attached to a larger continent? Is it an island? Is it a planet city? Or is it underwater/in orbit? Or is your focus just on one city? Or is it something else entirely?
Ideally, you would have some idea about what sort of setting it is when you get to this stage (unless you're designing a world because you think it's fun - in which case, carry on). 
Once you've picked the type of location, you probably need to decide how big it is. As in, in square kilometres (or miles, centimetres, parsecs, whatever you like). This is important, because you have to know how long it will take to traverse the area in question, for example. The size also determines the number of different climates you can squeeze in there. It also determines the size of the rivers and streams, and possibly of mountains (unless it's a volcanic island). 
Then you need the approximate shape of the area. I would recommend reading some basic geography if you want to keep things realistic. Of course your world doesn't have to play by the rules of reality - if there are forces there that can make a landmass a completely illogical shape, go right ahead.
At this stage, you will have a blank map with the outline of the the area in question. Now, it's time to fill it it.

4. Climate

What is the climate like in there? Are there a lot of micro-climates? What is the average temperature? How much precipitation do they get? What other factors would you expect to influence the climate?

5. More geography

Now, we have to fill in the important features. You can have mountains, lakes and other bodies of water, rivers, plains, marshes and bogs, etc.
I prefer to fill in the approximate elevations first (it's more practical in my case - the country is over 3 million square kilometres) instead of marking individual mountain ranges. The mountains are a good starting point, because they influence climates a lot, and most of the other features I mentioned tend to be dependent on them.
Once you've decided where the mountains are, you can start putting the rivers in. There are specific ways in which rivers work, though, and you might need to be careful about them (unless someone or something is pumping it, a river cannot flow uphill). They can start on flat land on occasion. They can just disappear into a desert (there are a few cases like that). In most cases, however, they tend to start from a mountainous area as a bunch of streams and flow into another stream or the sea, a lake, or other such source of water.
Then there are other features, like lakes. They could be formed by rivers emptying into it. they could be artificial, or they could be caused by springs at the location. They could be poisonous or have pitch in them (depends on volcanic activity). You can also add a few significant waterfalls along the rivers. 
Marshes could be directly connected to the sea, but they don't have to be. you can have a river draining into one if you want to (provided it's not too big). 
Now you can fill in the type of forests and grasslands as appropriate. You also have to determine which areas are occupied, and therefore changed by the inhabitants of the place in question.
All this, of course, refers to a place that is firmly on dry land. If your setting is underwater, for example, you might have to look into different features to liven it up.

6. Settlements

First of all, do they have settlements? If so, what sort of settlements are they? Are they medieval style cities? Or modern cities? Or are they small villages scattered far and wide?
How are these settlements connected? Is there a road network? Or are there alternative means of transport (rail, for example)?
Is there a command center, so to speak, politically or in a military sense? Where is it located? You would want to place it in a place that can be defended, but within a reasonable distance from the places that are being commanded from there.

7. Even more names!

You are going to have to name all the places you just created - the mountain ranges, lakes, rivers, cities/villages, etc. Here, you could use the same approach as you did when naming the country. Alternatively, you could also use words from English or the language you're working in to create an understandable place name (the shire from the lord of the rings comes to mind).

This is not the end of the list by any means. I am planning to cover the rest in a series of articles, but for now, I must say farewell. Please tell me what you think in the comments.
You can also follow me on facebook here.
Until next time!

Friday, 5 October 2018

How not to write a character death

Once upon a time, one of my characters died. Then me, the rest of the cast, and everyone else promptly forgot about him.
Let's back up a bit, and start from the beginning. I was writing the first draft of the novel I am working on at the moment. The character - let's call him Jack for now - was one of the main characters' inner circle. He died heroically, trying to hold off the enemy in the midst of a chaotic battle.
One would logically expect that the death of Jack would have an effect on the story. There would be grief, maybe anger, maybe feelings of guilt, inadequacy, etc. from his friends if not anyone else.
That didn't happen. Before I knew it, I had moved on with the next three or four chapters. I felt nothing, and neither did the rest of the cast. Why did this happen?
There are several reasons that I have identified since, and I will list them here one by one.

  1. Lack of relationships: Jack is a secondary level character. He had friends, yes, but the closest meaningful relationship he had with a viewpoint character was as a friend of a friend.
  2. His personality (or lack thereof): I designed his character, of course. I knew his name and what he looked like. Beyond that, I didn't pay much attention to him - I thought he would grow, organically, and be the character he was meant to be. That didn't happen, because...
  3. Invisibility: Jack simply wasn't saying anything, or doing anything - he was just there in the background. He was simply a prop. He rarely had to say anything, because he was in the presence of characters with more developed personalities, and I knew exactly how they would respond to a situation. So, he faded into oblivion long before he actually died, provided that a reader would have noticed his existence in the first place.

Now you are probably wondering why I bothered to kill off such a peripheral character. The answer is, I had too many characters in hand and I needed to reduce their number. On top of that I needed a character death at that point, since the main cast had been operating in a situation with a high mortality rate with no casualties. So, who was better suited to the situation than poor Jack? He wouldn't be a loss to the team.
That was the problem. You see, the team lost absolutely nothing by his death. There was only one character who would have lost something, but he was in a lot of problems of his own, and though he ought to have reacted to this a bit more, well, he didn't. I forgot all about it.
So, the moral of the story - develop your characters before you kill them if you want an emotional reaction (as in, in advance, not half a chapter ahead before their death). Mooks and random characters that die do not need this Also, don't randomly pick and character and kill them off just because you're feeling mean (I did this on a spectacular scale before. I might right about it later).
I hope this is a useful guide in how not to kill a character, and I hope you would avoid making the same mistakes that I made.
If you're wondering what has happened to Jack since, he's doing fine in the current version of the novel. He has a backstory now, and a personality, and most of the main cast are really his friends. I haven't reached the point where he died yet, but I doubt I'd thrust him in the line of fire so easily again. There is one thing I know, though - if he dies now, I'll definitely feel it, and so will the rest of the cast.
Until next time!

Friday, 28 September 2018

Vigenere Cipher - code - C++

This is a follow up to my article on the Vigenere Cipher. Here, I have given the c++ code for encrypting / decrypting a text file using the Vigenere Cipher. The user has to select whether to ecrypt or decrypt, and they must enter the key. The whole text is then encrypted or decrypted using the key repeated until the length of the text is reached.

I hope the comments explain things sufficiently in the code, but I will provide an additional explanation after the code. The code is given below:

/* 
 * File:   main.cpp
 * Author: 88615XC
 *
 * Created on September 28, 2018, 3:34 PM
 */

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <cstring>

#define CODE_ARR_SIZE 63                //Size of the code array

std::string line;                       //For reading data from file
std::string outLine;                    //For coded data
std::string inCmd;                      //For reading data input from console
std::string key;                        //To store the key
int key_marker = 0;                     //marks current position along the key
char cipher[CODE_ARR_SIZE]={'0','1','2','3','4','5','6','7','8','9','A','a',
'B','b','C','c','D','d','E','e','F','f','G','g','H','h','I','i','J','j','K','k',
'L','l','M','m','N','n','O','o','P','p','Q','q','R','r','S','s','T','t','U','u',
'V','v','W','w','X','x','Y','y','Z','z',' '};


using namespace std;

/*
 * Returns the array index corresponding to the character
 */
int getNumber(char char1){
    for (int i = 0; i<CODE_ARR_SIZE; i++){
        if (char1==cipher[i]){
            return i;
        }
    }
    return -1;
}
/*
 * Returns the array index corresponding to the character
 */
char getChar(int num){
    if ((num>=0)&&(num<CODE_ARR_SIZE)){
        return cipher[num];
    }
    return '|';
}
/*
 * codes a line from the input line with given key.
 */
void encryptLine(void){
    int tmp1, tmp2;                     //Temporary variables
    char tmp3;
    outLine.clear();                    //Clear output string
    //Loop through the line one character at a time
    for (int i = 0; i<line.length(); i++){
        tmp1 = getNumber(line[i]);        //get numerical equivalent
        if (tmp1 != -1){                //If character is in code array
            //Get numerical equivalent for key. No validity checking needed,
            //As non-alphanumeric characters are already removed.
            tmp2 = getNumber(key[key_marker]);
            key_marker++;                //Update key marker
            //If key marker overflows, set it back to 0
            if (key_marker >= key.length()) key_marker=0;
            tmp1 = tmp1 + tmp2;         //Add the two values
            tmp1 = tmp1%CODE_ARR_SIZE;  //Get modulus
            tmp3 = getChar(tmp1);       //Get corresponding character
            outLine.push_back(tmp3);    //Add to output string
        }
        else{
            //If character is not in code array (periods, commas, etc.) they 
            //will be added to the output string as it is. If neccassary to 
            //remove them, can be done like with the key in main.
            outLine.push_back(line[i]);
        }
    }
}
/*
 * decodes the input line using the given key
 */
void decryptLine(void){
    int tmp1, tmp2;                     //Temporary variables
    char tmp3;
    outLine.clear();                    //Clear output line
    for (int i = 0; i<line.length(); i++){
        tmp1 = getNumber(line[i]);        //get numerical equivalent
        if (tmp1 != -1){                //If character is in code array
            //Get numerical equivalent for key. No validity checking needed,
            //As non-alphanumeric characters are already removed.
            tmp2 = getNumber(key[key_marker]);
            key_marker++;               //Update key marker
            //If key marker overflows, set it back to 0
            if (key_marker >= key.length()) key_marker=0;
            tmp1 = tmp1 - tmp2;         //Subtract key value from character
            tmp1 = tmp1%CODE_ARR_SIZE;  //Get modulus
            //If the value is negative, add CODE_ARR_SIZE to it
            if (tmp1<0) tmp1=tmp1+CODE_ARR_SIZE;
            tmp3 = getChar(tmp1);       //Get corresponding character 
            outLine.push_back(tmp3);    //Add to output string
        }
        else{
            //If character is not in code array (periods, commas, etc.) they 
            //will be added to the output string as it is. If neccassary to 
            //remove them, can be done like with the key in main.
            outLine.push_back(line[i]);
        }
    }
}
/*
 * 
 */
int main(int argc, char** argv) {
    ifstream input1;
    ofstream output1;
    
    //Open the input and output files
    input1.open("input1.txt",ios::in);
    output1.open("output1.txt",ios::out);
    
    //The user chooses whether the input file is coded or decoded.
    cout<<"Enter E to encrypt, D to decrypt, Q to quit:"<<endl;
    cin>>inCmd;
    //If a quit command is received, the program exits.
    if ((inCmd[0]=='Q')||(inCmd[0]=='q')){
        cout<<"Quit command received"<<endl;
        return EXIT_SUCCESS;
    }
    else if ((inCmd[0]=='E')||(inCmd[0]=='e')){
        cout<<"encrypt mode"<<endl;
    }
    else if ((inCmd[0]=='D')||(inCmd[0]=='d')){
        cout<<"decrypt mode"<<endl;
    }
    //If the command is not valid, the program exits.
    else{
        cout<<"Command not understood"<<endl;
        return EXIT_FAILURE;
    }
    
    //The user enters the key. No spaces allowed. characters that are not in the
    //specified range will be ignored.
    cout<<"Enter Key. Characters 0-9, A-Z, a-z:"<<endl;
    cin>>key;
    if (key.length()==0){               //Impossible but just in case
        cout<<"key length 0. Exiting."<<endl;
        return EXIT_FAILURE;
    }
    else{
        //Check every character to see whether it is alphanumeric. If any 
        //non-alphanumeric characters are detected, remove them.
        int j = 0;
        for (int i = 0; i<key.length(); i++){
            if (isalnum(key[i])){ 
                j++;
            }
            else{
                for (int k=i+1;k<key.length();k++){
                    key[k-1] = key[k];
                }
                key.erase(key.length()-1);
                i--;
            }
        }
        if (j==0){                  
            //If no alphanumeric characters are detected, key is invalid.
            cout<<"key not alphanumeric. Exiting."<<endl;
            return EXIT_FAILURE;
        }
        else{
            cout<<"Key :"<<key<<", Key length :"<<key.length()<<endl;
        }
    }
    
    while (!(input1.eof())){            //Loop until end of input file
        getline(input1,line);           //Read a line from input file
        if ((inCmd[0]=='E')||(inCmd[0]=='e')){
            encryptLine();                 //If code mode, encode input file
        }
        else if ((inCmd[0]=='D')||(inCmd[0]=='d')){
            decryptLine();               //If decode mode, decode input file
        }
        output1<<outLine<<endl;         //Write result to output file
    }
    
    input1.close();
    output1.close();

    return 0;
}

Results:
For the input file, the following text was pasted into input1.txt:

This is a test.
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
01234567891011121314151617181920

The purpose was to test the entire range of possible characters. The console output on running this file through it on encrypt mode:

Enter E to encrypt, D to decrypt, Q to quit:
encrypt mode
Enter Key. Characters 0-9, A-Z, a-z:
Key :Testing, Key length :7


Please note that my IDE does not show the characters that I enter.

The key used in this case is 'Testing'. If I enter something like '..T.e.s.t..ing.', the periods would be removed, and the key would still be 'Testing'. The encrypted result is in output1.txt is:

lRalI17sKSmSf9.
Ykz2rxr9rBDy8ygyIKAGAnAPRH
TN0N37U UCUdf1b1J1kmcicQcr
tJoIVHvXmSHTFTUjOItgTWJqHwFwUNog

To decode this, rename the file input1.txt, and put it through the program in decode mode using the same key. Console output:

Enter E to encrypt, D to decrypt, Q to quit:
decrypt mode
Enter Key. Characters 0-9, A-Z, a-z:
Key :Testing, Key length :7


The decrypted result is:

Enter E to encrypt, D to decrypt, Q to quit:
decrypt mode
Enter Key. Characters 0-9, A-Z, a-z:
Key :Testing, Key length :7

So, for further explanation -

  • includes: iostream is needed for console input and output. fstream is needed for reading from and writing to files. cstring is needed for all the string operations used in the program.
  • The code array size is defined as a constant because it's needed to initialize the cipher array. You can change it if you want to expand or reduce the cipher array (and include punctuation marks or other symbols, if you want to).
  • variables: line is for reading the input data, and outLine for storing the ecrypted or decrypted data. key is the key. inCmd could be a character if necessary, but I went with a string here. key_marker is used to track which character of the key is used at the moment. It does not reset when a line is done, so if a line ends in the middle of the key character, it wraps around and continues where it left off. The cipher array includes all characters that will be included in the cipher - here it lists the numbers 0-9, all letters, both uppercase and lowercase, and the space character,
  • getNumber and getChar are both used to scan the cipher array. getNumber checks whether the char is in the array, and returns the array index if it is and -1 if it isn't. getChar reverses the process and returns '|' if the number doesn't correspond to an array index.
  • encryptLine and decryptLine encrypt/decrypt a line at a time. They go through one character at a time. encryptLine adds the key, and decryptLine subtracts it. Both use the modulus function to put the value back in the 0-CODE-ARR_SIZE range. The decrypt function also needs to correct for possible negative numbers. The result is then appended to outLine. This is repeated for every character in the line.
  • The main program defines the input and output files, and then opens them. Then the user is prompted to select whether to run the encryption program or the decryption program. If the user selected encryption or decryption, then they are prompted to enter the key. If the key contains at least one alphanumeric character, it will be used. However, using a single character is not recommended, because then it will be the same as a Caesar cipher, and will be relatively easy to crack.
  • Once the key is obtained, the program will then read the input file one line at a time, and put it through the encryption or decryption program (as the user selected before), and write the result to the output file.
I hope this helps. See you next time!






Monday, 17 September 2018

Dates and times

aka Calculating time for a novel


A story needs a timeline, especially if your characters are students/are working, and if the story covers a significant length of time (more than two weeks, at least given my writing style). You need to track the passage of time, you need to know what day of the week it is, and you have to track when the holidays are. It's a rather difficult problem if you actually count the days one by one.
This is one of the problems that I really enjoyed solving while writing. First, I love maths. Secondly, the maths is not complicated - you can always use a spreadsheet or something to do the calculations for you unless you are a masochist (if you are, go ahead and do it manually, but consider yourself warned).
So, first things first - you need a reference date. You need to know the date and the day of the week on that day, and if you're tracking the sun/moon/etc to track festivals (as I am doing), you will need to set these down as well. Basically, you have to start at an arbitrary point.
First up, the length of the year. My current biggest project does not take place on earth, so I had a little flexibility with this, so I went with approximately 372.058 days. If you're based on earth, the length of the year will be 365.25 days. Next up, you have to decide the nominal length of a year. I would recommend rounding it down to the nearest integer - for example, I went with 372 days. Again, if you're based on earth, that's 365 days.
From this, you can calculate the frequency of leap years. For earth, that will be every four years. Yes, that means that the calendar gradually gets out of sync with our actual position relative to the sun until it's effectively reset every leap year on February 29th. To calculate the frequency,it's 1 divided by the difference between the length of the actual year and the nominal year.
For example, for earth: 1 ÷ (365.25-365) = 1 ÷ 0.25 = 4.
For a planet with a 234.345 day long year, it will be 1 ÷ (234.345-234) = 1 ÷ 0.345 = 2.89855.
This translates to a leap year every 3 years (round it up to the nearest integer), but that will not get rid of the offset in this case. To deal with this, you simply have to repeat the process until the remainder is small enough / time periods involved are too long for it to matter. To continue with the previous example, that would give:
÷ (234.345 - (234 + (1/3)) = 85.71429 -> another leap year every 86 years. Note that these two cycles will be independent of each other, so in the years that are a multiple of both 3 and 86 from the first leap year (every 258 years), there will be a double leap year - i.e., you have to add two days to the calendar on those days.
Continuing with this process, we get 1 ÷ (234.345 - (234 + (1/3) + (1/86)) = 25800. At this point, we can safely ignore the rest of the remainder, unless your story spans millions of years.
Isn't the earth pretty neat?
Continuing on, after deciding how long the years will be, you have to decide how the year is divided. How many months are there? How long are the months? Do you have a wacky calendar like the Gregorian calendar? (Seriously, I don't care about the ego of Roman emperors, but have a 28 day month smack in the middle of the year while many other months have 31 days is simply insane. Also, there is simply no rhyme or reason as to how the number of days in a month are decided. It used to drive me insane as a child, and it still does).
Other things you have to decide before proceeding include the resolution of your calendar (seconds, or even shorter? It may be important if you're going to include festivals based on celestial events. Otherwise, days will work quite well), and the number of days in a week if you're going with the year-month-week-day system we use. If not, you can make anything up. If you're based on the earth, you can simply use the existing calendar.
That being done, you have to come up with a program, essentially, to output the day of the week once you input the date. This can be quite complicated, but the calculation can be used if you're going to include the movement of celestial objects, so bear with me.
The most important step, and the first thing you need to do, is to calculate the time elapsed since the reference date. I will use the earth for calculations, because it is both insanely complicated (thanks to humans, the universe made the starting point a lot easier) and familiar to everyone, so there is less information to absorb.
Say the reference point is the first of January, 2010. My computer says it's a Friday. So, armed with that information, we can proceed. Say we want to figure out what day it is on the 17th of September, 2018. We will use days for calculation. So, here are the steps:
Elapsed years = (2018-2010) - 1 = 7 (remember, 2018 is not over yet).
No of leap years = ((2018-2010) - 1)/4 + 1 = 2.75 = 2 (round it down. 1 is added because the starting year is a leap year. I would recommend starting with a leap year, otherwise this calculation will get complicated.)
No of days elapsed in the past years = 7*365 + 1 = 2557.
Elapsed months: January to August (The current month, September, isn't included). You have to specify this because the lengths of the months vary, so you have to add each of them individually. You have to account for February's changing length as well. Since 2018 is a leap year, this gives 31+29+31+30+31+30+31+31=244 days.
Then you add the remaining no of days to the 17th - which is 16 days.
The total is 2556+244+16 = 2817 days.
At least the weeks are consistent here on earth, which makes the next part a lot easier. You simply divide the number of days you obtained by 7 and get the remainder, and map it to the days of the week. The reference day will be 0, so you get
0 = Friday
1 = Saturday
2 = Sunday
3 = Monday
4 = Tuesday
5 = Wednesday
6 = Thursday.
So, you get 2817%7 = 3 ->Monday.
You can try this with any reference date. If you're working backwards from the reference date, there are some changes - the leap year calculation changes, and you have to start counting months and days from the other end, but once you account for those changes, the algorithm, in its basic form, still works.
As I said, you can use a spreadsheet for this calculation - once you're set it up, basically, you just have to enter the date and you'll get all the information you need. For my work, I calculate everything to the second, because track the movements of some celestial objects as well. The basis of this calculation is also the the time stamp mentioned here. I will get to that calculation in another article.
Hope this helps.
Until next time!

Friday, 14 September 2018

Caesar cipher - a simple program

I did some previous articles on cipers, the first one being simple subsitution ciphers. There, I talked about the Caesar cipher, where a simple shift is used for encoding. The code given below is for a simple program for the purpose.

The code is in c++. First, the program reads the input file (input.txt), code it, and output the coded version to output1.txt. Then, it reads the output1.txt file, decodes it, and outputs the result to output2.txt. Decoding is done by using -1*original shift as the shift.
The explanation follows the code.


/* 
 * File:   main.cpp
 * Author: 88415XC
 *
 * Created on September 14, 2018, 3:52 PM
 */

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

char line[250]={'\0'};                  //For input data
char line_c[250]={'\0'};                //For coded/decoded data
//array storing all simple and capital letters. this program is not case sensitive.
char code[2][26]={{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'},
{'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}};
//the 'value' assigned to the corresponding character in the code array.
int vals[26]={0,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};

/*
 * get the value corresponding to the char input
 */
int get_val(char character){
    int val = -1;
    for (int i=0; i<26;i++){
        if ((character==code[0][i])||(character==code[1][i])){
            val = vals[i];
            break;
        }
    }
    return val;
}

/*
 * gets the character corresponding to the char input
 */
char get_char(int val){
    char char_1 = '\0';
    for (int i=0; i<26;i++){
        if (val==vals[i]){
            char_1 = code[0][i];
            break;
        }
    }
    return char_1;
}

/*
 * Encodes/decodes the input data. 
 * All non-letter characters are ignored. All letters are shifted by the 
 * specified shift.
 */
void encode_caesar(int shift){
    int temp=0;
    char temp_1 = '\0';
    for (int i = 0; i<250; i++){
        if (line[i]=='\0') break;
        temp=get_val(line[i]);
        if (temp!=-1){
            temp = (temp+shift)%26;
            if (temp<0) temp=temp+26;
            temp_1=get_char(temp);
            line_c[i]=temp_1;
        }
        else{
            line_c[i]=line[i];
        }
    }
}

/*
 * 
 */
int main(int argc, char** argv) {
    ifstream input1;
    fstream output1;
    ofstream output2;
    
    input1.open("input1.txt",ios::in);
    output1.open("output1.txt",ios::out);
    
    //code input1 and put to output 1
    while(!(input1.eof())){
        memset(line,'\0',250);
        memset(line_c,'\0',250);
        input1>>line;
        encode_caesar(8);
        output1<<line_c<<endl;;
    }
    input1.close();
    output1.close();
    
    output1.open("output1.txt",ios::in);
    output2.open("output2.txt",ios::out);
    
    //decode output1 and put to output 2
    while(!(output1.eof())){
        memset(line,'\0',250);
        memset(line_c,'\0',250);
        output1>>line;
        encode_caesar(-8);
        output2<<line_c<<endl;
    }
    output1.close();
    output2.close();
    

    return 0;
}

First, the includes:
iostream: mainly for debugging.
fstream: for reading and writing to files.
cstring: because memset doesn't work without it (explanation will follow later.

Global variables: I hope the comments explain things sufficiently. The reason for using a 'val' array instead of using the array index of code is to allow more flexibility (as in, you could technically mix up the order as long as it's from 0-25 and make it a little more difficult to decode than the standard Caesar cipher)

get_val and get_char: These two functions are used to look up the values necessary in the arrays. Get_val looks up the number corresponding to the character it has to look up, and get_char does the opposite. Note that the program is not case sensitive, so get_char will return an upper case letter every time. In case of an error, get val returns -1, get char returns the null character (\0).

encode_caesar: This function handles one line at a time. It goes through the line one character at a time. Each character is converted to the corresponding value. If the value is -1, the same character is written to the coded string (line_c). If not, the shift (positive or negative) is added, and the modulus is taken. Here, you have to add the divisor (25) if the value is negative because '%' operator is actually the remainder from division. The resulting value is then converted back to a character and written to the coded string. As you probably noticed, numbers, punctuation marks, etc are not changed and written back as it is.

Moving on to the main program, it's basic functionality is as described in the introduction. Going step by step, first, the file handles are defined. I really need only 2 here, but I used three for the three files I was using. ifstream is for input, fstream is for both input and output, and ofstream is for output.
Then input.txt and output1.txt are opened, the former in input mode and the latter in output mode. The following while loop reads input.txt line by line until the end of the file. I should probably mention that c++ considers a space the end of the line, and the next word is considered another line. memset is used to clear line and line_c before reading the input to clear any of the previous line left in them. Once the line is read, encode_caesar is called with the required shift (8 in this case, but you can, technically, use any value you like). Then the coded line is written to output.txt.
The next part functions almost identically, with output1.txt as the input and output2.txt as the output. The only difference is, as this decodes the text, the previous shift multiplied by -1 is used with encode_caesar (-8 in this case).

I hope this is helpful. Until next time!



Monday, 30 July 2018

Conlanging adventures 001

As you may or may not know, I am writing a fantasy novel. Given this is a novel where the characters are sentient beings that communicate verbally, it logically follows that they use a language for the purpose. Given that this is in a fictional universe, chances are, the language will not be English.
At this juncture, I had to make a choice between the two paths that were before me:
1. Assume that the language that everyone speaks is the base language of the setting, so to speak, and make it equivalent to English.
2. Do the above, in a way, but create the language from scratch so that I can use the intricacies of the language in my writing (translated to English, obviously).
Guess which one I chose?
So, having chosen to go down the rabbit hole, I set about creating the language.

Origin

So, languages don't just show up out of nowhere. They tend to evolve out of something. There are few language isolates. So, I decided to give my language a family. This meant a parent language, and a bunch of other related languages. This was one of the best and one of the worst decisions I ever made.

Sound system

First of all, I didn't want this language to sound like English. That's boring. So, how did I go about it, you ask? Simple. Make the basic sounds in the language very different.
So, how did I go about it?
The first step is to get yourself an IPA chart. There are many wonderful ones on the internet (I found this one very useful). Step one, in the bag.
Step two is the difficult bit - figuring out how much of the chart to put into my language. Even this younger, naive me had the sense to not put the whole thing into my language. I also had the sense to let go of the sounds that I couldn't hope to make. Given that I am most decidedly not monolingual, that still left me with a lot of the chart. So, what is someone who is most decidedly not a robot to do?
In the end I made the tough decision to let go of most of the chart. The sounds I chose were:
Vowels: The schwa, a 'u' sound (like in pull), a 'e' sound, two 'o' sounds, two 'ah' sounds, and the 'er' sound (basically, schwa with a sort of r at the end. I don't do that in my natural English accent).
Consonants: Mostly what you get in English + ñ, unvoiced w, a trilled r, ts, and pf.
Sounds good, doesn't it? Certainly I thought so at the time. The consonants weren't too much of a problem, to tell you the truth. The vowel system, on the other hand, turned out to be a complete mess at least in this iteration.
Plus, there is this rather inconvenient detail; you see, single letters do not a language make. I had to make words out of them. This is where my lack of research caught up with me.
You see, most languages have these nifty patterns when it comes to how sounds can be put together. For example, in an English syllable, you can have up to three leading consonants (optional), one or two vowels (at least one vowel mandatory) and up to five trailing consonants (optional and thankfully some of them are silent). I didn't realise this at the time.
So I set about creating the words. How, you ask? Of course I used the tried and tested technique of using a random number generator to pick letters randomly. Don't get me wrong - I use a variation of this system now. The pitfall was that I neglected to fix the possible vowel and consonant combinations.
The end result was a near unpronounceable mess exacerbated by the insane vowel system. I used a random number generator with a normal distribution, with the vowels numbered 1-8, which made it worse. So the end result contained ample vowel and consonant bombs even with me selectively ignoring letters given by the random number generator. It sounded nothing like what I thought it would be.
So, after a while, and after some deliberation, I did the sensible thing, and started over.
This time I went with just seven distinct vowels. I dropped the /ts/, /pf/ and ñ, and added aspirated consonants instead. Then, the most sensible thing I did was to define the possible consonant and vowel clusters.
That done, I could actually create words. With a random number generator, true, but now they sounded like actual words.

Grammar

Ah, my favourite subject in school, the reason I absolutely loved learning languages (NOT TRUE!).
You see, trying to build a language without grammar is like trying to code without a compiler (yes I have heard of interpreted languages and assembly and machine code. May be this is a bad example? Meh, you get the idea).
The problem is that there is no such thing as a universal grammatical system. There are so many ways to format a message to another human being. For a conlang, you can go with any system you want to or even invent one. Not being a linguist, I decided to take the conservative route and get my inspiration from indo-European languages.
I had to narrow it down further - English falls into this category, as does Latin, Sanskrit, and Russian. I decided to draw inspiration from Latin at first.
There was a problem with that - I don't know any Latin. Still I really liked the case system and the flexibility it gave the sentence structure. So I decided to borrow that with no understanding of how it worked. I think ought to tell you, at this point, that my mother tongue is Sinhala.
So, continuing with the story. I had to learn how the case system worked. There were very few practical Latin courses online, so I decided to go for the next best thing - German. Don't facepalm too hard - a concussion will not be pleasant.
Still, it gave me some understanding, and I learned to say the very important phrases 'Hilfe, das Pferd frisst die heilige Kartoffel' and 'der grün Bär ist unsichtbar' (thanks, Duo!). That accomplished, I set out to get the language working.
I still had trouble with the case system. I was ploughing along when one day, the problem was magically solved by a random wiki walk. It allbegan when, for some reason I started researching Sinhala phonology, which lead to grammar, and boom, everything was cleared up just like that. You see, Sinhala has a case system. I've been speaking it my entire life. That cleared everything up instantly.
After that, there were a few more things I had to brush up to get the language working - deal with articles, expressing time (I decided to go with verb tenses), word order (not very important with cases, but you need the natural, default order. Plus there are times when some order is necessary even with cases), expressions, politeness levels, and so on.

Miscellaneous

Other things I had to consider include the number system (I came up with a pretty interesting one), colour names, and compound words. The latter was a fun outcome of learning German but how the words combine is somewhat different.

The extended family

I already mentioned that I came up with an extended language family. That could have remained a piece of trivia in the novel if not for one fact - every named character in the novel so far except for two speak languages belonging to this language family as their mother tongue.
So, yet again, I was at a crossroads. Yet again, I chose the more difficult option. No, I didn't flesh out these languages quite so much, but I did develop the basic phonology and grammar. Still, given what it added to the story - totally worth it.

Writing system

One more thing. Having created a language for a piece that is completely in a written medium, you would imagine that I was satisfied. Not so. There was no need to develop a writing system - no one was going to see it anyway. Yet I created it. Was it crazy? Undoubtedly. Was it worth it? Yes.
For this, I took my inspiration from Japanese, in a way. This is why I made the parent language a logography. The language in question ended up with an alphabet derived from characters in the parent language (simple explanation. The in-universe explanation is a little bit more complicated).
Perhaps you are wondering how I fitted a language with verb conjugation and a complex case system into a logography. I'll just say I took some inspiration from Chinese and Japanese. The end result is very functional if not exactly pretty, but it works.

Final thoughts

There are a lot of things I didn't talk about here, but I will get to them in a later article (accents, dialects, and all that stuff, for example). I touched on a lot of topics here, but I didn't go into detail - perhaps, that, too, will be another article.
In conclusion, it was difficult. Writing conversation in this language is still difficult for me. Still, given the layers it added to the story, to the characters, the character interactions, and all that, it was completely worth it.

Thank you for reading, and have a nice day!

Tuesday, 8 May 2018

The children of Mars - Chapter 02

I had to act, and act fast. Deimos was no mere supernatural creature, as you may have guessed, but a force of nature. A force of nature with the ability to induce pass panic and terror in people for no good reason. A force of nature who fed on people's fears that he amplified to feed himself. That in turn would make him more powerful.

True, a rampage by Deimos would produce a lot of magical energy in the world around, true. Whether I would be to harness it was another matter altogether. Besides, how would it affect other humans around me? What was the council even thinking?

First, I had to calm down, and think. I had dealt with a lot of crazy stuff in the last year, like university. This wasn't going to be much worse by comparison. Now, the first thing to do was to start monitoring the news. I turned the TV on. I simultaneously started looking for any traces of a mass panic online. Neither medium indicated anything of the sort. Was it outside the country? Deimos should have started doing something by now.

I kept monitoring the news, but there was no indication of anything like that. Finally, what happened was I fell asleep in front of the TV until I was woken up by the alarm. I seriously considered skipping lectures, but then I realised - Kathy was there. I couldn't possibly monitor all media, and my knowledge of this world was still limited. Kathy was already convinced I wasn't from this world, and if she did spill anything, chances are, no one would believe her. She would make a good ally.

By some miracle, I made it to university in one piece and in time. There was a short break during the first lecture, but I decided against speaking about it to Kathy at the time, because of two reasons - one, I slept through the lecture and woke up halfway through the break, and two, Kathy would want an explanation ranging from fifteen to thirty minutes long by my estimates, which wasn't possible during a ten minute break.

We usually had lunch together. This was starting to make me a little nervous. I hadn't checked the news properly in hours, and Kathy wasn't sitting near me. I pushed these thoughts away forcefully - they were just the sort of thing that would make me vulnerable to Deimos on the off chance he was hanging around here.

"What's up, Murdoch? you look a little nervous," said Ryan suddenly.

He was also one of my classmates - one who preferred to remain quiet most of the time.Why had he noticed my existence? Why had he bothered to comment on it? Was I becoming paranoid? No, I couldn't allow this. I was making myself the prime target for Deimos. Perhaps it was a good thing - but then, who would be able to stop him? Renard? No, he would be way too busy with his own schemes.

"Yeah, you look really pale," said Kathy, "did something happen?"

"No, no, nothing at all," I said, "I need to go to the library. Bye."

I ran away as quickly as I could - perhaps too quickly. The others stared after me. I didn't care. I had to get somewhere and check the news. Trying to team up with Kathy wasn't worth my sanity. I got to one of the library computers, and started browsing the news. All the news appeared to be political so far.

I was reaching this conclusion when I felt someone put their hand on my shoulder. Understandably, I reacted, the way I knew how to - by getting into position to cast a spell, before realising who I was facing. It was Kathy.

"Oh, it's just you. What are you doing here?" I asked.

"Are you going to tell me the truth? I know something's going on with you..."

"Actually, I wanted to talk to you as well," I said, "look, let's go somewhere a bit more private, okay? I get nervous when surrounded by people under these circumstances."

She looked slightly amused, but agreed. We met outside the library. She was waiting for me to start the conversation, obviously, so I did.

"First of all, you were right about me..."

"I knew it!"

"And, look, don't panic, but the council back home has released a supernatural entity into this world. It's dangerous, and I want your help finding it out, quickly. I've been here for about an year, so I'm not very good at looking for the news I want to find, plus I can't monitor everything all the time..."

"So, can't you use like, magic to find it?"

"No. I'm all out of magic. Wait, did you just believe everything I said, just like that?"

"I know you're not a liar. So, what are we looking for?"

"Mass panic, terror, or possibly one person or the other attacking people like crazy, perhaps?"

"Mass panic aside, I doubt the news will report anything like that. Are you sure this thing is in the country, to begin with? No one's going to report..."

"No, I'm not sure. Look, Kathy, just keep monitoring the situation, and if anything crops up, call me. You have my number, right? If you see anything of the sort, don't get involved. I might be able to use the magic leaking off it to do something, but don't fight it alone, or you might be possessed as well. Do you understand?"

Kathy nodded. She didn't seem concerned at all, which worried me a little. Did she even believe me? Was she leading me on, recording the conversation to go laugh at me later with friends? If that was the case, it would be her loss. They would know I was telling the truth when I warned them about Deimos. But what if this got out? I would be a wanted man here as well.

"It's going to be alright," said Kathy, suddenly, "You've dealt with this kind of thing before, right?"

"Y-yeah," I said, "we have ten minutes until the lecture. I'm going to check on the news until then."

I couldn't keep checking the news during the lecture. The tension, sleep deprivation, and post lunch sedation effect all took hold all at once, and I fell asleep shortly after the lecture began. Still, it was a terrible nap. I had nightmare after nightmare, and almost woke up screaming in the middle of the lecture hall. Luckily, I was fully awake before I could actually scream. The nap had been only ten minutes. I looked around the class in confusion. It was then that I saw Ryan. He was staring at me intensely.

He was the first one to notice my escalating panic during lunch as well. I inevitably jumped to the obvious conclusion. I had to be sure. If it was Ryan, he was only possessed. Still, if he was possessed by Deimos, I would be able to draw in some magical power. There should be some hanging around the area.

With my right hand still on the desk, I put my left hand under the desk, and tried to gather magical energy on to it. At first, there was no reaction, but soon, I started gathering magical energy. It wasn't a little - I could feel it surging through my arm - a felling I hadn't felt in about a year. There was no mistaking it. I kept going - I wanted to see exactly how much energy I could gather. I was watching the entire lecture hall intently. No one seemed to be reacting to it - not even Ryan.

The supply dried up pretty soon. I had gathered enough magical power to regain some base level powers, hopefully. A spell to locate Deimos would take more power than I managed to gather, but this confirmed my suspicions. Ryan was likely possessed by Deimos.

Now, I was wide awake. I was barely paying attention to the lecture, but Ryan seemed quite focused on it - a significant anomaly given his nature. There was a short break during the lecture, and I went out with the others as usual. So did Ryan. I didn't try to speak to him, but I watched his quite intently. The break was quite short, and the lecture resumed son afterwards, and I watched Ryan all through it.

Once the lecture finished, Kathy dragged me out by the arm. That was definitely going to get me teased to hell and back afterwards, but there was no reasoning with Kathy in this mood - because she was definitely worried about something.

"Stop staring at Ryan. Everyone's starting to notice it," she said, the moment she dragged me outside the class, "What's going on with you?"

"Did you notice anything odd about him?"

"What? No, I didn't notice - wait, are you trying to say he's whatever you're looking for? He doesn't look particularly terrified or panicked..."

"But he's good at sensing it - at least he noticed me panicking rather quickly. That's odd, don't you think, especially given the type of guy he is?"

"It's not that odd," said Kathy, "pull yourself together. This is getting ridiculous..."

"I know for a fact that Deimos was in that classroom," I said, "or, at least..."

"What's going on with you?" asked Ellis, "you were glaring at Ryan the entire time. Did something happen?"

This was another of my friends. He wasn't really the type that would notice a lot of things.

"Wait, he was?" asked Ryan, "I didn't see - I mean, I noticed he was worried, but then I forgot all about it - what's going on?"

There was one way I could find Deimos, once and for all. It was risky, but at that time, I was desperate. I switched to my language.

"Deimos, I want to talk to you, alone."

None of the three people around me reacted. Kathy looked slightly puzzled, and Ryan and Ellis stared at each other. He was either disguising himself well, or he wasn't among the three people here. I tried absorbing magical energy again. There was a little of it around, but it wasn't enough to confirm the presence of Deimos. Perhaps he had already passed by here and left the class. I pushed the three around me out of the way and rushed back into the lecture hall. It was nearly empty. I got to my seat. There, I tried checking for magical energy again. The levels were residual. Either he had left, or he was hiding his presence very well.

What could I do? I stuffed the books back into my bag as fast as I could, and brushed past the three of them, without talking to them. Right now, I could not. I made it back to my room in record time. I wanted to be alone, I wanted to think. What could I do now? How was I going to get Deimos to reveal himself?

I was sitting on my bed, thinking, when I heard a familiar voice. I had heard it in the holding cells next to the lab ever so often before, so I recognised it right away.

"Did you miss me?"

"So you finally showed yourself. Tell me, who did you possess?"

"I'm not stupid. I just came to tell you something. I will possess you. I will make you suffer. You had your turn making my life hell, and I will do the same to you."

"Go ahead and do that," I said, getting to my feet, "this time, I will make sure no one but me can set you free."

"All in good time," he said.

"We need to talk..."

By then, Deimos was gone. During the conversation, I had managed to acquire a good amount of magical power leaking off him. True, it was nowhere near the levels I had back at home, but with this, I wouldn't be completely helpless. In addition to that, I knew I was his target.

So, what would Deimos do to hurt me? What did I fear the most? I feared nothing much, really - not in this world. While I was friends with Kathy and all of them, I didn't care for them. I did care about my grades, but the exams weren't an immediate threat, and anyway Deimos would have to possess multiple professors for that to work. He could try to injure me physically, but he had made no such attempt. How was he going to hurt me?

I was pacing up and down in my room when suddenly, Another hologram appeared in my room. It was the head of the council, finally making contact with me. I stopped in my tracks, and waited for him to speak. I wanted to hear what he had to say for himself.

We glared at each other for a second, and then he decided to speak.

"I believe you are aware of the situation, at least partially."

I said nothing. I didn't even bother to nod in agreement. I waited for him to finish what he was saying.

"The keystones are all gone. Phobos is free in the city. He had caused minimal damage so far, but the chaos keeps spreading. I want you to come back as soon as you. For that end, we have released Deimos into the world you're in now, as per your request. You can use the energy he will leak to regain your powers, and return. You will return, contain Phobos, repair the keystones, and then you can go back to that world to recapture Deimos."

I didn't say anything.

"What is your reply?"

"I will do what I think is right."

"The right thing to do is to save your country from this disaster, like you did..."

"Please don't waste my time. The discussion is over, President. Please close the hologram."

He didn't - at least not right away. I glared at him for about a second, at which point he did turn it off. It was then that the reality of my situation came crashing down on me again. I crashed on my bed, and stayed there, staring at the ceiling. I don't know how long I stayed that way, and I don't know when I fell asleep like that, driven by pure mental exhaustion, with the room's light still on. All I know was that I was still there in the exact same position I went to sleep in when the alarm went off in the morning the next day.

I forced myself to go to lectures the next day. Deimos would be there, surely. I was already on the lookout for his presence as I entered the campus. I could feel the residual energy left behind as I walked in to the building. I certainly felt his presence in the lecture hall. He was definitely there, and he had apparently grown in power.

I did get a few strange looks from Kathy and co when I walked in, but that was expected. I nodded to them as I took my seat. Kathy came and sat next to me. Before she could speak, the lecturer came in. I was glad - I was convinced Deimos would possess someone close to me, and I needed time to study the situation.

Now the magical levels were back to residual levels. I was listening to the lecture, but scanning the rest of the class at the same time, while drawing in the magical power I could. I still didn't have enough for a search spell, but with my improved baseline sensitivity, I was starting to sense that it came from the front row, near Ryan and Ellis. Now I had to figure out how to draw Deimos away from them.

I never got so far. The moment the lecturer announced the break, Ryan suddenly leapt onto his chair and jumped over it, right at me and Kathy. I knew what it was right away, but before my conscious mind could process what was happening, I had jumped to cover Kathy, and both our chairs fell backwards, leaving the two us, and now Ryan on the floor. Ryan rolled off, and immediately got to his feet, brandishing a pen in a perfect ice-pick grip.

------------------------------------END OF CHAPTER TWO-----------------------------------------

None of the characters or places described in this work are representative of any real people, incidents, or the like.

Please do not post this story on other sites or on any other media. Instead, add the link to this blog post.

Thank you for reading.

How to write a character who is smarter than you

We all have that one character (or few) who is significantly smarter than the writer. So, as a writer, how do you write such a character con...